From gamito at gmail.com  Thu Feb  1 00:05:28 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 23:05:28 +0000
Subject: [Tutor] Why this error ?
Message-ID: <45C120B8.2060104@gmail.com>

Hi,

I have this code:

import MySQLdb

    conn = MySQLdb.connect (host = "localhost", user = "testuser", 
passwd = "testpass", db = "test")
    cursor = conn.cursor ()
    cursor.execute ("SELECT VERSION()")
    row = cursor.fetchone ()
    print "server version:", row[0]
    cursor.close ()
    conn.close ()

that gives me the error:
"./mysql.py: line 3: syntax error near unexpected token `('
./mysql.py: line 3: `   conn = MySQLdb.connect (host = "localhost", user 
= "testuser", passwd = "testpass", db = "test")'
"

Why is this ?
I can't imagine.

Any help would be appreciated.

Warm Regards,
M?rio Gamito

From john at fouhy.net  Thu Feb  1 00:22:37 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 1 Feb 2007 12:22:37 +1300
Subject: [Tutor] Why this error ?
In-Reply-To: <45C120B8.2060104@gmail.com>
References: <45C120B8.2060104@gmail.com>
Message-ID: <5e58f2e40701311522h6457d21bl56bf0a2cf1744649@mail.gmail.com>

On 01/02/07, M?rio Gamito <gamito at gmail.com> wrote:
> import MySQLdb
>
>     conn = MySQLdb.connect (host = "localhost", user = "testuser",
> passwd = "testpass", db = "test")
>     cursor = conn.cursor ()
>     cursor.execute ("SELECT VERSION()")
>     row = cursor.fetchone ()
>     print "server version:", row[0]
>     cursor.close ()
>     conn.close ()
>
> that gives me the error:
> "./mysql.py: line 3: syntax error near unexpected token `('
> ./mysql.py: line 3: `   conn = MySQLdb.connect (host = "localhost", user
> = "testuser", passwd = "testpass", db = "test")'
> "

Your indentation is wrong.  Try outdenting all your code so it all
starts in the same column, and see if that helps.

-- 
John.

From gamito at gmail.com  Thu Feb  1 00:23:49 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 23:23:49 +0000
Subject: [Tutor] Why this error ?
In-Reply-To: <b4e894c70701311511i72f09101lea7cd2321153171f@mail.gmail.com>
References: <45C120B8.2060104@gmail.com>
	<b4e894c70701311511i72f09101lea7cd2321153171f@mail.gmail.com>
Message-ID: <45C12505.2020500@gmail.com>

Hi,

Asrarahmed Kadri wrote:
> could you try:
> 'host'='localhost'
>  
> I mean put all the parameters with quotes, I guess that might be a cause 
> of the error.
>  
> conn = MySQLdb.connect ('host' = "localhost", 'user' = "testuser",
> 'passwd'= "testpass", 'db' = "test")
No, unfortunately the problem remains, but thanks anyway.

Warm Regards,
M?rio Gamito


> 
>  
> On 1/31/07, *M?rio Gamito* <gamito at gmail.com <mailto:gamito at gmail.com>> 
> wrote:
> 
>     Hi,
> 
>     I have this code:
> 
>     import MySQLdb
> 
>        conn = MySQLdb.connect (host = "localhost", user = "testuser",
>     passwd = "testpass", db = "test")
>        cursor = conn.cursor ()
>        cursor.execute ("SELECT VERSION()")
>        row = cursor.fetchone ()
>        print "server version:", row[0]
>        cursor.close ()
>        conn.close ()
> 
>     that gives me the error:
>     "./mysql.py: line 3: syntax error near unexpected token `('
>     ./mysql.py: line 3: `   conn = MySQLdb.connect (host = "localhost",
>     user
>     = "testuser", passwd = "testpass", db = "test")'
>     "
> 
>     Why is this ?
>     I can't imagine.
> 
>     Any help would be appreciated.
> 
>     Warm Regards,
>     M?rio Gamito
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> -- 
> To HIM you shall return.


From gamito at gmail.com  Thu Feb  1 00:33:23 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 23:33:23 +0000
Subject: [Tutor] Why this error ?
In-Reply-To: <5e58f2e40701311522h6457d21bl56bf0a2cf1744649@mail.gmail.com>
References: <45C120B8.2060104@gmail.com>
	<5e58f2e40701311522h6457d21bl56bf0a2cf1744649@mail.gmail.com>
Message-ID: <45C12743.5080602@gmail.com>

Hi,

> Your indentation is wrong.  Try outdenting all your code so it all
> starts in the same column, and see if that helps.
Ok, now i have:

import MySQLdb

conn = MySQLdb.connect('host' = "localhost", 'user' = "testuser", 
'passwd' = "testpass", 'db' = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

but the problem remains :-(

Any ideas ?

Warm Regards,
M?rio Gamito

From dyoo at hkn.eecs.berkeley.edu  Thu Feb  1 00:37:11 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 31 Jan 2007 15:37:11 -0800 (PST)
Subject: [Tutor] Why this error ?
In-Reply-To: <45C12505.2020500@gmail.com>
References: <45C120B8.2060104@gmail.com>
	<b4e894c70701311511i72f09101lea7cd2321153171f@mail.gmail.com>
	<45C12505.2020500@gmail.com>
Message-ID: <Pine.LNX.4.64.0701311533230.9276@hkn.eecs.berkeley.edu>

>> I mean put all the parameters with quotes, I guess that might be a cause
>> of the error.
>>
>> conn = MySQLdb.connect ('host' = "localhost", 'user' = "testuser",
>> 'passwd'= "testpass", 'db' = "test")
> No, unfortunately the problem remains, but thanks anyway.


It's supposed to be without quotes on the keyword argument names.

     conn = MySQLdb.connect (host = "localhost",
                             user = "testuser",
                             passwd = "testpass",
                             db = "test")

It is very good that you're showing us literal error messages.  There is 
something very funky looking in the error message you're showing us:

     "./mysql.py: line 3: syntax error near unexpected token `(

That does NOT look like a Python error message.  It looks like a shell 
error message from bash.  Double check that you're running the script with 
Python.

From john at fouhy.net  Thu Feb  1 00:37:17 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 1 Feb 2007 12:37:17 +1300
Subject: [Tutor] Why this error ?
In-Reply-To: <45C12743.5080602@gmail.com>
References: <45C120B8.2060104@gmail.com>
	<5e58f2e40701311522h6457d21bl56bf0a2cf1744649@mail.gmail.com>
	<45C12743.5080602@gmail.com>
Message-ID: <5e58f2e40701311537s20c7ff62h6b5dd7c490bb9811@mail.gmail.com>

On 01/02/07, M?rio Gamito <gamito at gmail.com> wrote:
> Ok, now i have:
>
> import MySQLdb
>
> conn = MySQLdb.connect('host' = "localhost", 'user' = "testuser",
> 'passwd' = "testpass", 'db' = "test")
> cursor = conn.cursor ()
> cursor.execute ("SELECT VERSION()")
> row = cursor.fetchone ()
> print "server version:", row[0]
> cursor.close ()
> conn.close ()
>
> but the problem remains :-(

This will fail because you have quote marks around 'host', 'user',
etc.  See the tutorial on keyword arguments..

-- 
John.

From gamito at gmail.com  Thu Feb  1 00:48:47 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 23:48:47 +0000
Subject: [Tutor] Why this error ?
In-Reply-To: <5e58f2e40701311537s20c7ff62h6b5dd7c490bb9811@mail.gmail.com>
References: <45C120B8.2060104@gmail.com>	<5e58f2e40701311522h6457d21bl56bf0a2cf1744649@mail.gmail.com>	<45C12743.5080602@gmail.com>
	<5e58f2e40701311537s20c7ff62h6b5dd7c490bb9811@mail.gmail.com>
Message-ID: <45C12ADF.3070300@gmail.com>

Hi,

> This will fail because you have quote marks around 'host', 'user',
> etc.  See the tutorial on keyword arguments..
Now i have:

import MySQLdb

conn = MySQLdb.connect(host = "localhost", user = "testuser", passwd = 
"testpass", db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

Same problem :(
Can't really figure why :(

Any ideas ?

Warm Regards,
M?rio Gamito

From carroll at tjc.com  Thu Feb  1 02:53:08 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 31 Jan 2007 17:53:08 -0800 (PST)
Subject: [Tutor] Regarding licensing GPL terms
In-Reply-To: <OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>
Message-ID: <Pine.LNX.4.44.0701311746290.437-100000@violet.rahul.net>

On Wed, 31 Jan 2007, Anup Rao wrote:

> Hi,
> 
> I am writing an application that uses a python libary  (a *.so file) 
> generated using SWIG.
> This library  makes direct system calls to the Linux kernel. 

The Linux kernel is not actually licensed under the standard GPL.  The 
copy of the GPL Linus releases it under includes the following very 
important modification:

 
   NOTE! This copyright does *not* cover user programs that use kernel
   services by normal system calls - this is merely considered normal use
   of the kernel, and does *not* fall under the heading of "derived work".

(There's a little more, but none relevant to your question.)

This means that your program is not, solely by virtue of making these 
calls, a derived work, subject to the GPL inheritance (a more neutral word 
than "virus").

> This raises three questions.

As I read it, the answers are:
 
> a> Does this mean that the library must be distributed under GPL terms?

No.  You can distribute it under any license you like, unrestricted by the 
GPL.

> b> Can I distribute it as LGPL?

Yes.  You can distribute it under any license you like, unrestricted by
the GPL.

(I'll skip on the PSF-license question, because I haven't read it in a 
while.)

Now, the standard disclaimer: Yes, I am a lawyer, but I'm not your lawyer, 
so don't take this as definitive legal advice.  If this is a critical 
issue for you on which you have substantial money riding, get a lawyer who 
will grille you for all possible material facts that could perhaps result 
in a different answer.


From eric at digitalert.net  Thu Feb  1 03:13:12 2007
From: eric at digitalert.net (Eric Pais)
Date: Wed, 31 Jan 2007 21:13:12 -0500
Subject: [Tutor] Why this error ?
In-Reply-To: <Pine.LNX.4.64.0701311533230.9276@hkn.eecs.berkeley.edu>
References: <45C120B8.2060104@gmail.com>	<b4e894c70701311511i72f09101lea7cd2321153171f@mail.gmail.com>	<45C12505.2020500@gmail.com>
	<Pine.LNX.4.64.0701311533230.9276@hkn.eecs.berkeley.edu>
Message-ID: <45C14CB8.5010705@digitalert.net>

Danny Yoo wrote:
>>> I mean put all the parameters with quotes, I guess that might be a cause
>>> of the error.
>>>
>>> conn = MySQLdb.connect ('host' = "localhost", 'user' = "testuser",
>>> 'passwd'= "testpass", 'db' = "test")
>>>       
>> No, unfortunately the problem remains, but thanks anyway.
>>     
>
>
> It's supposed to be without quotes on the keyword argument names.
>
>      conn = MySQLdb.connect (host = "localhost",
>                              user = "testuser",
>                              passwd = "testpass",
>                              db = "test")
>
> It is very good that you're showing us literal error messages.  There is 
> something very funky looking in the error message you're showing us:
>
>      "./mysql.py: line 3: syntax error near unexpected token `(
>
> That does NOT look like a Python error message.  It looks like a shell 
> error message from bash.  Double check that you're running the script with 
> Python.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   
Read what Danny Yoo said.

You are executing the file with

"./mysql.py" If you don't have the file starting with a shebang #! the script will be executed as a shell script, and not via python.

try putting this on the first line

#!/usr/bin/env python


From kent37 at tds.net  Thu Feb  1 03:40:32 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 31 Jan 2007 21:40:32 -0500
Subject: [Tutor] Regarding licensing GPL terms
In-Reply-To: <45C078A7.4040901@tds.net>
References: <OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>
	<45C078A7.4040901@tds.net>
Message-ID: <45C15320.3010304@tds.net>

Kent Johnson wrote:
> Anup Rao wrote:
>> c> Also, does any python script that uses this module have to be 
>> distributed under GPL , LGPL, or is the PSF license sufficient?
>>      My preference would be the PSF but I am not sure if it is ok.
> 
> The PSF itself discourages using the PSF license for non-PSF code. You 
> should probably consider a BSD or MIT license if you want something more 
> liberal than LGPL.

See http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq

Kent


From python at wardroper.org  Thu Feb  1 10:01:38 2007
From: python at wardroper.org (Alan Wardroper)
Date: Thu, 01 Feb 2007 01:01:38 -0800
Subject: [Tutor] Why this error ?
In-Reply-To: <mailman.10441.1170285834.32030.tutor@python.org>
References: <mailman.10441.1170285834.32030.tutor@python.org>
Message-ID: <45C1AC72.3090602@wardroper.org>

Other than outdenting the whole thing, are you using a 'non-standard' 
character set? Are you sure that '(' isn't an alternative encoding 
variant that python isn't recognising as a parenthesis? I've see nthat 
sometimes with Japanese or unicode encoding.
Just a thought...
(Just to check, I tried your code in ERIC and it ran fine for me once 
the indenting was fixed up)

> I have this code:
> 
> import MySQLdb
> 
>     conn = MySQLdb.connect (host = "localhost", user = "testuser", 
> passwd = "testpass", db = "test")
>     cursor = conn.cursor ()
>     cursor.execute ("SELECT VERSION()")
>     row = cursor.fetchone ()
>     print "server version:", row[0]
>     cursor.close ()
>     conn.close ()
> 
> that gives me the error:
> "./mysql.py: line 3: syntax error near unexpected token `('
> ./mysql.py: line 3: `   conn = MySQLdb.connect (host = "localhost", user 
> = "testuser", passwd = "testpass", db = "test")'

From zebra05 at gmail.com  Thu Feb  1 10:22:57 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Thu, 1 Feb 2007 11:22:57 +0200
Subject: [Tutor] Python 2.5 and PHP 5.2.0
Message-ID: <c7c6f3bc0702010122i4bfdfac6ue85583010177d84a@mail.gmail.com>

Hi Guys,

I need some wisdom from you. Is it possible to have PHP pages posting to
python scripts on the server side and returning values back to the calling
PHP files? Like, if my enterval.php form's action="think.py", would the two
scripts be able to talk to each other?

Thanks and Best Regards,

"Shortash"

-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070201/e9151563/attachment.html 

From rabidpoobear at gmail.com  Thu Feb  1 11:21:20 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 01 Feb 2007 04:21:20 -0600
Subject: [Tutor] Python 2.5 and PHP 5.2.0
In-Reply-To: <c7c6f3bc0702010122i4bfdfac6ue85583010177d84a@mail.gmail.com>
References: <c7c6f3bc0702010122i4bfdfac6ue85583010177d84a@mail.gmail.com>
Message-ID: <45C1BF20.1090303@gmail.com>

OkaMthembo wrote:
> Hi Guys,
>
> I need some wisdom from you. Is it possible to have PHP pages posting 
> to python scripts on the server side and returning values back to the 
> calling PHP files? Like, if my enterval.php form's action="think.py", 
> would the two scripts be able to talk to each other?
A client that is accessing your page never sees your PHP.
they just see an html file with a form in it.
when they submit the form, the python file will be called and its output 
will be displayed in the client's browser.
I can think of a roundabout way to do what you want:

PHP file returns a form to the client.  when this form is submitted to 
the py file, all of the data your py script needs is sent in the query 
string or whatever.
the py file does whatever it does, and then inside the html it returns 
to the client, it includes an instant redirect back to the PHP file with 
whatever
data you want to return.

However, this is a bad way to go about it.
You should be able to use python scripts on the server side without 
relying on the client's browser to pass data.
Not exactly sure how to, though.  May depend on your OS.

-Luke

From chris.arndt at web.de  Thu Feb  1 12:22:11 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 01 Feb 2007 12:22:11 +0100
Subject: [Tutor] Python 2.5 and PHP 5.2.0
In-Reply-To: <45C1BF20.1090303@gmail.com>
References: <c7c6f3bc0702010122i4bfdfac6ue85583010177d84a@mail.gmail.com>
	<45C1BF20.1090303@gmail.com>
Message-ID: <45C1CD63.1070809@web.de>

Luke Paireepinart schrieb:
> I can think of a roundabout way to do what you want:
> 
> PHP file returns a form to the client.  when this form is submitted to 
> the py file, all of the data your py script needs is sent in the query 
> string or whatever.
> the py file does whatever it does, and then inside the html it returns 
> to the client, it includes an instant redirect back to the PHP file with 
> whatever data you want to return.

The Python script can access the PHP page on the server directly, by
just making a request to localhost (if the PHP page is on the same
server). You could use urllib or some higher level HTTP client library
and pass the data to the PHP page either in a GET or POST request. The
PHP page looks just like any other web service to the Python script.
Based on the results from the request, it can then return HTML to the
client with a redirect to the PHP script, so the user can see the
updated data, or an error message.

Chris

From zebra05 at gmail.com  Thu Feb  1 12:53:41 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Thu, 1 Feb 2007 13:53:41 +0200
Subject: [Tutor] Python 2.5 and PHP 5.2.0
In-Reply-To: <45C1CD63.1070809@web.de>
References: <c7c6f3bc0702010122i4bfdfac6ue85583010177d84a@mail.gmail.com>
	<45C1BF20.1090303@gmail.com> <45C1CD63.1070809@web.de>
Message-ID: <c7c6f3bc0702010353h6d3279e5n93be9649210a3820@mail.gmail.com>

Thank you soooo much gentlemen, you have come to my aid very promptly indeed
:-)

I have to say, this is why i love Open Source; For the People, By the
People!

Thankee

"Shortash"

On 2/1/07, Christopher Arndt <chris.arndt at web.de> wrote:
>
> Luke Paireepinart schrieb:
> > I can think of a roundabout way to do what you want:
> >
> > PHP file returns a form to the client.  when this form is submitted to
> > the py file, all of the data your py script needs is sent in the query
> > string or whatever.
> > the py file does whatever it does, and then inside the html it returns
> > to the client, it includes an instant redirect back to the PHP file with
> > whatever data you want to return.
>
> The Python script can access the PHP page on the server directly, by
> just making a request to localhost (if the PHP page is on the same
> server). You could use urllib or some higher level HTTP client library
> and pass the data to the PHP page either in a GET or POST request. The
> PHP page looks just like any other web service to the Python script.
> Based on the results from the request, it can then return HTML to the
> client with a redirect to the PHP script, so the user can see the
> updated data, or an error message.
>
> Chris
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070201/59975bbb/attachment.htm 

From asdlinux at yahoo.se  Thu Feb  1 14:33:44 2007
From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=)
Date: Thu, 01 Feb 2007 14:33:44 +0100
Subject: [Tutor] The best way to implement a config file ???
Message-ID: <45C1EC38.7010904@yahoo.se>

Hi everyone

I'm learning to program python with wxpython gui. I have a application i 
made with several modules and i want to implement a configfile that 
applies to all those modules. Is there an easy way to do this ?  Can 
anyone point me in the right direction ?

Thanks
Magnus

From andreas at kostyrka.org  Thu Feb  1 15:09:16 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 1 Feb 2007 15:09:16 +0100
Subject: [Tutor] The best way to implement a config file ???
In-Reply-To: <45C1EC38.7010904@yahoo.se>
References: <45C1EC38.7010904@yahoo.se>
Message-ID: <20070201140916.GB26306@andi-lap.la.revver.com>

* Magnus Wirstr?m <asdlinux at yahoo.se> [070201 14:38]:
> Hi everyone
> 
> I'm learning to program python with wxpython gui. I have a application i 
> made with several modules and i want to implement a configfile that 
> applies to all those modules. Is there an easy way to do this ?  Can 
> anyone point me in the right direction ?

Depending upon your tastes:

ConfigFile => win.ini style config files.
shlex      => unix shell script style parsing.

Andreas

From kent37 at tds.net  Thu Feb  1 15:18:11 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Feb 2007 09:18:11 -0500
Subject: [Tutor] The best way to implement a config file ???
In-Reply-To: <20070201140916.GB26306@andi-lap.la.revver.com>
References: <45C1EC38.7010904@yahoo.se>
	<20070201140916.GB26306@andi-lap.la.revver.com>
Message-ID: <45C1F6A3.6060107@tds.net>

Andreas Kostyrka wrote:
> * Magnus Wirstr?m <asdlinux at yahoo.se> [070201 14:38]:
>> Hi everyone
>>
>> I'm learning to program python with wxpython gui. I have a application i 
>> made with several modules and i want to implement a configfile that 
>> applies to all those modules. Is there an easy way to do this ?  Can 
>> anyone point me in the right direction ?
> 
> Depending upon your tastes:
> 
> ConfigFile => win.ini style config files.
> shlex      => unix shell script style parsing.

You can also use a python module as a shared config; just define 
whatever values you want in Python code and import the module where you 
need it.

Kent


From gamito at gmail.com  Thu Feb  1 16:03:56 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Thu, 01 Feb 2007 15:03:56 +0000
Subject: [Tutor] Get variable values
Message-ID: <45C2015C.1070806@gmail.com>

Hi,

I'm new to Python, so forgive me the lame question.

I have this code (following my signature) and i'm trying to get the 
value of "content" and insert it into a MySQL database.

I've been reading the docs in www.python.org, but i can't find a solution.

Can someone help me, please ?

Warm Regards,
M?rio Gamito
--
def get_date(self, key):
         """Get (or update) the date key.

         We check whether the date the entry claims to have been changed is
         since we last updated this feed and when we pulled the feed off the
         site.

         If it is then it's probably not bogus, and we'll sort accordingly.

         If it isn't then we bound it appropriately, this ensures that
         entries appear in posting sequence but don't overlap entries
         added in previous updates and don't creep into the next one.
         """

         for other_key in ("updated", "modified", "published", "issued", 
"created"):
             if self.has_key(other_key):
                 date = self.get_as_date(other_key)
                 break
         else:
             date = None

         if date is not None:
             if date > self._channel.updated:
                 date = self._channel.updated
#            elif date < self._channel.last_updated:
#                date = self._channel.updated
         elif self.has_key(key) and self.key_type(key) != self.NULL:
             return self.get_as_date(key)
         else:
             date = self._channel.updated

         self.set_as_date(key, date)
         return date

     def get_content(self, key):
         """Return the key containing the content."""
         for key in ("content", "tagline", "summary"):
             if self.has_key(key) and self.key_type(key) != self.NULL:
                 return self.get_as_string(key)
         db = MySQLdb.connect(host="localhost", user="planet", 
passwd="secret", db="planet_geek")
         cursor = db.cursor()
         cursor.execute("INSERT INTO blog_posts (title) VALUES (key)")

         return ""

From sanelson at gmail.com  Thu Feb  1 16:07:04 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Thu, 1 Feb 2007 15:07:04 +0000
Subject: [Tutor] VOT - Similar list for Ruby?
Message-ID: <b6131fdc0702010707p85181fmd3464915f1ca644a@mail.gmail.com>

Hello all,

I may be about to switch jobs to an environment in which the main
utility language is Ruby.  I've found this group to be brilliant in
the last few years, and wondered if anyone on the list is also a Ruby
user, and could recommend a similarly helpful, patient and informative
list?

Thanks,

S.

From Mike.Hansen at atmel.com  Thu Feb  1 16:17:01 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 1 Feb 2007 08:17:01 -0700
Subject: [Tutor] VOT - Similar list for Ruby?
References: <b6131fdc0702010707p85181fmd3464915f1ca644a@mail.gmail.com>
Message-ID: <57B026980605A64F9B23484C5659E32E5B1968@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> 
> Hello all,
> 
> I may be about to switch jobs to an environment in which the main
> utility language is Ruby.  I've found this group to be brilliant in
> the last few years, and wondered if anyone on the list is also a Ruby
> user, and could recommend a similarly helpful, patient and informative
> list?
> 
> Thanks,
> 
> S.

When I started getting interested in Ruby, the only list I found was
Ruby Talk. See this page for a list of mail lists:

http://www.ruby-lang.org/en/community/mailing-lists/

Maybe someone deeper into the Ruby community might have a better
suggestion.

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From janos.juhasz at VELUX.com  Thu Feb  1 17:00:18 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 1 Feb 2007 17:00:18 +0100
Subject: [Tutor] Printing txt files in landscape from python
Message-ID: <OF4C19AC8B.4C709DAD-ONC1257275.0055ABEF-C1257275.0057EB15@velux.com>

Hi All,

do you have any idea, how I can send a txt file to the default printer in 
landscape view with python on windows.
I wanted to set up just the char size and the orientation of the printout.

thinking about
        os.system('notepad.exe /pt "%%%s"' % filename)


Yours sincerely,
______________________________
J?nos Juh?sz


From dyoo at hkn.eecs.berkeley.edu  Thu Feb  1 17:12:38 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 1 Feb 2007 08:12:38 -0800 (PST)
Subject: [Tutor] Get variable values
In-Reply-To: <45C2015C.1070806@gmail.com>
References: <45C2015C.1070806@gmail.com>
Message-ID: <Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>



On Thu, 1 Feb 2007, M?rio Gamito wrote:

> I'm new to Python, so forgive me the lame question.
>
> I have this code (following my signature) and i'm trying to get the
> value of "content" and insert it into a MySQL database.

Hi Mario,

Wait, wait, before we continue here: did you finally get things working 
from your last question?

     http://mail.python.org/pipermail/tutor/2007-February/052387.html

That thread was so full of confusion and a mixture of correct and 
incorrect advice that I felt a bit bad about it.


I'd feel better if I knew for certain that you were able to resolve what 
was going on.  Can you summarize the situation now?

From chris.arndt at web.de  Thu Feb  1 17:31:09 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 01 Feb 2007 17:31:09 +0100
Subject: [Tutor] The best way to implement a config file ???
In-Reply-To: <45C1EC38.7010904@yahoo.se>
References: <45C1EC38.7010904@yahoo.se>
Message-ID: <45C215CD.40204@web.de>

Magnus Wirstr?m schrieb:
> Hi everyone
> 
> I'm learning to program python with wxpython gui. I have a application i 
> made with several modules and i want to implement a configfile that 
> applies to all those modules. Is there an easy way to do this ?  Can 
> anyone point me in the right direction ?

The wxWidgets library has a config component built-in:

http://wxpython.wxcommunity.com/docs/api/wx.Config-class.html
http://wxwidgets.org/manuals/2.6.3/wx_wxconfigoverview.html#wxconfigoverview

Chris

From chris.arndt at web.de  Thu Feb  1 17:40:24 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 01 Feb 2007 17:40:24 +0100
Subject: [Tutor] Printing txt files in landscape from python
In-Reply-To: <OF4C19AC8B.4C709DAD-ONC1257275.0055ABEF-C1257275.0057EB15@velux.com>
References: <OF4C19AC8B.4C709DAD-ONC1257275.0055ABEF-C1257275.0057EB15@velux.com>
Message-ID: <45C217F8.2000304@web.de>

J?nos Juh?sz schrieb:
> do you have any idea, how I can send a txt file to the default printer in 
> landscape view with python on windows.

I assume that by "txt file", you mean a file containing ASCII text?

> I wanted to set up just the char size and the orientation of the printout.

Printers normally don't understand ASCII file sent to them, unless you
configure them (with some status codes) to do so.

Normally, the OS converts a text file sent to its printing system to
something the printer understands, like PostScript or PL5/6, and allows
you to set other options, e.g. setting landscape mode or choosing the
paper tray. Under windows, this is what the printer drivers are for,
under MAC OS X and Linux, this is done by the CUPS system.

Unfortunately, the specifics depend highly on the system, the printer
driver, the printer and the application that sends the file to the print
system.

> thinking about
>         os.system('notepad.exe /pt "%%%s"' % filename)

So this is actually your safest bet, but will only work under windows
obviously. Under Linux, you could try to use the 'a2ps' programm, but it
is not installed everywhere.

Chris

From gamito at gmail.com  Thu Feb  1 17:57:10 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Thu, 01 Feb 2007 16:57:10 +0000
Subject: [Tutor] Get variable values
In-Reply-To: <Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
References: <45C2015C.1070806@gmail.com>
	<Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
Message-ID: <45C21BE6.8060300@gmail.com>

Hi Danny,

> Wait, wait, before we continue here: did you finally get things working 
> from your last question?
Yes, i got things working.
That was just a test for python-MySQldb.

Now, i'm trying to get info from a python file, but i'm unable to get 
the variable values to insert in MySQL.

For example:

# Source field: save both url and value
                 if entry[key].has_key("value"):
                     self.set_as_string(key + "_name", entry[key].value)
                 if entry[key].has_key("url"):
                     self.set_as_string(key + "_link", entry[key].url)

                     db = MySQLdb.connect(host="localhost", 
user="planet", passwd="secret", db="planet_geek")
                     cursor = db.cursor()
                     cursor.execute("INSERT INTO blog_posts (title) 
VALUES ('entry[key].url')")

This isn't working.
It inserts nothing in the database.

How to retrieve the value of url ?

Warm Regards,
M?rio Gamito

From mail at timgolden.me.uk  Thu Feb  1 18:13:20 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 1 Feb 2007 17:13:20 -0000 (GMT)
Subject: [Tutor] Printing txt files in landscape from python
In-Reply-To: <OF4C19AC8B.4C709DAD-ONC1257275.0055ABEF-C1257275.0057EB15@velux.com>
References: <OF4C19AC8B.4C709DAD-ONC1257275.0055ABEF-C1257275.0057EB15@velux.com>
Message-ID: <47234.81.171.156.66.1170350000.squirrel@81.171.156.66>

> Hi All,
>
> do you have any idea, how I can send a txt file to the default printer in
> landscape view with python on windows.
> I wanted to set up just the char size and the orientation of the printout.
>
> thinking about
>         os.system('notepad.exe /pt "%%%s"' % filename)

Doesn't completely answer your question, but
have a look at this:

http://timgolden.me.uk/python/win32_how_do_i/print.html

and perhaps consider a ReportLab solution. It's ridiculously
difficult to set up the printing params construct under
Windows (just search for DEVMODE) so might well be easier
to use a PDF approach.

TJG

From dyoo at hkn.eecs.berkeley.edu  Thu Feb  1 19:35:38 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 1 Feb 2007 10:35:38 -0800 (PST)
Subject: [Tutor] Get variable values
In-Reply-To: <45C21BE6.8060300@gmail.com>
References: <45C2015C.1070806@gmail.com>
	<Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
	<45C21BE6.8060300@gmail.com>
Message-ID: <Pine.LNX.4.64.0702011023300.10432@hkn.eecs.berkeley.edu>



>> Wait, wait, before we continue here: did you finally get things working 
>> from your last question?
>
> Yes, i got things working. That was just a test for python-MySQldb.

Hi Mario,

Ok, good.  Next time, make it more clear to the group that things worked 
out fine, to close the thread.  Remember, we can't read your mind: make it 
explicit.

Otherwise, people will continue to try to help you with something that you 
don't have problems with anymore.  *grin*



>                     db = MySQLdb.connect(host="localhost", 
> user="planet", passwd="secret", db="planet_geek")
>                     cursor = db.cursor()
>
>                     cursor.execute("INSERT INTO blog_posts (title)
> VALUES ('entry[key].url')")
>
> This isn't working.
> It inserts nothing in the database.


There are two things you need to consider:

    1.  "Autocommit" mode is off.  That is, by default, your database 
access is transactioned.  That means that if you don't commit, the 
database rolls any changes right back out as soon as the connection 
closes.  See:

     http://www.amk.ca/python/writing/DB-API.html


    2.  String literals are really string literals.  That is, the code as 
written above will insert the literal string "entry[key].url" as a title.

Use prepared statements.  See:

     http://mail.python.org/pipermail/tutor/2003-April/022010.html

for an example.


There's also a third thing I'd suggest: abstract our the database-creation 
into a separate function.  You're probably going to be opening connections 
in several places in your code: keep the connection-open logic in a single 
place so you can more easily change configurations.

If it's possible, pull out the code that touches the database into a 
separate module layer.  People on the list can talk about this more if 
you'd like.

If you have more questions, please free to ask.

From gamito at gmail.com  Thu Feb  1 19:55:31 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Thu, 01 Feb 2007 18:55:31 +0000
Subject: [Tutor] Get variable values
In-Reply-To: <Pine.LNX.4.64.0702011023300.10432@hkn.eecs.berkeley.edu>
References: <45C2015C.1070806@gmail.com>
	<Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
	<45C21BE6.8060300@gmail.com>
	<Pine.LNX.4.64.0702011023300.10432@hkn.eecs.berkeley.edu>
Message-ID: <45C237A3.9090003@gmail.com>

Hi,

Danny Yoo wrote:
> Ok, good.  Next time, make it more clear to the group that things worked 
> out fine, to close the thread.  Remember, we can't read your mind: make 
> it explicit.
> 
> Otherwise, people will continue to try to help you with something that 
> you don't have problems with anymore.  *grin*
Ok.


>    1.  "Autocommit" mode is off.  That is, by default, your database 
> access is transactioned.  That means that if you don't commit, the 
> database rolls any changes right back out as soon as the connection 
> closes.  See:
> 
>     http://www.amk.ca/python/writing/DB-API.html
> 
> 
>    2.  String literals are really string literals.  That is, the code as 
> written above will insert the literal string "entry[key].url" as a title.
Yes, i know, i'm a long time PHP programmer.
I was just testing.


> Use prepared statements.  See:
> 
>     http://mail.python.org/pipermail/tutor/2003-April/022010.html
> 
> for an example.
Yes, i know too.


> There's also a third thing I'd suggest: abstract our the 
> database-creation into a separate function.  You're probably going to be 
> opening connections in several places in your code: keep the 
> connection-open logic in a single place so you can more easily change 
> configurations.
> 
> If it's possible, pull out the code that touches the database into a 
> separate module layer.  People on the list can talk about this more if 
> you'd like.
Yes, that will be for later.

For now, i'd just like to pull out the variables values, and i don't 
know how.
For those who may be interested it's about file __init.py__ from 
planetplanet code.

Warm Regards,
M?rio Gamito

From kent37 at tds.net  Thu Feb  1 20:36:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Feb 2007 14:36:53 -0500
Subject: [Tutor] Get variable values
In-Reply-To: <45C2015C.1070806@gmail.com>
References: <45C2015C.1070806@gmail.com>
Message-ID: <45C24155.2080806@tds.net>

M?rio Gamito wrote:
> Hi,
> 
> I'm new to Python, so forgive me the lame question.
> 
> I have this code (following my signature) and i'm trying to get the 
> value of "content" and insert it into a MySQL database.
> 
> I've been reading the docs in www.python.org, but i can't find a solution.
> 
> Can someone help me, please ?

I keep looking at this and your other posts and I just don't understand 
what you are trying to do. What do you mean by "content"? Is this code 
part of some class? It looks like it is from a class that subclasses 
dict. Anyway more context both of code and of what you are trying to do 
might be helpful.

Kent

> 
> Warm Regards,
> M?rio Gamito
> --
> def get_date(self, key):
>          """Get (or update) the date key.
> 
>          We check whether the date the entry claims to have been changed is
>          since we last updated this feed and when we pulled the feed off the
>          site.
> 
>          If it is then it's probably not bogus, and we'll sort accordingly.
> 
>          If it isn't then we bound it appropriately, this ensures that
>          entries appear in posting sequence but don't overlap entries
>          added in previous updates and don't creep into the next one.
>          """
> 
>          for other_key in ("updated", "modified", "published", "issued", 
> "created"):
>              if self.has_key(other_key):
>                  date = self.get_as_date(other_key)
>                  break
>          else:
>              date = None
> 
>          if date is not None:
>              if date > self._channel.updated:
>                  date = self._channel.updated
> #            elif date < self._channel.last_updated:
> #                date = self._channel.updated
>          elif self.has_key(key) and self.key_type(key) != self.NULL:
>              return self.get_as_date(key)
>          else:
>              date = self._channel.updated
> 
>          self.set_as_date(key, date)
>          return date
> 
>      def get_content(self, key):
>          """Return the key containing the content."""
>          for key in ("content", "tagline", "summary"):
>              if self.has_key(key) and self.key_type(key) != self.NULL:
>                  return self.get_as_string(key)
>          db = MySQLdb.connect(host="localhost", user="planet", 
> passwd="secret", db="planet_geek")
>          cursor = db.cursor()
>          cursor.execute("INSERT INTO blog_posts (title) VALUES (key)")
> 
>          return ""
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From asdlinux at yahoo.se  Thu Feb  1 21:05:16 2007
From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=)
Date: Thu, 01 Feb 2007 21:05:16 +0100
Subject: [Tutor] The best way to implement a config file ???
In-Reply-To: <20070201140916.GB26306@andi-lap.la.revver.com>
References: <45C1EC38.7010904@yahoo.se>
	<20070201140916.GB26306@andi-lap.la.revver.com>
Message-ID: <45C247FC.7070700@yahoo.se>

Andreas Kostyrka skrev:
> * Magnus Wirstr?m <asdlinux at yahoo.se> [070201 14:38]:
>   
>> Hi everyone
>>
>> I'm learning to program python with wxpython gui. I have a application i 
>> made with several modules and i want to implement a configfile that 
>> applies to all those modules. Is there an easy way to do this ?  Can 
>> anyone point me in the right direction ?
>>     
>
> Depending upon your tastes:
>
> ConfigFile => win.ini style config files.
> shlex      => unix shell script style parsing.
>
> Andreas
>
>   
/ think i want win.ini style, I'm designing a configuration module that 
is going to write this file. I have not heard of shlex so i can really 
not judge if it suits my needs. I do like the kind of config file that 
can be editable with a editor if nessary. Anyone have an good example 
how to use ConfigFile to write a config file that stores strings and 
boolean settings. Sorry for my english....

Thanks
Magnus
/

From gamito at gmail.com  Thu Feb  1 21:10:28 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Thu, 01 Feb 2007 20:10:28 +0000
Subject: [Tutor] Get variable values
In-Reply-To: <45C24155.2080806@tds.net>
References: <45C2015C.1070806@gmail.com> <45C24155.2080806@tds.net>
Message-ID: <45C24934.7000601@gmail.com>

Hi,

> I keep looking at this and your other posts and I just don't understand 
> what you are trying to do. What do you mean by "content"? Is this code 
> part of some class? It looks like it is from a class that subclasses 
> dict. Anyway more context both of code and of what you are trying to do 
> might be helpful.
Ok, so here it is.
Planetplanet relies basicly on two files.
__init.py__
http://pastebin.com/872998

and cache.py:
http://pastebin.com/873004

They both interact.

Planetplanet is a blog agregater, aka a planet, like 
http://www.planetgeek.org

What i'm trying to do is to fetch the values of the variables such as 
the blog's URLs, title of the articles, authors names, etc. and insert 
them into MySQL.

What i can't figure is how to get the variables values from the code.
I've been studying Python during the afternoon, i know Java, so they're 
not that different in the concept, but i can't see how in this 
particular case to retrieve the values of all that variables.

Any help would be appreciated.

Warm Regards,
M?rio Gamito

From kent37 at tds.net  Thu Feb  1 21:39:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Feb 2007 15:39:40 -0500
Subject: [Tutor] The best way to implement a config file ???
In-Reply-To: <45C247FC.7070700@yahoo.se>
References: <45C1EC38.7010904@yahoo.se>	<20070201140916.GB26306@andi-lap.la.revver.com>
	<45C247FC.7070700@yahoo.se>
Message-ID: <45C2500C.4040307@tds.net>

Magnus Wirstr?m wrote:
> / think i want win.ini style, I'm designing a configuration module that 
> is going to write this file. I have not heard of shlex so i can really 
> not judge if it suits my needs. I do like the kind of config file that 
> can be editable with a editor if nessary. Anyone have an good example 
> how to use ConfigFile to write a config file that stores strings and 
> boolean settings. Sorry for my english....

http://effbot.org/librarybook/configparser.htm

There are also a bunch of third-party modules that are supposed to be 
better than ConfigParser in some way:
http://wiki.python.org/moin/ConfigParserShootout

Kent


From dyoo at hkn.eecs.berkeley.edu  Thu Feb  1 21:56:00 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 1 Feb 2007 12:56:00 -0800 (PST)
Subject: [Tutor] Get variable values
In-Reply-To: <45C237A3.9090003@gmail.com>
References: <45C2015C.1070806@gmail.com>
	<Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
	<45C21BE6.8060300@gmail.com>
	<Pine.LNX.4.64.0702011023300.10432@hkn.eecs.berkeley.edu>
	<45C237A3.9090003@gmail.com>
Message-ID: <Pine.LNX.4.64.0702011250090.11177@hkn.eecs.berkeley.edu>

> For now, i'd just like to pull out the variables values, and i don't 
> know how. For those who may be interested it's about file __init.py__ 
> from planetplanet code.

Hi Mario,

Have you read either of the following yet?

     http://www.amk.ca/python/writing/DB-API.html

     http://mail.python.org/pipermail/tutor/2003-April/022010.html

The small examples in those two should be fairly direct, so I'm a little 
confused about why you are still stuck.


Please tell me if you've read those and yet don't understand what they are 
saying.  Alternatively, if you've read them but still feel that they are 
relevant to you, say that, and we'll try to elaborate why they should be 
applicable.

From dyoo at hkn.eecs.berkeley.edu  Thu Feb  1 21:58:40 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 1 Feb 2007 12:58:40 -0800 (PST)
Subject: [Tutor] Get variable values
In-Reply-To: <Pine.LNX.4.64.0702011250090.11177@hkn.eecs.berkeley.edu>
References: <45C2015C.1070806@gmail.com>
	<Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
	<45C21BE6.8060300@gmail.com>
	<Pine.LNX.4.64.0702011023300.10432@hkn.eecs.berkeley.edu>
	<45C237A3.9090003@gmail.com>
	<Pine.LNX.4.64.0702011250090.11177@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0702011258170.11177@hkn.eecs.berkeley.edu>

> Please tell me if you've read those and yet don't understand what they 
> are saying.  Alternatively, if you've read them but still feel that they 
> are relevant to you, say that, and we'll try to elaborate why they 
> should be applicable.

Errr.. substitute "relevant" with "irrelevant".  Sorry.  *grin*

From gamito at gmail.com  Thu Feb  1 22:22:49 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Thu, 01 Feb 2007 21:22:49 +0000
Subject: [Tutor] Get variable values
In-Reply-To: <Pine.LNX.4.64.0702011250090.11177@hkn.eecs.berkeley.edu>
References: <45C2015C.1070806@gmail.com>
	<Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
	<45C21BE6.8060300@gmail.com>
	<Pine.LNX.4.64.0702011023300.10432@hkn.eecs.berkeley.edu>
	<45C237A3.9090003@gmail.com>
	<Pine.LNX.4.64.0702011250090.11177@hkn.eecs.berkeley.edu>
Message-ID: <45C25A29.5000209@gmail.com>

Hi,

>     http://www.amk.ca/python/writing/DB-API.html
> 
>     http://mail.python.org/pipermail/tutor/2003-April/022010.html

Yes, i've read the two docs.
But my problem is more related with Python.

If you read my previous post with the links to the code, my doubt is how 
to get the values for "url", "content", "name", etc.

Warm Regards,
M?rio Gamito

From rdm at rcblue.com  Thu Feb  1 22:25:20 2007
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 01 Feb 2007 13:25:20 -0800
Subject: [Tutor] Python 2.5 Quick Reference
Message-ID: <20070201212531.893A71E400A@bag.python.org>

<http://rgruet.free.fr/PQR25/PQR2.5.html>
Is this reliable? (Looks good to me, but...)

Thanks,

Dick Moores


From alan.gauld at btinternet.com  Thu Feb  1 23:55:04 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Feb 2007 22:55:04 -0000
Subject: [Tutor] Get variable values
References: <45C2015C.1070806@gmail.com>
Message-ID: <eptr4c$a9q$1@sea.gmane.org>

> I have this code (following my signature) and i'm trying
> to get the value of "content" and insert it into a MySQL
> database.

>From where are you trying to get the value of content?
Its not clear from your code.

--
> def get_date(self, key):
>   ...

The fact that this has a self param,eter suggets this is
a method extracted from within a class? But without knowing
anything about that class its hard to know whats going on.

>      def get_content(self, key):
>         """Return the key containing the content."""

This doesn't return the key. It seems to return the content
corresponding to the key or an empty string. Is that what
you mean?

         for key in ("content", "tagline", "summary"):
             if self.has_key(key) and self.key_type(key) != self.NULL:
                 return self.get_as_string(key)

and if this works you will never do the insert.

So you only do the insert if you don't find a key, and
in that case you leave the value "summary" as the key
But that doesn't matter because you always execute exactly
the same INSERT statement - since its a hard coded string -
overwriting the previous one each time.

         db = MySQLdb.connect(host="localhost", user="planet",
passwd="secret", db="planet_geek")
         cursor = db.cursor()
         cursor.execute("INSERT INTO blog_posts (title) VALUES (key)")

         return ""

I think I'm confused, and I'm still not sure what you problem is.
We can't answer the question of why you don't get content
because thats done by the get_as_string() method which you
don't include in your listing.

Alan G. 



From dyoo at hkn.eecs.berkeley.edu  Fri Feb  2 00:35:52 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 1 Feb 2007 15:35:52 -0800 (PST)
Subject: [Tutor] Get variable values [Introduction to Planet RSS news
 aggregator]
In-Reply-To: <45C25A29.5000209@gmail.com>
References: <45C2015C.1070806@gmail.com>
	<Pine.LNX.4.64.0702010809090.10432@hkn.eecs.berkeley.edu>
	<45C21BE6.8060300@gmail.com>
	<Pine.LNX.4.64.0702011023300.10432@hkn.eecs.berkeley.edu>
	<45C237A3.9090003@gmail.com>
	<Pine.LNX.4.64.0702011250090.11177@hkn.eecs.berkeley.edu>
	<45C25A29.5000209@gmail.com>
Message-ID: <Pine.LNX.4.64.0702011451160.13780@hkn.eecs.berkeley.edu>



> Yes, i've read the two docs.
> But my problem is more related with Python.
>
> If you read my previous post with the links to the code, my doubt is how 
> to get the values for "url", "content", "name", etc.

Hi Mario,


After taking a much closer look at the code you mentioned here:

     http://pastebin.com/872998

it looks like you're supposed to have a "NewsItem" in hand.


Ok, wait.  I think I have a better idea of what you're trying to do.

Let me try to dissuade you from doing what you're doing.  *grin*


There should be no reason for mucking into the definition of Planet's 
implementation in order to make it do what you want: you should be able to 
just treat Planet as a library, and use it to do what you want. You should 
almost certainly not touch the internals of get_content(), if I understand 
what you're trying to do: that's private to the implementation of Planet 
and a very bad approach toward code reuse.


Rather than hack at NewsItem.get_content() to get it to insert into a 
database, it's probably a lot better to not modify Planet, but rather 
write new programs that use Planet.  Respect the library and treat it as 
if it were a resource.  If Scott James Remnant and Jeff Waugh take their 
code at:

     http://www.planetplanet.org/

and update it, or correct bugs, then you do not want to have to manually 
update your own code to patch things up the same way.



Concretely, if we want to take a feed and print out all the titles, we 
should not be modify the get_title() method of these news items in a 
private copy of the Planet library.  Rather, we can more simply use Planet 
as an external library:

#################################################
>>> import planet
>>> import ConfigParser
>>> config = ConfigParser.ConfigParser()
>>> p = planet.Planet(config)
>>> c = planet.Channel(p, 
"http://hashcollision.blogspot.com/feeds/posts/default")
>>> c.update()
>>> len(c.items())
25
#################################################


Ok, there are 25 items here.  Let's take a look at the titles:

##################################################
>>> for item in c:
...     print item.title
...
latex
in summation...
heresy
debugging test-case
new year
[text output truncated]
##################################################


Let's look at a particular item in the channel.

####################################################
>>> firstItem = c.items()[0]
>>> firstItem.title
'how not to write xml'
>>> firstItem.id
'tag:blogger.com,1999:blog-18302393.post-116249176169366001'
>>> firstItem.link
'http://hashcollision.blogspot.com/2006/11/how-not-to-write-xml.html'
>>> firstItem.summary
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "/usr/lib/python2.4/site-packages/planet/cache.py", line 279, in 
__getattr__
     raise AttributeError, key
AttributeError: summary
####################################################



Ok, so some things are not defined.  That's to be expected.  What things 
are defined for my news item?


####################################################
>>> firstItem.keys()
['updated', 'subtitle', 'title', 'author', 'author_name', 'order', 
'content', 'link', 'published', 'date', 'id_hash', 'id']
>>> firstItem.author
'Danny Yoo'
####################################################

(It really is _my_ news item.  *wink*)


According to the documentation of a NewsItem, you can expect to see the 
following (usually):

#####################################################################
id              Channel-unique identifier for this item.
id_hash         Relatively short, printable cryptographic hash of id
date            Corrected UTC-Normalised update time, for sorting.
order           Order in which items on the same date can be sorted.
hidden          Item should be hidden (True if exists).
title           One-line title (*).
link            Link to the original format text (*).
summary         Short first-page summary (*).
content         Full HTML content.
modified        Date the item claims to have been modified (*).
issued          Date the item claims to have been issued (*).
created         Date the item claims to have been created (*).
expired         Date the item claims to expire (*).
author          Name of the author (*).
publisher       Name of the publisher (*).
category        Category name (*).
comments        Link to a page to enter comments (*).
license         Link to the licence for the content (*).
source_name     Name of the original source of this item (*).
source_link     Link to the original source of this item (*).
#####################################################################


In able to see help documentation on planet, use the help() function at 
the prompt:

#################
>>> import planet
>>> help(planet)
#################


The documentation on Planet is a bit focused for developers: the authors 
expect you to already know Python before touching Planet, so you might 
have some rough going at first.


Does this help you get started?  Please ask more questions if you have 
them.

From cspears2002 at yahoo.com  Fri Feb  2 02:47:43 2007
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 1 Feb 2007 17:47:43 -0800 (PST)
Subject: [Tutor] adding columns of numbers
Message-ID: <945627.14453.qm@web51610.mail.yahoo.com>

I've been reading an old copy of "Programming Python"
and started to work on one of its challenges.  I have
a text file called table.txt:

1	5	10	2	1.0
2	10	20	4	2.0	3
3	15	30	8	3	2	1
4	20	40	16	4.0

I want to add each column of numbers, so the end
result would be a list like so:

[10, 50, 100, 30 , 10.0, 5, 1]

So far, I've been able to modify some code I found in
the book:

#!/usr/bin/python
import string

def summer(fileName):
	for lines_in_file in open(fileName, 'r').readlines():
		cols_in_file = string.split(lines_in_file)
		#print cols_in_file
		numCols = len(cols_in_file)
		sums = [0] * numCols
		#print sums
		cols = string.split(lines_in_file)
		#print cols
		for i in range(numCols):
			sums[i] = sums[i] + eval(cols[i])
	return sums
			
if __name__ == '__main__':
	import sys
	print summer(sys.argv[1])

Unfortunately, the output is:
[4, 20, 40, 16, 4.0]

The code can read the file, but the code doesn't sum
the numbers to produce a new list.  Any hints?




From john at fouhy.net  Fri Feb  2 03:10:19 2007
From: john at fouhy.net (John Fouhy)
Date: Fri, 2 Feb 2007 15:10:19 +1300
Subject: [Tutor] adding columns of numbers
In-Reply-To: <945627.14453.qm@web51610.mail.yahoo.com>
References: <945627.14453.qm@web51610.mail.yahoo.com>
Message-ID: <5e58f2e40702011810k1abc2b1cq5c34785f6460032e@mail.gmail.com>

On 02/02/07, Christopher Spears <cspears2002 at yahoo.com> wrote:
> I've been reading an old copy of "Programming Python"
> and started to work on one of its challenges.  I have
> a text file called table.txt:
>
> 1       5       10      2       1.0
> 2       10      20      4       2.0     3
> 3       15      30      8       3       2       1
> 4       20      40      16      4.0
>
> I want to add each column of numbers, so the end
> result would be a list like so:
>
> [10, 50, 100, 30 , 10.0, 5, 1]
>
> So far, I've been able to modify some code I found in
> the book:
>
> #!/usr/bin/python
> import string
>
> def summer(fileName):
>         for lines_in_file in open(fileName, 'r').readlines():
>                 cols_in_file = string.split(lines_in_file)
>                 #print cols_in_file
>                 numCols = len(cols_in_file)
>                 sums = [0] * numCols
>                 #print sums
>                 cols = string.split(lines_in_file)
>                 #print cols
>                 for i in range(numCols):
>                         sums[i] = sums[i] + eval(cols[i])
>         return sums
>
> if __name__ == '__main__':
>         import sys
>         print summer(sys.argv[1])
>
> Unfortunately, the output is:
> [4, 20, 40, 16, 4.0]

Compare the output with the input.  Where do you think the output came from?

Can you see how this is reflected in your code?

-- 
John.

From carroll at tjc.com  Fri Feb  2 03:14:17 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 1 Feb 2007 18:14:17 -0800 (PST)
Subject: [Tutor] Printing txt files in landscape from python
In-Reply-To: <OF4C19AC8B.4C709DAD-ONC1257275.0055ABEF-C1257275.0057EB15@velux.com>
Message-ID: <Pine.LNX.4.44.0702011806030.30671-100000@violet.rahul.net>

On Thu, 1 Feb 2007, [ISO-8859-1] J?nos Juh?sz wrote:

> do you have any idea, how I can send a txt file to the default printer in 
> landscape view with python on windows.
> I wanted to set up just the char size and the orientation of the printout.

I've gotten a crush on wxPython, now that it's nicely documented in the 
"wxPython in Action" book.

Take a look at http://wiki.wxpython.org/index.cgi/Printing for a 
discussion of printing.

Here's an example on printing, copying the code from "Code Sample - Easy 
Printing" on that page.


###################################

# this part copied from URL above:

from wx.html import HtmlEasyPrinting

class Printer(HtmlEasyPrinting):
    def __init__(self):
        HtmlEasyPrinting.__init__(self)

    def GetHtmlText(self,text):
        "Simple conversion of text.  Use a more powerful version"
        html_text = text.replace('\n\n','<P>')
        html_text = text.replace('\n', '<BR>')
        return html_text

    def Print(self, text, doc_name):
        self.SetHeader(doc_name)
        self.PrintText(self.GetHtmlText(text),doc_name)

    def PreviewText(self, text, doc_name):
        self.SetHeader(doc_name)
        HtmlEasyPrinting.PreviewText(self, self.GetHtmlText(text))

# now, using it:

text_to_print = """
Congress shall make no law respecting an establishment of religion,
or prohibiting the free exercise thereof; or abridging the freedom
of speech, or of the press; or the right of the people peaceably to
assemble, and to petition the government for a redress of
grievances.
"""

app = wx.PySimpleApp()  
p = Printer()
p.Print(text_to_print, "Amend 1")

###################################


This works, and gives you (well, the user) the option of printing 
landscape.

I'm not sure how to go about specifying a font.  I suspect you'll have to 
go with the more heavyweight "Code Sample - `(wx)Printout` Printing" 
examplefor that.



From kent37 at tds.net  Fri Feb  2 03:20:00 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Feb 2007 21:20:00 -0500
Subject: [Tutor] adding columns of numbers
In-Reply-To: <945627.14453.qm@web51610.mail.yahoo.com>
References: <945627.14453.qm@web51610.mail.yahoo.com>
Message-ID: <45C29FD0.2030909@tds.net>

Christopher Spears wrote:
> I've been reading an old copy of "Programming Python"
> and started to work on one of its challenges.  I have
> a text file called table.txt:
> 
> 1	5	10	2	1.0
> 2	10	20	4	2.0	3
> 3	15	30	8	3	2	1
> 4	20	40	16	4.0
> 
> I want to add each column of numbers, so the end
> result would be a list like so:
> 
> [10, 50, 100, 30 , 10.0, 5, 1]
> 
> So far, I've been able to modify some code I found in
> the book:
> 
> #!/usr/bin/python
> import string
> 
> def summer(fileName):
> 	for lines_in_file in open(fileName, 'r').readlines():
> 		cols_in_file = string.split(lines_in_file)
> 		#print cols_in_file
> 		numCols = len(cols_in_file)
> 		sums = [0] * numCols

This creates a new sums list for each line of the file. You need to 
initialize sums outside the loop. It's a little tricky to figure out how 
long sums really needs to be, since the lines are not all the same length.

> 		#print sums
> 		cols = string.split(lines_in_file)
> 		#print cols
> 		for i in range(numCols):
> 			sums[i] = sums[i] + eval(cols[i])

Instead of eval(cols[i]) it would be better to use float(cols[i]). It's 
usually a good idea to avoid eval().

Extra credit: Write summer() as a one-liner. :-)

(I know, I shouldn't be encouraging this. But it is a good exercise even 
if you wouldn't use it in production code. It would be pretty easy if 
the lines were all the same length...)

Kent

> 	return sums
> 			
> if __name__ == '__main__':
> 	import sys
> 	print summer(sys.argv[1])
> 
> Unfortunately, the output is:
> [4, 20, 40, 16, 4.0]
> 
> The code can read the file, but the code doesn't sum
> the numbers to produce a new list.  Any hints?
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From dyoo at hkn.eecs.berkeley.edu  Fri Feb  2 04:55:33 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 1 Feb 2007 19:55:33 -0800 (PST)
Subject: [Tutor] Get variable values [Introduction to Planet RSS news
 aggregator] (fwd)
Message-ID: <Pine.LNX.4.64.0702011955300.25362@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Fri, 02 Feb 2007 00:52:49 +0000
From: "[ISO-8859-1] M?rio Gamito" <gamito at gmail.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Get variable values  [Introduction to Planet RSS news
     aggregator]

Hi Danny,

Thank you for your insightful info.

Now i'm getting somewhere.

I've made this mysql.py teste script:

import planet
import ConfigParser
import MySQLdb

db = MySQLdb.connect(host="localhost", user="planet", passwd="secret", 
db="planet_geek")
cursor = db.cursor()

config = ConfigParser.ConfigParser()
p = planet.Planet(config)
c = planet.Channel(p, "http://blog.gamito.org/rss.php?blogId=1&profile=rss20")
c.update()
print len(c.items())

for item in c:
    print item.title
    cursor.execute("INSERT INTO blog_posts (title) VALUES (item.title)")
    print item.content

it prints the info from the feeds to the screen, but get an error from MySQL:
"File "sql.py", line 16, in ?
     cursor.execute("INSERT INTO blog_posts (title) VALUES (item.title)")
   File "/usr/local/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, 
in execute
     self.errorhandler(self, exc, value)
   File "/usr/local/lib/python2.4/site-packages/MySQLdb/connections.py", line 
35, in defaulterrorhandler
     raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1109, "Unknown table 'item' in field 
list")"

which means that the variable item.title is not recognized as a variable.

Any ideas ?

Warm Regards,
M?rio Gamito

From johan at accesstel.co.za  Fri Feb  2 05:07:40 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Fri, 2 Feb 2007 06:07:40 +0200
Subject: [Tutor] The best way to implement a config file ???
In-Reply-To: <45C1F6A3.6060107@tds.net>
Message-ID: <200702020402.l1242ij9006480@mail.mtn.co.za>

I've used two options in the past. The one is as Kent suggested, by using a
module that is imported by all others and share the values.
This doesn't allow for users to change the values, without changing the
code.

The second is to make use of a other file format. I used xml with all the
info in and extracted the values from there. It can be done with any type of
file, as long as you will know how to get the correct attributes for each
value.

HTH

Johan 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Kent Johnson
Sent: 01 February 2007 04:18 PM
To: Andreas Kostyrka
Cc: tutor at python.org
Subject: Re: [Tutor] The best way to implement a config file ???

Andreas Kostyrka wrote:
> * Magnus Wirstr?m <asdlinux at yahoo.se> [070201 14:38]:
>> Hi everyone
>>
>> I'm learning to program python with wxpython gui. I have a 
>> application i made with several modules and i want to implement a 
>> configfile that applies to all those modules. Is there an easy way to 
>> do this ?  Can anyone point me in the right direction ?
> 
> Depending upon your tastes:
> 
> ConfigFile => win.ini style config files.
> shlex      => unix shell script style parsing.

You can also use a python module as a shared config; just define whatever
values you want in Python code and import the module where you need it.

Kent

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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.18/662 - Release Date: 2007/01/31
03:16 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.18/662 - Release Date: 2007/01/31
03:16 PM
 


From gamito at gmail.com  Fri Feb  2 11:33:59 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Fri, 02 Feb 2007 10:33:59 +0000
Subject: [Tutor] Problems with date
Message-ID: <45C31397.1030401@gmail.com>

Hi,

I have this instruction

print item.date that outputs

(2007, 1, 23, 18, 35, 33, 1, 23, 0)

What i'd like to do is to convert it to, for example

23-01-2007 18:35:33

I've googled for an answer, but couldn't get there.
Something is escaping me.

Any help would be appreciated.

Warm Regards,
M?rio Gamito

From gamito at gmail.com  Fri Feb  2 11:51:56 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Fri, 02 Feb 2007 10:51:56 +0000
Subject: [Tutor] Problems with date
In-Reply-To: <45C31397.1030401@gmail.com>
References: <45C31397.1030401@gmail.com>
Message-ID: <45C317CC.3040905@gmail.com>

Hi,

Don't bother, i already got there :)

Warm Regards,
M?rio Gamito

M?rio Gamito wrote:
> Hi,
> 
> I have this instruction
> 
> print item.date that outputs
> 
> (2007, 1, 23, 18, 35, 33, 1, 23, 0)
> 
> What i'd like to do is to convert it to, for example
> 
> 23-01-2007 18:35:33
> 
> I've googled for an answer, but couldn't get there.
> Something is escaping me.
> 
> Any help would be appreciated.
> 
> Warm Regards,
> M?rio Gamito
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From kent37 at tds.net  Fri Feb  2 11:54:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 02 Feb 2007 05:54:23 -0500
Subject: [Tutor] Problems with date
In-Reply-To: <45C31397.1030401@gmail.com>
References: <45C31397.1030401@gmail.com>
Message-ID: <45C3185F.4080800@tds.net>

M?rio Gamito wrote:
> Hi,
> 
> I have this instruction
> 
> print item.date that outputs
> 
> (2007, 1, 23, 18, 35, 33, 1, 23, 0)
> 
> What i'd like to do is to convert it to, for example
> 
> 23-01-2007 18:35:33

That is a struct_time tuple such as would be returned by 
time.localtime() for example. Use time.strftime() to format it the way 
you want.
http://docs.python.org/lib/module-time.html

Kent


From gamito at gmail.com  Fri Feb  2 12:46:31 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Fri, 02 Feb 2007 11:46:31 +0000
Subject: [Tutor] Get variable values [Introduction to Planet RSS news
 aggregator] (fwd)
In-Reply-To: <Pine.LNX.4.64.0702011955300.25362@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0702011955300.25362@hkn.eecs.berkeley.edu>
Message-ID: <45C32497.7010803@gmail.com>

Hi,

Now, i got into something:
http://pastebin.com/873482

I'm already inserting data in MySQL.

Just two glitches:

1) This way i can only retrieve information from one blog. The one in 
the line
c = planet.Channel(p, 
"http://blog.gamito.org/rss.php?blogId=1&profile=rss20")

How can i retrieve from them all ?


2) I can't get the category and the URL :(


The code from __init.py__ and cache.py are here:
http://pastebin.com/872998
http://pastebin.com/873004


Any help would be appreciated.

Warm Regards,
M?rio Gamito

From dyoo at hkn.eecs.berkeley.edu  Fri Feb  2 16:29:20 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 2 Feb 2007 07:29:20 -0800 (PST)
Subject: [Tutor] Get variable values [Introduction to Planet RSS news
 aggregator] (fwd)
In-Reply-To: <45C32497.7010803@gmail.com>
References: <Pine.LNX.4.64.0702011955300.25362@hkn.eecs.berkeley.edu>
	<45C32497.7010803@gmail.com>
Message-ID: <Pine.LNX.4.64.0702020716190.18706@hkn.eecs.berkeley.edu>



On Fri, 2 Feb 2007, M?rio Gamito wrote:

> 1) This way i can only retrieve information from one blog. The one in
> the line
> c = planet.Channel(p,
> "http://blog.gamito.org/rss.php?blogId=1&profile=rss20")
>
> How can i retrieve from them all ?


Hi Mario,


Have you tried asking for help from the planet devel list?

     http://lists.planetplanet.org/mailman/listinfo/devel

From what I understand, Planet does it own on-disk caching already: it 
really does look like you're trying to implement something that Planet 
already does internally.


There's a refactored version of "Planet Planet" called "Planet Venus" 
which may be helpful for you:

     http://intertwingly.net/code/venus/docs/

I would strongly recommend looking closely at it, as it at least has some 
docs you can read.



> 2) I can't get the category and the URL :(

We can't tell what you're doing from this end.  Please make sure you're 
showing us what you mean when you run into difficulties --- showing code 
that demonstrates the problem is usually good.

From magoldfish at gmail.com  Fri Feb  2 21:16:19 2007
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Fri, 2 Feb 2007 15:16:19 -0500
Subject: [Tutor] curious struct problem
Message-ID: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>

I'm trying to read a binary file using struct.  This code works
interactively in the IPython shell, but not as a function invoked from a
command line (Windows).  Can someone point out my error?  Thanks!

import struct

def demux(filename, channel, nchannels):
   "Demultiplexes a stream of shorts (signed int16) from a file."
   fmt = str(nchannels) + 'h'
   sz = struct.calcsize(fmt)

   infile = open(fname, 'rb')
   chunk = infile.read(sz)
   while chunk:
      x = struct.unpack(fmt, chunk)
      chunk = infile.read(sz)
   infile.close()

#struct.error: unpack str size does no match format
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070202/0b0db4d4/attachment.html 

From gamito at gmail.com  Fri Feb  2 22:27:17 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Fri, 02 Feb 2007 21:27:17 +0000
Subject: [Tutor] Get variable values [Introduction to Planet RSS news
 aggregator] (fwd)
In-Reply-To: <Pine.LNX.4.64.0702020716190.18706@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0702011955300.25362@hkn.eecs.berkeley.edu>
	<45C32497.7010803@gmail.com>
	<Pine.LNX.4.64.0702020716190.18706@hkn.eecs.berkeley.edu>
Message-ID: <45C3ACB5.10902@gmail.com>

Hi,

Danny Yoo wrote:
> 
> Have you tried asking for help from the planet devel list?
Yes, but the list is comfortably numb :(


>  From what I understand, Planet does it own on-disk caching already: it 
> really does look like you're trying to implement something that Planet 
> already does internally.
Yes it does.
But I want to put the feeds data into the database to make pagination 
(as is, in planetplanet once a new article arrives, the last goes to the 
oblivion), subscribe only certain categories from a blog, censor some 
nasty article, etc.
Planetplanet doesn't have nothing of this.


> There's a refactored version of "Planet Planet" called "Planet Venus" 
> which may be helpful for you:
Yes, i know, i've already its docs.

Regards,
M?rio Gamito

From dyoo at hkn.eecs.berkeley.edu  Sat Feb  3 00:09:43 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 2 Feb 2007 15:09:43 -0800 (PST)
Subject: [Tutor] curious struct problem
In-Reply-To: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>
References: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0702021508010.18059@hkn.eecs.berkeley.edu>



On Fri, 2 Feb 2007, Marcus Goldfish wrote:

> I'm trying to read a binary file using struct.  This code works
> interactively in the IPython shell, but not as a function invoked from a
> command line (Windows).  Can someone point out my error?  Thanks!

Hi Marcus,

There is something very suspicious in the code.  You don't happen to have 
any global variables in your program, do you?

Let me underline what you might want to look at.


> def demux(filename, channel, nchannels):
             ^^^^^^^^

>  infile = open(fname, 'rb')
                  ^^^^^


Good luck!

From alan.gauld at btinternet.com  Sat Feb  3 00:24:48 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Feb 2007 23:24:48 -0000
Subject: [Tutor] curious struct problem
References: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>
Message-ID: <eq0h85$kok$1@sea.gmane.org>


"Marcus Goldfish" <magoldfish at gmail.com> wrote

> interactively in the IPython shell, but not as a function invoked 
> from a
> command line (Windows).  Can someone point out my error?  Thanks!

One problem I dsee is that the function does not return anything.
It stores it in a local variable x which is garbage collected when
the function exits.

Could that be the problem?

It would help if you tell us exactly how it doesn't work.
Do you get an error message? If so what - exactly?
Is the data written anyplace? Is the format wrong?
What exactly is the problem we are trying to diagnose?
Without specific information we are just guessing.

HTH,

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

> import struct
>
> def demux(filename, channel, nchannels):
>   "Demultiplexes a stream of shorts (signed int16) from a file."
>   fmt = str(nchannels) + 'h'
>   sz = struct.calcsize(fmt)
>
>   infile = open(fname, 'rb')
>   chunk = infile.read(sz)
>   while chunk:
>      x = struct.unpack(fmt, chunk)
>      chunk = infile.read(sz)
>   infile.close()
>
> #struct.error: unpack str size does no match format
>


--------------------------------------------------------------------------------


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



From bgailer at alum.rpi.edu  Sat Feb  3 00:58:39 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 02 Feb 2007 15:58:39 -0800
Subject: [Tutor] curious struct problem
In-Reply-To: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>
References: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>
Message-ID: <45C3D02F.4030308@alum.rpi.edu>

Marcus Goldfish wrote:
> I'm trying to read a binary file using struct.  This code works 
> interactively in the IPython shell, but not as a function invoked from 
> a command line (Windows).  

> Can someone point out my error?  Thanks!
Not without more information:
  What are you entering on the command line?
  What do you enter in the IPython shell to run the function?

>
> import struct
>
> def demux(filename, channel, nchannels):
>    "Demultiplexes a stream of shorts (signed int16) from a file."
>    fmt = str(nchannels) + 'h'
>    sz = struct.calcsize(fmt)
>
>    infile = open(fname, 'rb')
>    chunk = infile.read(sz)
>    while chunk:
>       x = struct.unpack(fmt, chunk)
>       chunk = infile.read(sz)
>    infile.close()
>
> #struct.error: unpack str size does no match format
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
510-978-4454


From asdlinux at yahoo.se  Sun Feb  4 20:51:22 2007
From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=)
Date: Sun, 04 Feb 2007 20:51:22 +0100
Subject: [Tutor] How to make ftplib show progress while uploading a large
	file
Message-ID: <45C6393A.7040201@yahoo.se>

Hi all

I'm workinga on a program that will upload a large file to a server 
using ftp. I'm using ftplib to do this. I'm using a gui with wxpython 
and i would like to have a progressbar showing in % how much have been 
transfered. I have been googling but i can't make any sense of what i 
have found. does anyone have a good example or could explain how to do 
this ?

Thanks
Magnus

From dkuhlman at rexx.com  Sun Feb  4 21:49:18 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 4 Feb 2007 12:49:18 -0800
Subject: [Tutor] How to make ftplib show progress while uploading a
	large file
In-Reply-To: <45C6393A.7040201@yahoo.se>
References: <45C6393A.7040201@yahoo.se>
Message-ID: <20070204204918.GA71936@cutter.rexx.com>

On Sun, Feb 04, 2007 at 08:51:22PM +0100, Magnus Wirstr?m wrote:
> Hi all
> 
> I'm workinga on a program that will upload a large file to a server 
> using ftp. I'm using ftplib to do this. I'm using a gui with wxpython 
> and i would like to have a progressbar showing in % how much have been 
> transfered. I have been googling but i can't make any sense of what i 
> have found. does anyone have a good example or could explain how to do 
> this ?

This code was originally given to me.  I've adapted it some.

Your will have to modify it for wxPython.  But, at least it gives
you some scaffolding to start with.  Note the "fancy" flag and
variable, which is probably what you want, not too sure.

Hope this helps.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
-------------- next part --------------
A non-text attachment was scrubbed...
Name: testupload.py
Type: text/x-python
Size: 3740 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070204/9c1e39c6/attachment.py 

From gizmo1 at gmail.com  Mon Feb  5 03:58:25 2007
From: gizmo1 at gmail.com (Gizmo)
Date: Sun, 4 Feb 2007 18:58:25 -0800
Subject: [Tutor] Why is this not working? Seems like a whitespace issue
Message-ID: <5d2e4d280702041858v5a867f0x353c4a2e86bffd53@mail.gmail.com>

Hello
I have a whole directory tree of RAR files that I wish to extract as a batch
job. In my real script I've used os.walk() and os.spawn*() but for
demonstration purposes have a look at the code below

>>> import os
>>> process=r"C:\Program Files\WinRAR\Rar.exe"
>>> startDir = r"C:\to burn"

>>> os.system(process+" x "+"C:\\to burn\\somemovie\\mymovie.rar"+"
"+startDir)

This doesnt work for me.. I get the error "  'C:\Program' is not recognized
as an internal or external command, operable program or batch file."
Notice that it says "C:\Program".... thats the incorrect path, the path is
supposed to be "C:\Program Files\..."

I realised the problem definitely because of the space between "Program" and
"Files"..
Actually, I even know the solution to an extend. In Windows command prompt,
whenever you have whitespaces in your path, you are expected to enclose the
whole path in double quotes; for example:

C:\>rar.exe x "C:\to burn\blah blah\"

I think this is the reason, but I am unsure. Your support is greatly
appreciated.

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070204/6bcfd099/attachment.htm 

From thian_seng at yahoo.com  Mon Feb  5 03:56:48 2007
From: thian_seng at yahoo.com (Wong Vincent)
Date: Sun, 4 Feb 2007 18:56:48 -0800 (PST)
Subject: [Tutor] Can I pause, stop or reset python virtual machine
Message-ID: <315727.14906.qm@web32601.mail.mud.yahoo.com>

Dear tutors,
    Hi. Does python provide any API to pause, stop or reset the virtual machine?
  Am currently building an application which will run a script file using os.popen().
  In order to allow user to run, stop and pause the application, is it advisable to do the abovementioned? or is there any better way of doing it?
   
  Too, can you please suggest me several hot forum for wxPython?I did sign up for SandBox, but my post has got no reply for +/- 1 week already.
   
  Thanks all.....
   
  Best regards 
  Vincent :D

 
---------------------------------
Be a PS3 game guru.
Get your game face on with the latest PS3 news and previews at Yahoo! Games.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070204/18561eb9/attachment.html 

From necmettin.begiter at gmail.com  Mon Feb  5 09:41:30 2007
From: necmettin.begiter at gmail.com (Necmettin Begiter)
Date: Mon, 5 Feb 2007 10:41:30 +0200
Subject: [Tutor] Why is this not working? Seems like a whitespace issue
In-Reply-To: <5d2e4d280702041858v5a867f0x353c4a2e86bffd53@mail.gmail.com>
References: <5d2e4d280702041858v5a867f0x353c4a2e86bffd53@mail.gmail.com>
Message-ID: <200702051041.30354.necmettin.begiter@gmail.com>

05 ?ub 2007 Pts 04:58 tarihinde, Gizmo ?unlar? yazm??t?: 
> Hello
> I have a whole directory tree of RAR files that I wish to extract as a
> batch job. In my real script I've used os.walk() and os.spawn*() but for
> demonstration purposes have a look at the code below
>
> >>> import os
> >>> process=r"C:\Program Files\WinRAR\Rar.exe"
> >>> startDir = r"C:\to burn"
> >>>
> >>> os.system(process+" x "+"C:\\to burn\\somemovie\\mymovie.rar"+"
>
> "+startDir)
>
> This doesnt work for me.. I get the error "  'C:\Program' is not recognized
> as an internal or external command, operable program or batch file."
> Notice that it says "C:\Program".... thats the incorrect path, the path is
> supposed to be "C:\Program Files\..."
>
> I realised the problem definitely because of the space between "Program"
> and "Files"..
> Actually, I even know the solution to an extend. In Windows command prompt,
> whenever you have whitespaces in your path, you are expected to enclose the
> whole path in double quotes; for example:
>
> C:\>rar.exe x "C:\to burn\blah blah\"
>
> I think this is the reason, but I am unsure. Your support is greatly
> appreciated.
>
> Thanks!
Do you actually need the strings to be "raw"? (r"")
Converting those strings to normal strings, you could easily make sure the 
space character (#32) is taken into account by escaping it:
process= "c:\\Program\ files\\WinRar\Rar.exe"

From necmettin.begiter at gmail.com  Mon Feb  5 09:45:07 2007
From: necmettin.begiter at gmail.com (Necmettin Begiter)
Date: Mon, 5 Feb 2007 10:45:07 +0200
Subject: [Tutor] Can I pause, stop or reset python virtual machine
In-Reply-To: <315727.14906.qm@web32601.mail.mud.yahoo.com>
References: <315727.14906.qm@web32601.mail.mud.yahoo.com>
Message-ID: <200702051045.07523.necmettin.begiter@gmail.com>

05 ?ub 2007 Pts 04:56 tarihinde, Wong Vincent ?unlar? yazm??t?: 
> Dear tutors,
>     Hi. Does python provide any API to pause, stop or reset the virtual
> machine? Am currently building an application which will run a script file
> using os.popen(). In order to allow user to run, stop and pause the
> application, is it advisable to do the abovementioned? or is there any
> better way of doing it?
In your "virtual machine", are you asking the user for a filename? Because if 
you are, if you have a dialog or whatever that asks the user for a filename, 
that point is where the "virtual machine" waits.

From alan.gauld at btinternet.com  Mon Feb  5 09:59:38 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Feb 2007 08:59:38 -0000
Subject: [Tutor] Can I pause, stop or reset python virtual machine
References: <315727.14906.qm@web32601.mail.mud.yahoo.com>
Message-ID: <eq6rm1$4te$1@sea.gmane.org>

"Wong Vincent" <thian_seng at yahoo.com> wrote 

> Hi. Does python provide any API to pause, 
> stop or reset the virtual machine?

Can you explain a little bit more about what you mean?
Are those 3 separate things? If so whjat is the difference 
between stop and pause? Does reset mean restart the 
running script or restart the interpreter? Or do you just 
mean you want to stop and restart the application?

>  Am currently building an application which will run 
> a script file using os.popen().  In order to allow user 
> to run, stop and pause the application, 

So you have an application, A that runs a script B 
using popen. Now, do you want to run,stop and 
pause A or B?

And are A and B both written in Python?

> ...is there any better way of doing it?

Once we have a clearer view of what "it" is we might 
be able to answer. I suspect what you want can be done, 
but I'm just not clear on what exactly you mean.

>  Too, can you please suggest me several hot forum 
> for wxPython? I did sign up for SandBox, but my post 
> has got no reply for +/- 1 week already.

Usually a Sandbox is a play area, you wouldn't expect 
a reply.  There is a wxPython mailing list which is probably 
a better place to ask questions about wxPython. It is very active.
The gmane archive is here:

http://news.gmane.org/gmane.comp.python.wxpython

Alan G.



From alan.gauld at btinternet.com  Mon Feb  5 10:09:30 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Feb 2007 09:09:30 -0000
Subject: [Tutor] Why is this not working? Seems like a whitespace issue
References: <5d2e4d280702041858v5a867f0x353c4a2e86bffd53@mail.gmail.com>
Message-ID: <eq6s8h$70k$1@sea.gmane.org>


"Gizmo" <gizmo1 at gmail.com> wrote

>>>> import os
>>>> process=r"C:\Program Files\WinRAR\Rar.exe"
>>>> startDir = r"C:\to burn"
>>>> os.system(process+" x "+"C:\\to burn\\somemovie\\mymovie.rar"+"
> "+startDir)
>
> This doesnt work for me.. I get the error "  'C:\Program' is not 
> recognized

> whenever you have whitespaces in your path, ...enclose the
> whole path in double quotes; for example:

You got the right problem. The solution is to enclose your process
string in single quotes (or tripple quotes if you prefer!) That way 
your
double quotes will be passed through untouched.

It would make your code slightly easier to maintain if you were
more consistent in the approach though. In some places you use
raw strings in others double escaped strings. That could lead
to confusion later.

Just a thought,

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



From yozara at terra.es  Mon Feb  5 10:29:29 2007
From: yozara at terra.es (Zara)
Date: Mon, 05 Feb 2007 10:29:29 +0100
Subject: [Tutor] Why is this not working? Seems like a whitespace issue
References: <5d2e4d280702041858v5a867f0x353c4a2e86bffd53@mail.gmail.com>
Message-ID: <j4uds21fmkvdanlko795j52k1al6tol9fm@4ax.com>

On Sun, 4 Feb 2007 18:58:25 -0800, Gizmo <gizmo1 at gmail.com> wrote:

>Hello
>I have a whole directory tree of RAR files that I wish to extract as a batch
>job. In my real script I've used os.walk() and os.spawn*() but for
>demonstration purposes have a look at the code below
>
>>>> import os
>>>> process=r"C:\Program Files\WinRAR\Rar.exe"

You may try
... process=r'"C:\Program Files\WinRAR\Rar.exe"'
(It is your original string, surrounde by simple quotes)

>>>> startDir = r"C:\to burn"
>
>>>> os.system(process+" x "+"C:\\to burn\\somemovie\\mymovie.rar"+"
>"+startDir)
>
>This doesnt work for me.. I get the error "  'C:\Program' is not recognized
>as an internal or external command, operable program or batch file."
>Notice that it says "C:\Program".... thats the incorrect path, the path is
>supposed to be "C:\Program Files\..."
<...>

I have not tried the soultion myself, but it is the same that must be
applied in other similar situation .

best regards,

zara


From magoldfish at gmail.com  Mon Feb  5 15:03:32 2007
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Mon, 5 Feb 2007 09:03:32 -0500
Subject: [Tutor] curious struct problem
In-Reply-To: <Pine.LNX.4.64.0702021508010.18059@hkn.eecs.berkeley.edu>
References: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>
	<Pine.LNX.4.64.0702021508010.18059@hkn.eecs.berkeley.edu>
Message-ID: <5e183f3d0702050603u415ad46ted9f23ff9493dbb9@mail.gmail.com>

On 2/2/07, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
> > I'm trying to read a binary file using struct.  This code works
> > interactively in the IPython shell, but not as a function invoked from a
> > command line (Windows).  Can someone point out my error?  Thanks!
>
> Hi Marcus,
>
> There is something very suspicious in the code.  You don't happen to have
> any global variables in your program, do you?
>
> Let me underline what you might want to look at.
>
>
> > def demux(filename, channel, nchannels):
>              ^^^^^^^^
>

Danny,
Sorry, I had a typo.  Attached below is the complete code actually copied
from my editor.  Notice that it doesn't do anything now, which is fine b.c.
I just want to troubleshoot the problem.  The error is reproduced as a
comment below the source.  As far as I know, there are no globals; I am
invoking this from a command line prompt: python demux.py foo.bin 1 1


# ---
import struct

def demux(fname, ch=1, nchan=1):
    fmt = str(nchan) + 'h'          # nchan of short (int16)
    blockSize = struct.calcsize(fmt)

    # file setup
    infile  = open(fname, 'rb')
    #outfile = open(fname + 'ch' + str(ch), 'wb')

    # iterate over data
    chunk = infile.read(blockSize)
    while chunk:
        x = struct.unpack(fmt, chunk)
        chunk = infile.read(blockSize)

    # file cleanup
    # outfile.close()
    infile.close()

# -------------------------------------------------------------------------
#   main()
#  -------------------------------------------------------------------------
def main(argv=None):
    if argv is None:
        printHelp()
    demux(argv[1], int(argv[2]), int(argv[3]))     # filename, ch, nchans


if __name__ == "__main__":
    import sys
    sys.exit(main(sys.argv))


# C:\python\python demux.py demux.py 1 1
# Traceback (most recent call last):
#   File "demux.py", line xx, in ?
#     sys.exit(main(sys.argv))
#   File "demux.py", line xx, in main
#     demux(argv[1], int(argv[2]), int(argv[3]))     # filename, ch, nchans
#   File "demux.py", line xx, in demux
#     x = struct.unpack(fmt, chunk)
# struct.error: unpack str size does not match format
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/913180b4/attachment.html 

From magoldfish at gmail.com  Mon Feb  5 15:12:21 2007
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Mon, 5 Feb 2007 09:12:21 -0500
Subject: [Tutor] curious struct problem
In-Reply-To: <Pine.LNX.4.64.0702021508010.18059@hkn.eecs.berkeley.edu>
References: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com>
	<Pine.LNX.4.64.0702021508010.18059@hkn.eecs.berkeley.edu>
Message-ID: <5e183f3d0702050612w734127ccn2d742a53add2d1f5@mail.gmail.com>

On 2/2/07, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> There is something very suspicious in the code.  You don't happen to have
> any global variables in your program, do you?


I think I found the problem: the last chunk read is incomplete, so there is
size(chunk) is not sufficient to unpack according to the format string.

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/45175972/attachment.htm 

From govindgoyal at gmail.com  Mon Feb  5 15:42:31 2007
From: govindgoyal at gmail.com (govind goyal)
Date: Mon, 5 Feb 2007 20:12:31 +0530
Subject: [Tutor] Coding for AP configuration
Message-ID: <f96f96bc0702050642lc1addfcxfba2629788afc96e@mail.gmail.com>

Hello,

I am a beginner in python.I am working as S/W tester relating to WI-FI
testing where we've to manually configure Access points(AP).
I want to write a Automated Scripts to configure my AP through HTTP.
Can any body suggest basic coding for this?

Thanks.
Best Regards,
Govind Goyal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/1e7df7dc/attachment.html 

From chris.arndt at web.de  Mon Feb  5 16:32:15 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Mon, 05 Feb 2007 16:32:15 +0100
Subject: [Tutor] Coding for AP configuration
In-Reply-To: <f96f96bc0702050642lc1addfcxfba2629788afc96e@mail.gmail.com>
References: <f96f96bc0702050642lc1addfcxfba2629788afc96e@mail.gmail.com>
Message-ID: <45C74DFF.4080102@web.de>

govind goyal schrieb:
> I want to write a Automated Scripts to configure my AP through HTTP.
> Can any body suggest basic coding for this?

Search the cheeseshop [1] for mechanoid and mechanize.


Chris

[1] http://cheeseshop.python.org/pypi/

From dyoo at WPI.EDU  Mon Feb  5 16:16:24 2007
From: dyoo at WPI.EDU (Daniel Yoo)
Date: Mon, 5 Feb 2007 10:16:24 -0500 (EST)
Subject: [Tutor] curious struct problem
In-Reply-To: <5e183f3d0702050612w734127ccn2d742a53add2d1f5@mail.gmail.com>
References: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com> 
	<Pine.LNX.4.64.0702021508010.18059@hkn.eecs.berkeley.edu>
	<5e183f3d0702050612w734127ccn2d742a53add2d1f5@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0702051015400.26816@CCC1.WPI.EDU>



On Mon, 5 Feb 2007, Marcus Goldfish wrote:

> I think I found the problem: the last chunk read is incomplete, so there 
> is size(chunk) is not sufficient to unpack according to the format 
> string.

Good!  I'm glad you found the problem.

From kent37 at tds.net  Mon Feb  5 16:59:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Feb 2007 10:59:52 -0500
Subject: [Tutor] Coding for AP configuration
In-Reply-To: <f96f96bc0702050642lc1addfcxfba2629788afc96e@mail.gmail.com>
References: <f96f96bc0702050642lc1addfcxfba2629788afc96e@mail.gmail.com>
Message-ID: <45C75478.90504@tds.net>

govind goyal wrote:
> Hello,
>  
> I am a beginner in python.I am working as S/W tester relating to WI-FI 
> testing where we've to manually configure Access points(AP).
> I want to write a Automated Scripts to configure my AP through HTTP.
> Can any body suggest basic coding for this?

You can use urllib or urllib2 to make HTTP requests from Python. Here is 
a tutorial:
http://www.voidspace.org.uk/python/articles/urllib2.shtml

Kent


From frank.hoffsummer at gmail.com  Mon Feb  5 19:55:37 2007
From: frank.hoffsummer at gmail.com (frank h.)
Date: Mon, 5 Feb 2007 19:55:37 +0100
Subject: [Tutor] timedelta doesnt do month
Message-ID: <60fae7c30702051055x1862df72le17559c50176f416@mail.gmail.com>

so what is the easiest way to to get to a list of months in a given
timeinterval, e.g.

>> startdate = datetime.date(2005,2,13)
>> enddate = datetime.date(2007,1,25)
>> delta = enddate - startdate
>> delta.days
711
>> delta.months
exceptions.AttributeError                            Traceback (most recent
call last)
AttributeError: 'datetime.timedelta' object has no attribute 'months'

I want to compute the "monthdifference" and so I can then iterate over the
months from my startdate to my enddate
what is the easiest way to accomplish this?
thanks for any insight you might have
-frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/ad992c5e/attachment.htm 

From alan.gauld at btinternet.com  Mon Feb  5 20:05:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Feb 2007 19:05:27 -0000
Subject: [Tutor] curious struct problem
References: <5e183f3d0702021216x755ee138wa3b874ce0f589c0d@mail.gmail.com><Pine.LNX.4.64.0702021508010.18059@hkn.eecs.berkeley.edu>
	<5e183f3d0702050603u415ad46ted9f23ff9493dbb9@mail.gmail.com>
Message-ID: <eq7v5u$tql$1@sea.gmane.org>

"Marcus Goldfish" <magoldfish at gmail.com> wrote

> I just want to troubleshoot the problem.  The error is reproduced as 
> a
> comment below the source.  As far as I know, there are no globals; I 
> am
> invoking this from a command line prompt: python demux.py foo.bin 1 
> 1

> def demux(fname, ch=1, nchan=1):
>    fmt = str(nchan) + 'h'          # nchan of short (int16)
>    blockSize = struct.calcsize(fmt)

Try a print statement here:

print fmt,' = ',blockSize

>    # file setup
>    infile  = open(fname, 'rb')
>    #outfile = open(fname + 'ch' + str(ch), 'wb')
>
>    # iterate over data
>    chunk = infile.read(blockSize)
>    while chunk:

And another print here

print chunk

Does chunk match the fmt/blockSize above?

Alan G 



From alan.gauld at btinternet.com  Mon Feb  5 20:08:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Feb 2007 19:08:40 -0000
Subject: [Tutor] Coding for AP configuration
References: <f96f96bc0702050642lc1addfcxfba2629788afc96e@mail.gmail.com>
Message-ID: <eq7vbv$bd$1@sea.gmane.org>

"govind goyal" <govindgoyal at gmail.com> wrote

> I am a beginner in python.I am working as S/W tester relating to 
> WI-FI

Welcome.

> testing where we've to manually configure Access points(AP).
> I want to write a Automated Scripts to configure my AP through HTTP.
> Can any body suggest basic coding for this?

That kind of depends on the API offered by your access points.
Assuming:
a) You are new to Python but not to programming, and
b) there is a web interface that you use manually then,

take a look at the urllib module documentation.
It allows you to send http messages to a server as if you were
using a browser.

HTH,


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



From kent37 at tds.net  Mon Feb  5 20:28:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Feb 2007 14:28:15 -0500
Subject: [Tutor] timedelta doesnt do month
In-Reply-To: <60fae7c30702051055x1862df72le17559c50176f416@mail.gmail.com>
References: <60fae7c30702051055x1862df72le17559c50176f416@mail.gmail.com>
Message-ID: <45C7854F.4050301@tds.net>

frank h. wrote:
> so what is the easiest way to to get to a list of months in a given 
> timeinterval, e.g.
> 
>  >> startdate = datetime.date(2005,2,13)
>  >> enddate = datetime.date(2007,1,25)
>  >> delta = enddate - startdate
>  >> delta.days
> 711
>  >> delta.months
> exceptions.AttributeError                            Traceback (most 
> recent call last)
> AttributeError: 'datetime.timedelta' object has no attribute 'months'
> 
> I want to compute the "monthdifference" and so I can then iterate over 
> the months from my startdate to my enddate
> what is the easiest way to accomplish this?

Because of the ambiguities of month arithmetic (what is 2005-1-31 plus 
one month?) datetime refuses to guess and does not support this. ("In 
the face of ambiguity, refuse the temptation to guess." - The Zen of 
Python) The third-party dateutil module is not as circumspect:

In [1]: import datetime

In [2]: startdate = datetime.date(2005,2,13)

In [3]: enddate = datetime.date(2007,1,25)

In [10]: from dateutil.relativedelta import relativedelta

In [11]: delta = relativedelta(months=+1)

In [16]: d = startdate

In [17]: while d <= enddate:
    ....:     print d
    ....:     d += delta
    ....:
    ....:
2005-02-13
2005-03-13
2005-04-13
2005-05-13
2005-06-13
2005-07-13
2005-08-13
2005-09-13
2005-10-13
2005-11-13
2005-12-13
2006-01-13
2006-02-13
2006-03-13
2006-04-13
2006-05-13
2006-06-13
2006-07-13
2006-08-13
2006-09-13
2006-10-13
2006-11-13
2006-12-13
2007-01-13

http://labix.org/python-dateutil

Kent


From frank.hoffsummer at gmail.com  Mon Feb  5 20:55:08 2007
From: frank.hoffsummer at gmail.com (frank h.)
Date: Mon, 5 Feb 2007 20:55:08 +0100
Subject: [Tutor] timedelta doesnt do month
In-Reply-To: <45C7854F.4050301@tds.net>
References: <60fae7c30702051055x1862df72le17559c50176f416@mail.gmail.com>
	<45C7854F.4050301@tds.net>
Message-ID: <60fae7c30702051155y62581c25h25859a5e1b5048a3@mail.gmail.com>

thanks kent for your fast and comprehensive answer!

On 2/5/07, Kent Johnson <kent37 at tds.net> wrote:
>
> frank h. wrote:
> > so what is the easiest way to to get to a list of months in a given
> > timeinterval, e.g.
> >
> >  >> startdate = datetime.date(2005,2,13)
> >  >> enddate = datetime.date(2007,1,25)
> >  >> delta = enddate - startdate
> >  >> delta.days
> > 711
> >  >> delta.months
> > exceptions.AttributeError                            Traceback (most
> > recent call last)
> > AttributeError: 'datetime.timedelta' object has no attribute 'months'
> >
> > I want to compute the "monthdifference" and so I can then iterate over
> > the months from my startdate to my enddate
> > what is the easiest way to accomplish this?
>
> Because of the ambiguities of month arithmetic (what is 2005-1-31 plus
> one month?) datetime refuses to guess and does not support this. ("In
> the face of ambiguity, refuse the temptation to guess." - The Zen of
> Python) The third-party dateutil module is not as circumspect:
>
> In [1]: import datetime
>
> In [2]: startdate = datetime.date(2005,2,13)
>
> In [3]: enddate = datetime.date(2007,1,25)
>
> In [10]: from dateutil.relativedelta import relativedelta
>
> In [11]: delta = relativedelta(months=+1)
>
> In [16]: d = startdate
>
> In [17]: while d <= enddate:
>     ....:     print d
>     ....:     d += delta
>     ....:
>     ....:
> 2005-02-13
> 2005-03-13
> 2005-04-13
> 2005-05-13
> 2005-06-13
> 2005-07-13
> 2005-08-13
> 2005-09-13
> 2005-10-13
> 2005-11-13
> 2005-12-13
> 2006-01-13
> 2006-02-13
> 2006-03-13
> 2006-04-13
> 2006-05-13
> 2006-06-13
> 2006-07-13
> 2006-08-13
> 2006-09-13
> 2006-10-13
> 2006-11-13
> 2006-12-13
> 2007-01-13
>
> http://labix.org/python-dateutil
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/afd9943b/attachment.htm 

From purdeaandrew at gmail.com  Mon Feb  5 21:52:40 2007
From: purdeaandrew at gmail.com (Andrew Purdea)
Date: Mon, 5 Feb 2007 22:52:40 +0200
Subject: [Tutor] best book?
Message-ID: <b51938f10702051252p58bd6e65p2ccf892ee71ad4c@mail.gmail.com>

Hi! what do you guys think that would be the best free book, or tutorial or
something to start learning python?
Something that can also focus on important differences from other languages,
and present why some choices made in the design are better then others. Not
just present the information, but also make it easyer to understand it ;-)
I have previous programming knowledge (Pascal/Delphi, C, Java, Assembler)
 Thanks
       Andrew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/0b4452b9/attachment.htm 

From sanelson at gmail.com  Mon Feb  5 21:54:27 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Mon, 5 Feb 2007 20:54:27 +0000
Subject: [Tutor] MapReduce
Message-ID: <b6131fdc0702051254p1cadaae2v985cffa8596ba5d8@mail.gmail.com>

Hello,

I have to give a presentation this week on how the MapReduce (of
Google and Hadoop fame) algorithm works.

I understand how map() works, and how reduce() works, and having read
the google papers, I have an idea of their implementation (which I
must say takes certain liberties with FP-derived terminology).

As I understand it, we have a "map" function which is passed a set of
key/value pairs, which, by applying a user function, produces an
intermediate set of key-value pairs.

I've come up with an example... return the url and how frequently
occurs if the url contains a given word.  I'm planning to pass a "map"
function an indexed list of urls:
>>> stuff
[(1, 'http://www.beer.com'), (2, 'http://www.ban-beer.com'), (3,
'http://www.bbc.co.uk'), (4, 'http://www.beer.com'), (5,
'http://wwww.kernel.org')]

And I have a map function with reverses the keys and values if the
word is present:

def myMap(stuff):
  return [(url, key) for key, url in stuff if "beer" in url]

This does as expected:

>>> myMap(stuff)
[('http://www.beer.com', 1), ('http://www.ban-beer.com', 2),
('http://www.beer.com', 4)]

What I want to do is now "group" these urls so that repeated urls have
as their "partner" a lsit of indexes.  To take a test example of the
method I have in mind:

def testGrouper(self):
    """Group occurences of a record together"""
    test_list = [('fred', 1), ('jim', 2), ('bill', 3), ('jim', 4)]
    grouped_list = [('fred', 1), ('jim', [2, 4]), ('bill' ,3)]
    self.assertEqual(myGroup(test_list), grouped_list)

I have seen some code which purports to do this, but I thought it was
ugly, and it seemed to return a generator object rather than a list.

I refactored it for clarity thus:

def myGroup(stuff):
  sorted_list = sorted(stuff)
  if not sorted_list:
    return
  reduce_key, reduce_list = sorted_list[0][0], sorted_list[0][1]
  for key, url in sorted_list[1:]:
    if key == reduce_key:
      reduce_list.append(value)
    else:
      yield (remote_key, remote_list)
      remote_key, remote_list = k, [v]
  yield(remote_key, remote_list)


Does this make sense?  I would like a clearer, more attractive way of
making the test pass.  If this can be done in functional style, even
better.

Your help is always appreciated!

S.

From sanelson at gmail.com  Mon Feb  5 23:22:04 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Mon, 5 Feb 2007 22:22:04 +0000
Subject: [Tutor] MapReduce
In-Reply-To: <b6131fdc0702051254p1cadaae2v985cffa8596ba5d8@mail.gmail.com>
References: <b6131fdc0702051254p1cadaae2v985cffa8596ba5d8@mail.gmail.com>
Message-ID: <b6131fdc0702051422y491e1261qfdcdb85cdaea2043@mail.gmail.com>

On 2/5/07, Steve Nelson <sanelson at gmail.com> wrote:
> What I want to do is now "group" these urls so that repeated urls have
> as their "partner" a lsit of indexes.  To take a test example of the
> method I have in mind:
>
> def testGrouper(self):
>     """Group occurences of a record together"""
>     test_list = [('fred', 1), ('jim', 2), ('bill', 3), ('jim', 4)]
>     grouped_list = [('fred', 1), ('jim', [2, 4]), ('bill' ,3)]
>     self.assertEqual(myGroup(test_list), grouped_list)

<snip>

> I would like a clearer, more attractive way of
> making the test pass.  If this can be done in functional style, even
> better.

I now have:

def myGroup(stuff):
  return [(key, map(lambda item: item[1], list(group))) for key, group
in groupby(sorted(stuff), lambda item: item[0] )]

Not sure I fully understand how groupby objects work, nor what a
sub-iterator is, though.  But I more or less understand it.

I understand I could use itemgetter() instead of the lambda...

Can anyone clarify?

S.

From pyro9219 at gmail.com  Mon Feb  5 23:46:43 2007
From: pyro9219 at gmail.com (Chris Hengge)
Date: Mon, 5 Feb 2007 14:46:43 -0800
Subject: [Tutor] Trying to get a feel
Message-ID: <c25107380702051446g594c1dc0sd034422282a67c9@mail.gmail.com>

I've asked this on the Turbogears list, but I thought I'd ask here since
there is a larger active user base from what I can tell.

Basically I'm trying to get an idea of how practical streaming data with
something like turbogears would be for going from the client (web site user)
to the server. I know alot of this is most likely based on the connection
speed, but I'll play with perfect world numbers for the connection speed.
I've got some stuff I stream using python, and I'm just trying to figure out
if the same could be essentially done using a website built on something
like turbogears using exposed methods?

Thanks for any feedback that can be offered.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/4719105c/attachment.htm 

From kent37 at tds.net  Tue Feb  6 00:58:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Feb 2007 18:58:44 -0500
Subject: [Tutor] MapReduce
In-Reply-To: <b6131fdc0702051422y491e1261qfdcdb85cdaea2043@mail.gmail.com>
References: <b6131fdc0702051254p1cadaae2v985cffa8596ba5d8@mail.gmail.com>
	<b6131fdc0702051422y491e1261qfdcdb85cdaea2043@mail.gmail.com>
Message-ID: <45C7C4B4.7030108@tds.net>

Steve Nelson wrote:
> On 2/5/07, Steve Nelson <sanelson at gmail.com> wrote:
>> What I want to do is now "group" these urls so that repeated urls have
>> as their "partner" a lsit of indexes.  To take a test example of the
>> method I have in mind:
>>
>> def testGrouper(self):
>>     """Group occurences of a record together"""
>>     test_list = [('fred', 1), ('jim', 2), ('bill', 3), ('jim', 4)]
>>     grouped_list = [('fred', 1), ('jim', [2, 4]), ('bill' ,3)]
>>     self.assertEqual(myGroup(test_list), grouped_list)
> 
> <snip>
> 
>> I would like a clearer, more attractive way of
>> making the test pass.  If this can be done in functional style, even
>> better.
> 
> I now have:
> 
> def myGroup(stuff):
>   return [(key, map(lambda item: item[1], list(group))) for key, group
> in groupby(sorted(stuff), lambda item: item[0] )]
> 
> Not sure I fully understand how groupby objects work, nor what a
> sub-iterator is, though.  But I more or less understand it.

Sub-iterator is just a way to refer to a nested iterator - groupby() 
yields tuples one of whose members is an iterator. Since groupby() is 
also an iterator (well, a generator actually), they call the nested 
iterator a sub-iterator.
> 
> I understand I could use itemgetter() instead of the lambda...
> 
> Can anyone clarify?

I have written an explanation of itemgetter and groupby here:
http://personalpages.tds.net/~kent37/blog/arch_m1_2005_12.html#e69

You can also do this operation easily with dicts (not tested!):

def myGroup(stuff):
   groups = {}
   for url, index in stuff:
     groups.setdefault(url, []).append(index)
   return sorted(groups.items())

Or a bit less opaque in Python 2.5, avoiding setdefault():
from collections import defaultdict
def myGroup(stuff):
   groups = defaultdict(list)
   for url, index in stuff:
     groups[url].append(index)
   return sorted(groups.items())

Kent


From tim at johnsons-web.com  Tue Feb  6 16:46:43 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Tue, 06 Feb 2007 15:46:43 +0000
Subject: [Tutor] Using __import__ and byte-compiling
Message-ID: <200702061546.43166.tim@johnsons-web.com>

I am currently using the __import__ function to do
conditional importing of modules, whose names are determined
at runtime.

It appears the __import__ does not handle byte-compiling,
or at least it is not being done in my current implementation. From reading 
the __import__ documentation, I don't see any options that handle 
byte-compiles implicitly.

It follows then that I might want to use the py_compile module
with the follow method: (pseudo code example follows)
## ====================================
if exists module.pyc and 
     (timestamp for module.pyc) < (timestamp for module.py)
  then compile module.py
else  ## module.pyc does not exist
  compile module.py
## ====================================
Or is there a python asset that handles this?
cheers
tim

-- 
Tim Johnson <tim at johnsons-web.com>

From tim at johnsons-web.com  Tue Feb  6 17:05:58 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Tue, 06 Feb 2007 16:05:58 +0000
Subject: [Tutor] Using __import__ and byte-compiling
In-Reply-To: <200702061546.43166.tim@johnsons-web.com>
References: <200702061546.43166.tim@johnsons-web.com>
Message-ID: <200702061605.58702.tim@johnsons-web.com>

I should add one thing: If the source module is in the same directory,
it *is* byte-compiled.
thanks
tim
On Tuesday 06 February 2007 03:46 pm, Tim Johnson wrote:
> I am currently using the __import__ function to do
> conditional importing of modules, whose names are determined
> at runtime.
>
> It appears the __import__ does not handle byte-compiling,
> or at least it is not being done in my current implementation. From reading
> the __import__ documentation, I don't see any options that handle
> byte-compiles implicitly.
>
> It follows then that I might want to use the py_compile module
> with the follow method: (pseudo code example follows)
> ## ====================================
> if exists module.pyc and
>      (timestamp for module.pyc) < (timestamp for module.py)
>   then compile module.py
> else  ## module.pyc does not exist
>   compile module.py
> ## ====================================
> Or is there a python asset that handles this?
> cheers
> tim

-- 
Tim Johnson <tim at johnsons-web.com>

From kent37 at tds.net  Tue Feb  6 03:49:09 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Feb 2007 21:49:09 -0500
Subject: [Tutor] best book?
In-Reply-To: <b51938f10702051252p58bd6e65p2ccf892ee71ad4c@mail.gmail.com>
References: <b51938f10702051252p58bd6e65p2ccf892ee71ad4c@mail.gmail.com>
Message-ID: <45C7ECA5.8070909@tds.net>

Andrew Purdea wrote:
> Hi! what do you guys think that would be the best free book, or tutorial 
> or something to start learning python?
> Something that can also focus on important differences from other 
> languages, and present why some choices made in the design are better 
> then others. Not just present the information, but also make it easyer 
> to understand it ;-)
> I have previous programming knowledge (Pascal/Delphi, C, Java, Assembler)

The official tutorial that comes with Python is a good quick intro for 
programmers. Dive Into Python is available on-line and has much more 
depth. Those and other good resources are listed here:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Cookbook is a good place to learn idiomatic Python. There is 
an on-line version here:
http://aspn.activestate.com/ASPN/Cookbook/Python

You can also hang out on this list or comp.lang.python, that might be 
the best way to get a sense for what makes Python different.

Kent


From carroll at tjc.com  Tue Feb  6 05:04:16 2007
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 5 Feb 2007 20:04:16 -0800 (PST)
Subject: [Tutor] How to make ftplib show progress while uploading a
 large file
In-Reply-To: <45C6393A.7040201@yahoo.se>
Message-ID: <Pine.LNX.4.44.0702051802590.26710-100000@violet.rahul.net>

On Sun, 4 Feb 2007, [ISO-8859-1] Magnus Wirstr?m wrote:

> I'm workinga on a program that will upload a large file to a server 
> using ftp. I'm using ftplib to do this. I'm using a gui with wxpython 
> and i would like to have a progressbar showing in % how much have been 
> transfered. I have been googling but i can't make any sense of what i 
> have found. does anyone have a good example or could explain how to do 
> this ?

Magnus --

When you installed wxPython, did you also download and install the "Docs, 
Demo, Samples, etc."?  There are great examples of nearly all wxPython 
dialogs, including ProgressDialog.

The hard part is going to get ftplib to talk to your dialog.  You're 
uploading.  ftplib's download methods (retrbinary and retrlines) include a 
callback option, which would let you update the progress as you went, but 
the upload methods (storbinary and storlines) does not.[1]

You could either a) install the patch from [2] on your system (or override 
storbinary and/or storlines as appropriate; or b) wrap the uploaded file 
in a class that updates the dialog every time data gets read. 

Maybe someone else will have a better idea.



[1] And why not?  I don't see any good reason why it shouldn't.  A patch 
to do this was submitted last year.[2]  It would be nice to see this in 
2.6.  Ruby has it.[3]


[2] 
http://sourceforge.net/tracker/index.php?func=detail&aid=1221598&group_id=5470&atid=305470

[3] http://www.rubycentral.com/book/lib_network.html#Net::FTP.storbinary



From sanelson at gmail.com  Tue Feb  6 09:22:30 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Tue, 6 Feb 2007 08:22:30 +0000
Subject: [Tutor] MapReduce
In-Reply-To: <45C7C4B4.7030108@tds.net>
References: <b6131fdc0702051254p1cadaae2v985cffa8596ba5d8@mail.gmail.com>
	<b6131fdc0702051422y491e1261qfdcdb85cdaea2043@mail.gmail.com>
	<45C7C4B4.7030108@tds.net>
Message-ID: <b6131fdc0702060022x4cd2fdc3lf2cb43165fc76cb@mail.gmail.com>

On 2/5/07, Kent Johnson <kent37 at tds.net> wrote:
> You can also do this operation easily with dicts (not tested!):

Thank you - code now complete and tests passing.  Would appreciate
comments / criticisms.  I did wonder if I should create a UrlAnalyser
Class rather than have hanging methods:

#!/usr/bin/python
import unittest

def myMap(data, search):
  """Take list of tuples of record number and url accessed and return
list of tuples keyed by url with record number as value if search is
in the url"""
  return [(value, key) for key, value in data if search in value]

def myGroup(data):
  """Take list of tuples keyed by url with record number as value, and
group together same urls with list of record numbers as value."""
  groups = {}
  for value, index in data:
    groups.setdefault(value, []).append(index)
  return sorted(groups.items())

def myReduce(data):
  """Process list of tuples of url and record number list and return
list of url and frequency of occurence."""
  return [(value, len(occurences)) for value, occurences in data]

class UnitTests(unittest.TestCase):
  """Do not taunt unit tests."""

  def setUp(self):
    pass

  def tearDown(self):
    pass

  def testMapper(self):
    """Produce set of intermediate key value pairs, with record
content as key and record number as value, if a condition is met."""
    test_pairs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'a'), (5, 'd')]
    intermediate_list = [('a', 1), ('a', 4)]
    self.assertEqual(myMap(test_pairs, "a"), intermediate_list)

  def testGrouper(self):
    """Group occurences of a record together:

    [('fred', 1), ('jim', 2), ('bill', 3), ('jim', 4)] -> [(fred, 1),
('jim', [2, 4]), ('bill' ,3)]"""

    test_list = [('fred', 1), ('jim', 2), ('bill', 3), ('jim', 4)]
    grouped_list = [('bill', [3]), ('fred', [1]), ('jim', [2, 4])]
    self.assertEqual(myGroup(test_list), grouped_list)

  def testReduce(self):
    """Aggregate results of map and group functions to produce value
and frequency."""
    test_intermediate =  [('bill', [3]), ('fred', [1]), ('jim', [2, 4])]
    test_summary = [('bill', 1), ('fred', 1), ('jim', 2)]
    self.assertEqual(myReduce(test_intermediate), test_summary)

def doTests():
  """Run our test suite"""
  suite = unittest.makeSuite(UnitTests,'test')
  runner = unittest.TextTestRunner()
  result = runner.run(suite)
  return result

def main():
  """Main program here"""
  print "Analysing URL data:\n"
  url_data = [(1, 'http://www.beer.com'), (2,
'http://www.ban-beer.com'), (3, 'http://www.bbc.co.uk'), (4,
'http://www.beer.com'), (5, 'http://wwww.kernel.org')]
  print myReduce(myGroup(myMap(url_data, "beer")))

if __name__ == "__main__":
  result = doTests()
  if result.wasSuccessful():
    main()
  else:
    print "Error - check test output."

From alan.gauld at btinternet.com  Tue Feb  6 09:52:58 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Feb 2007 08:52:58 -0000
Subject: [Tutor] best book?
References: <b51938f10702051252p58bd6e65p2ccf892ee71ad4c@mail.gmail.com>
Message-ID: <eq9flh$h1s$1@sea.gmane.org>


"Andrew Purdea" <purdeaandrew at gmail.com> wrote

> Hi! what do you guys think that would be the best free book, or 
> tutorial or
> something to start learning python?

The best free book for an experienced programmer is the
standard tutorial that comes with Python.

> Something that can also focus on important differences from
> other languages,

It doesn't do this but other papers on the web site do.

> present why some choices made in the design are better then others.

That's very hard to be objective about. Thee is no right decision
in language design. Python has its own strengths and philosophy
but they are very different to the goals that guided C++ development,
which in turn were different to those guiding Java..

> just present the information, but also make it easyer to understand 
> it ;-)

The best place for that is probably the PEP archive. The rationale
behind new features is explained well in mosty cases.

If you don't mind paying for it, Wesley's 'Core Python' paper
book does a very good job of explaining the core language.

HTH,

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



From alan.gauld at btinternet.com  Tue Feb  6 10:32:23 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Feb 2007 09:32:23 -0000
Subject: [Tutor] timedelta doesnt do month
References: <60fae7c30702051055x1862df72le17559c50176f416@mail.gmail.com>
	<45C7854F.4050301@tds.net>
Message-ID: <eq9hvd$p5q$1@sea.gmane.org>

"Kent Johnson" <kent37 at tds.net> wrote

> Because of the ambiguities of month arithmetic (what is 2005-1-31 
> plus
> one month?) datetime refuses to guess and does not support this.

> The third-party dateutil module is not as circumspect:
>
> In [1]: import datetime
>
> In [2]: startdate = datetime.date(2005,2,13)

As a matter of interest what would dateutil do with
the example above?

Just curious,

Alan G. 



From kent37 at tds.net  Tue Feb  6 12:05:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 06:05:51 -0500
Subject: [Tutor] How to make ftplib show progress while uploading a
 large file
In-Reply-To: <Pine.LNX.4.44.0702051802590.26710-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0702051802590.26710-100000@violet.rahul.net>
Message-ID: <45C8610F.8080506@tds.net>

Terry Carroll wrote:
> The hard part is going to get ftplib to talk to your dialog.  You're 
> uploading.  ftplib's download methods (retrbinary and retrlines) include a 
> callback option, which would let you update the progress as you went, but 
> the upload methods (storbinary and storlines) does not.[1]
> 
> [1] And why not?  I don't see any good reason why it shouldn't.  A patch 
> to do this was submitted last year.[2]  It would be nice to see this in 
> 2.6.  Ruby has it.[3]

For a good look at the realities of getting patches accepted and 
committed, see this thread on python-dev:

http://mail.python.org/pipermail/python-dev/2004-October/049490.html

Bottom line: the committers are volunteers and they work on what they 
want to. Often they prefer writing code to reviewing and applying patches.

Kent


From kent37 at tds.net  Tue Feb  6 12:08:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 06:08:57 -0500
Subject: [Tutor] timedelta doesnt do month
In-Reply-To: <eq9hvd$p5q$1@sea.gmane.org>
References: <60fae7c30702051055x1862df72le17559c50176f416@mail.gmail.com>	<45C7854F.4050301@tds.net>
	<eq9hvd$p5q$1@sea.gmane.org>
Message-ID: <45C861C9.9010107@tds.net>

Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
> 
>> Because of the ambiguities of month arithmetic (what is 2005-1-31 
>> plus
>> one month?) datetime refuses to guess and does not support this.
> 
>> The third-party dateutil module is not as circumspect:
>>
>> In [1]: import datetime
>>
>> In [2]: startdate = datetime.date(2005,2,13)
> 
> As a matter of interest what would dateutil do with
> the example above?

It coerces the day to fall within the month:

In [1]: import datetime

In [2]: startdate = datetime.date(2005,1,31)

In [3]: from dateutil.relativedelta import relativedelta

In [4]: delta = relativedelta(months=+1)

In [5]: startdate+delta
Out[5]: datetime.date(2005, 2, 28)

Details here:
http://labix.org/python-dateutil#head-72c4689ec5608067d118b9143cef6bdffb6dad4e

Kent


From kent37 at tds.net  Tue Feb  6 12:12:49 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 06:12:49 -0500
Subject: [Tutor] MapReduce
In-Reply-To: <b6131fdc0702060022x4cd2fdc3lf2cb43165fc76cb@mail.gmail.com>
References: <b6131fdc0702051254p1cadaae2v985cffa8596ba5d8@mail.gmail.com>	
	<b6131fdc0702051422y491e1261qfdcdb85cdaea2043@mail.gmail.com>	
	<45C7C4B4.7030108@tds.net>
	<b6131fdc0702060022x4cd2fdc3lf2cb43165fc76cb@mail.gmail.com>
Message-ID: <45C862B1.1090802@tds.net>

Steve Nelson wrote:
> On 2/5/07, Kent Johnson <kent37 at tds.net> wrote:
>> You can also do this operation easily with dicts (not tested!):
> 
> Thank you - code now complete and tests passing.  Would appreciate
> comments / criticisms.  I did wonder if I should create a UrlAnalyser
> Class rather than have hanging methods:

NOOOOOOOO! Python is not Java! There is nothing wrong with a "hanging 
method". In Python we call them functions. :-)

The code looks fine to me.

Kent

> 
> #!/usr/bin/python
> import unittest
> 
> def myMap(data, search):
>   """Take list of tuples of record number and url accessed and return
> list of tuples keyed by url with record number as value if search is
> in the url"""
>   return [(value, key) for key, value in data if search in value]
> 
> def myGroup(data):
>   """Take list of tuples keyed by url with record number as value, and
> group together same urls with list of record numbers as value."""
>   groups = {}
>   for value, index in data:
>     groups.setdefault(value, []).append(index)
>   return sorted(groups.items())
> 
> def myReduce(data):
>   """Process list of tuples of url and record number list and return
> list of url and frequency of occurence."""
>   return [(value, len(occurences)) for value, occurences in data]
> 
> class UnitTests(unittest.TestCase):
>   """Do not taunt unit tests."""
> 
>   def setUp(self):
>     pass
> 
>   def tearDown(self):
>     pass
> 
>   def testMapper(self):
>     """Produce set of intermediate key value pairs, with record
> content as key and record number as value, if a condition is met."""
>     test_pairs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'a'), (5, 'd')]
>     intermediate_list = [('a', 1), ('a', 4)]
>     self.assertEqual(myMap(test_pairs, "a"), intermediate_list)
> 
>   def testGrouper(self):
>     """Group occurences of a record together:
> 
>     [('fred', 1), ('jim', 2), ('bill', 3), ('jim', 4)] -> [(fred, 1),
> ('jim', [2, 4]), ('bill' ,3)]"""
> 
>     test_list = [('fred', 1), ('jim', 2), ('bill', 3), ('jim', 4)]
>     grouped_list = [('bill', [3]), ('fred', [1]), ('jim', [2, 4])]
>     self.assertEqual(myGroup(test_list), grouped_list)
> 
>   def testReduce(self):
>     """Aggregate results of map and group functions to produce value
> and frequency."""
>     test_intermediate =  [('bill', [3]), ('fred', [1]), ('jim', [2, 4])]
>     test_summary = [('bill', 1), ('fred', 1), ('jim', 2)]
>     self.assertEqual(myReduce(test_intermediate), test_summary)
> 
> def doTests():
>   """Run our test suite"""
>   suite = unittest.makeSuite(UnitTests,'test')
>   runner = unittest.TextTestRunner()
>   result = runner.run(suite)
>   return result
> 
> def main():
>   """Main program here"""
>   print "Analysing URL data:\n"
>   url_data = [(1, 'http://www.beer.com'), (2,
> 'http://www.ban-beer.com'), (3, 'http://www.bbc.co.uk'), (4,
> 'http://www.beer.com'), (5, 'http://wwww.kernel.org')]
>   print myReduce(myGroup(myMap(url_data, "beer")))
> 
> if __name__ == "__main__":
>   result = doTests()
>   if result.wasSuccessful():
>     main()
>   else:
>     print "Error - check test output."
> 
> 



From johan at accesstel.co.za  Tue Feb  6 13:31:16 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Tue, 6 Feb 2007 14:31:16 +0200
Subject: [Tutor] CRC calculation with python
Message-ID: <20070206122522.1876C174F4@mail.accesstel.co.za>

Hi all,
 
I'm not a C++ expert at all and I would like to find out if somebody can
explain to me how the statement below can be done in Python?
 
"""
_uint16 ComCRC16(_uint8 val, _uint16 crc)
{
        _uint8 i;
        _uint16 cval;
 
    for (i=0;i<8;i++)
    {
        if (((crc & 0x0001)^(val & 0x0001))!= 0)   crc = (crc >> 1)^
CCITT_POLY;
        else   crc >>= 1;
        val >>= 1;
    }
    return crc
}
 
"""
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.25/669 - Release Date: 2007/02/04
09:58 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070206/52a66788/attachment.htm 

From kent37 at tds.net  Tue Feb  6 14:14:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 08:14:58 -0500
Subject: [Tutor] CRC calculation with python
In-Reply-To: <20070206122522.1876C174F4@mail.accesstel.co.za>
References: <20070206122522.1876C174F4@mail.accesstel.co.za>
Message-ID: <45C87F52.5000204@tds.net>

Johan Geldenhuys wrote:
> Hi all,
>  
> I'm not a C++ expert at all and I would like to find out if somebody can 
> explain to me how the statement below can be done in Python?

I suggest you Google "Python CRC" and find out how others have done 
this, rather than trying to translate the code directly.

Kent

>  
> """
> _uint16 ComCRC16(_uint8 val, _uint16 crc)
> {
>         _uint8 i;
>         _uint16 cval;
>  
>     for (i=0;i<8;i++)
>     {
>         if (((crc & 0x0001)^(val & 0x0001))!= 0)   crc = (crc >> 1)^ 
> CCITT_POLY;
>         else   crc >>= 1;
>         val >>= 1;
>     }
>     return crc
> }
>  
> """
>  
> Thanks
>  
> Johan
> 
> --
> No virus found in this outgoing message.
> Checked by AVG Free Edition.
> Version: 7.5.432 / Virus Database: 268.17.25/669 - Release Date: 
> 2007/02/04 09:58 PM
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From dyoo at WPI.EDU  Tue Feb  6 17:25:22 2007
From: dyoo at WPI.EDU (Daniel Yoo)
Date: Tue, 6 Feb 2007 11:25:22 -0500 (EST)
Subject: [Tutor] CRC calculation with python
In-Reply-To: <20070206122522.1876C174F4@mail.accesstel.co.za>
References: <20070206122522.1876C174F4@mail.accesstel.co.za>
Message-ID: <Pine.LNX.4.64.0702061119080.16508@CCC1.WPI.EDU>



On Tue, 6 Feb 2007, Johan Geldenhuys wrote:

> I'm not a C++ expert at all and I would like to find out if somebody can 
> explain to me how the statement below can be done in Python?
>
> """
> _uint16 ComCRC16(_uint8 val, _uint16 crc)
> {
>        _uint8 i;
>        _uint16 cval;
>
>    for (i=0;i<8;i++)
>    {
>        if (((crc & 0x0001)^(val & 0x0001))!= 0)   crc = (crc >> 1)^
> CCITT_POLY;
>        else   crc >>= 1;
>        val >>= 1;
>    }
>    return crc
> }
>
> """

I agree with Kent that you might want to see if someone has done this work 
already.  Still, a translation of the above should be fairly 
straightforward.  We do have right shifts, and bitwise operators:

############
>>> (42 >> 1)
21
############

The bit pattern of 42 is shifted to the right by one place: in effect, 
doing a division by 2.


We also have XORs and bitwise ANDs:

############
>>> (12345678 ^ 0xdeadbeef)
<stdin>:1: FutureWarning: hex/oct constants > sys.maxint will return 
positive values in Python 2.4 and up
-569253983
>>>
>>> (12345678 ^ 0xdeadbeef) ^ 0xdeadbeef
<stdin>:1: FutureWarning: hex/oct constants > sys.maxint will return 
positive values in Python 2.4 and up
12345678
############


What problems do you have in translating the C++ code to the equivalent 
Python code?

From cbc at unc.edu  Tue Feb  6 18:10:36 2007
From: cbc at unc.edu (Chris Calloway)
Date: Tue, 06 Feb 2007 12:10:36 -0500
Subject: [Tutor] CRC calculation with python
In-Reply-To: <20070206122522.1876C174F4@mail.accesstel.co.za>
References: <20070206122522.1876C174F4@mail.accesstel.co.za>
Message-ID: <45C8B68C.3050604@unc.edu>

First, you need to find the preprocessor define for CCITT_POLY. The code 
is incomplete without it.

Second, where did this code come from? It defines an unused local named 
cval, which will usually cause at least a compilation warning.

This looks like a snippet, not a complete CCITT CRC calculation.

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599

Johan Geldenhuys wrote:
> Hi all,
>  
> I'm not a C++ expert at all and I would like to find out if somebody can 
> explain to me how the statement below can be done in Python?
>  
> """
> _uint16 ComCRC16(_uint8 val, _uint16 crc)
> {
>         _uint8 i;
>         _uint16 cval;
>  
>     for (i=0;i<8;i++)
>     {
>         if (((crc & 0x0001)^(val & 0x0001))!= 0)   crc = (crc >> 1)^ 
> CCITT_POLY;
>         else   crc >>= 1;
>         val >>= 1;
>     }
>     return crc
> }
>  
> """


From nospamformeSVP at gmail.com  Tue Feb  6 18:21:26 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Tue, 06 Feb 2007 12:21:26 -0500
Subject: [Tutor] Multi-line code that uses \ in doctest
Message-ID: <eqadeq$2k2$1@sea.gmane.org>

When I try to use something like:

 >>> hexStringNums = ('1', '2', '3', '4', '5', '6',\
...                  '7', '8', '9','0')

or:

 >>> for hexString in hexStrings:
...     for x in hexString:
...         if ((not x in hexStringChars) and
...             (not x in hexStringNums)):
...             print hexString+ \
...                 " is not a hex string."
...             break

in doctest (Python 2.4) I get an invalid syntax error around the line 
continuation marker, e.g.

Failed example:
     hexStringNums = ('1', '2', '3', '4', '5', '6',... 
'7', '8', '9','0')
Exception raised:
     Traceback (most recent call last):
       File "C:\PYTHON24\lib\doctest.py", line 1243, in __run
         compileflags, 1) in test.globs
       File "<doctest __main__[1]>", line 1
          hexStringNums = ('1', '2', '3', '4', '5', '6',... 
      '7', '8', '9','0')
                                                        ^
      SyntaxError: invalid syntax

I can fix this by not using \ line continuations, but is there a way to 
get doctest to parse these lines as I expect?


Thanks,


Don Taylor


From vladoportos at vladoportos.sk  Tue Feb  6 17:59:56 2007
From: vladoportos at vladoportos.sk (Vladimir Strycek)
Date: Tue, 06 Feb 2007 17:59:56 +0100
Subject: [Tutor] sefl modifing script
Message-ID: <45C8B40C.7040504@vladoportos.sk>

Hi all,

Is it possible to do self modifing script ? I think like variables which 
are defined in the beginning of script could be modified by it self on 
the run... like saving setting but not to external file but directly to 
it self...


Thanks and best regards
Vladimir

From dkuhlman at rexx.com  Tue Feb  6 18:27:35 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 6 Feb 2007 09:27:35 -0800
Subject: [Tutor] CRC calculation with python
In-Reply-To: <45C8B68C.3050604@unc.edu>
References: <20070206122522.1876C174F4@mail.accesstel.co.za>
	<45C8B68C.3050604@unc.edu>
Message-ID: <20070206172735.GA13268@cutter.rexx.com>

On Tue, Feb 06, 2007 at 12:10:36PM -0500, Chris Calloway wrote:
> First, you need to find the preprocessor define for CCITT_POLY. The code 
> is incomplete without it.
> 
> Second, where did this code come from? It defines an unused local named 
> cval, which will usually cause at least a compilation warning.
> 
> This looks like a snippet, not a complete CCITT CRC calculation.

Also, see the crcmod module:

    http://crcmod.sourceforge.net/

But, the README that comes with crcmod recommends the md5 module in
the Python standard library.

Dave


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

From kent37 at tds.net  Tue Feb  6 18:34:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 12:34:42 -0500
Subject: [Tutor] Multi-line code that uses \ in doctest
In-Reply-To: <eqadeq$2k2$1@sea.gmane.org>
References: <eqadeq$2k2$1@sea.gmane.org>
Message-ID: <45C8BC32.4060906@tds.net>

Don Taylor wrote:
> When I try to use something like:
> 
>  >>> hexStringNums = ('1', '2', '3', '4', '5', '6',\
> ...                  '7', '8', '9','0')
> 
> or:
> 
>  >>> for hexString in hexStrings:
> ...     for x in hexString:
> ...         if ((not x in hexStringChars) and
> ...             (not x in hexStringNums)):
> ...             print hexString+ \
> ...                 " is not a hex string."
> ...             break
> 
> in doctest (Python 2.4) I get an invalid syntax error around the line 
> continuation marker, e.g.
> 
> Failed example:
>      hexStringNums = ('1', '2', '3', '4', '5', '6',... 
> '7', '8', '9','0')
> Exception raised:
>      Traceback (most recent call last):
>        File "C:\PYTHON24\lib\doctest.py", line 1243, in __run
>          compileflags, 1) in test.globs
>        File "<doctest __main__[1]>", line 1
>           hexStringNums = ('1', '2', '3', '4', '5', '6',... 
>       '7', '8', '9','0')
>                                                         ^
>       SyntaxError: invalid syntax
> 
> I can fix this by not using \ line continuations, but is there a way to 
> get doctest to parse these lines as I expect?

I think the problem is that the normal Python string processor (not 
doctest) is swallowing the \<newline> in the string. Try putting your 
doctest string in a raw string (r'') or double the backslash (\\).

This page has more details:
file:///C:/Python25/Doc/lib/doctest-finding-examples.html

Kent


From chris.arndt at web.de  Tue Feb  6 18:59:08 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Tue, 06 Feb 2007 18:59:08 +0100
Subject: [Tutor] sefl modifing script
In-Reply-To: <45C8B40C.7040504@vladoportos.sk>
References: <45C8B40C.7040504@vladoportos.sk>
Message-ID: <45C8C1EC.4090208@web.de>

Vladimir Strycek schrieb:
> Hi all,
> 
> Is it possible to do self modifing script ? I think like variables which 
> are defined in the beginning of script could be modified by it self on 
> the run... like saving setting but not to external file but directly to 
> it self...

While what you propose is certainly possible -- after all, a Python script is
just a file and can be therefore read and altered by Python, but for the
scenario you mention it is not the best solution. What if the script is
installed read-only? What if different users on the system where the script is
installed want different settings?

There was a thread on this list titled "The best way to implement a config file
???". I would look in this direction for a solution.

Chris


From vladoportos at vladoportos.sk  Tue Feb  6 19:13:51 2007
From: vladoportos at vladoportos.sk (Vladimir Strycek)
Date: Tue, 06 Feb 2007 19:13:51 +0100
Subject: [Tutor] sefl modifing script
In-Reply-To: <45C8C1EC.4090208@web.de>
References: <45C8B40C.7040504@vladoportos.sk> <45C8C1EC.4090208@web.de>
Message-ID: <45C8C55F.60009@vladoportos.sk>

Christopher Arndt  wrote / nap?sal(a):
> Vladimir Strycek schrieb:
>   
>> Hi all,
>>
>> Is it possible to do self modifing script ? I think like variables which 
>> are defined in the beginning of script could be modified by it self on 
>> the run... like saving setting but not to external file but directly to 
>> it self...
>>     
>
> While what you propose is certainly possible -- after all, a Python script is
> just a file and can be therefore read and altered by Python, but for the
> scenario you mention it is not the best solution. What if the script is
> installed read-only? What if different users on the system where the script is
> installed want different settings?
>
> There was a thread on this list titled "The best way to implement a config file
> ???". I would look in this direction for a solution.
>
> Chris
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> __________ NOD32 2040 (20070206) Information __________
>
> This message was checked by NOD32 antivirus system.
> http://www.eset.com
>
>
>
>   
Thanks i'll check that thread...

From kent37 at tds.net  Tue Feb  6 19:18:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 13:18:05 -0500
Subject: [Tutor] Multi-line code that uses \ in doctest
In-Reply-To: <45C8BC32.4060906@tds.net>
References: <eqadeq$2k2$1@sea.gmane.org> <45C8BC32.4060906@tds.net>
Message-ID: <45C8C65D.2080108@tds.net>

Kent Johnson wrote:
> This page has more details:
> file:///C:/Python25/Doc/lib/doctest-finding-examples.html

Oops. The on-line version of that is here:
file:///C:/Python25/Doc/lib/doctest-finding-examples.html

Kent


From carroll at tjc.com  Tue Feb  6 20:51:48 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 6 Feb 2007 11:51:48 -0800 (PST)
Subject: [Tutor] How to make ftplib show progress while uploading a
 large file
In-Reply-To: <45C8610F.8080506@tds.net>
Message-ID: <Pine.LNX.4.44.0702061144140.20128-100000@violet.rahul.net>

On Tue, 6 Feb 2007, Kent Johnson wrote:

> Bottom line: the committers are volunteers and they work on what they 
> want to. Often they prefer writing code to reviewing and applying patches.

I wonder if there's any way to wave this one under their nose.  If for no 
reason other than to stem potential Ruby envy.

My only experience with the patch process is one patch I submitted in 
2003, when I was still a Python baby.[1]  I got lucky.  Guido himself 
picked it up right away, suggested a few changes, and then checked it in 
once I made them.  It showed up in 2.2, I think.


[1] I tweaked nntplib.py to allow multiline results to be put in a file or 
a file-like object, rather than returned in a list.  The list approach was 
really painful when retrieving headers from a large newsgroup.  
http://sourceforge.net/tracker/index.php?func=detail&aid=720468&group_id=5470&atid=305470



From carroll at tjc.com  Tue Feb  6 21:01:58 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 6 Feb 2007 12:01:58 -0800 (PST)
Subject: [Tutor] Multi-line code that uses \ in doctest
In-Reply-To: <45C8C65D.2080108@tds.net>
Message-ID: <Pine.LNX.4.44.0702061201470.20128-100000@violet.rahul.net>

On Tue, 6 Feb 2007, Kent Johnson wrote:

> Kent Johnson wrote:
> > This page has more details:
> > file:///C:/Python25/Doc/lib/doctest-finding-examples.html
> 
> Oops. The on-line version of that is here:
> file:///C:/Python25/Doc/lib/doctest-finding-examples.html

http://www.python.org/doc/lib/doctest-finding-examples.html


From kent37 at tds.net  Tue Feb  6 21:16:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 15:16:37 -0500
Subject: [Tutor] Multi-line code that uses \ in doctest
In-Reply-To: <Pine.LNX.4.44.0702061201470.20128-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0702061201470.20128-100000@violet.rahul.net>
Message-ID: <45C8E225.3010000@tds.net>

Terry Carroll wrote:
> On Tue, 6 Feb 2007, Kent Johnson wrote:
> 
>> Kent Johnson wrote:
>>> This page has more details:
>>> file:///C:/Python25/Doc/lib/doctest-finding-examples.html
>> Oops. The on-line version of that is here:
>> file:///C:/Python25/Doc/lib/doctest-finding-examples.html
> 
> http://www.python.org/doc/lib/doctest-finding-examples.html

=:-0

Not my day for external references...thanks.

Kent


From kent37 at tds.net  Tue Feb  6 21:19:30 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Feb 2007 15:19:30 -0500
Subject: [Tutor] How to make ftplib show progress while uploading a
 large file
In-Reply-To: <Pine.LNX.4.44.0702061144140.20128-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0702061144140.20128-100000@violet.rahul.net>
Message-ID: <45C8E2D2.9050705@tds.net>

Terry Carroll wrote:
> On Tue, 6 Feb 2007, Kent Johnson wrote:
> 
>> Bottom line: the committers are volunteers and they work on what they 
>> want to. Often they prefer writing code to reviewing and applying patches.
> 
> I wonder if there's any way to wave this one under their nose.  If for no 
> reason other than to stem potential Ruby envy.

Well, the options seem to be
- take Martin L. Lowis up on his review 5 / get 1 reviewed offer
- beg on python-dev
- beg privately to a committer of your choice
- become a committer and fix it yourself ;-)

Kent


From carroll at tjc.com  Wed Feb  7 00:54:57 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 6 Feb 2007 15:54:57 -0800 (PST)
Subject: [Tutor] How to make ftplib show progress while uploading a
 large file
In-Reply-To: <Pine.LNX.4.44.0702051802590.26710-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0702061542540.20128-100000@violet.rahul.net>

On Mon, 5 Feb 2007, Terry Carroll wrote:

> On Sun, 4 Feb 2007, [ISO-8859-1] Magnus Wirstr?m wrote:
> 
> > I'm workinga on a program that will upload a large file to a server 
> > using ftp. I'm using ftplib to do this. I'm using a gui with wxpython 
> > and i would like to have a progressbar showing in % how much have been 
> > transfered. I have been googling but i can't make any sense of what i 
> > have found. does anyone have a good example or could explain how to do 
> > this ?
> 
> Magnus --
> 
> When you installed wxPython, did you also download and install the "Docs, 
> Demo, Samples, etc."?  There are great examples of nearly all wxPython 
> dialogs, including ProgressDialog.
> 
> The hard part is going to get ftplib to talk to your dialog.  You're 
> uploading.  ftplib's download methods (retrbinary and retrlines) include a 
> callback option, which would let you update the progress as you went, but 
> the upload methods (storbinary and storlines) does not.[1]
> 
> You could either a) install the patch from [2] on your system (or override 
> storbinary and/or storlines as appropriate; 

I couldn't resist.  This intrigued me, partially because I will have a 
similar problem in a project I have coming up.  Here's an example.  Most 
of this is derived either from the callback patch I mentioned or from 
the wxPython sample code.  Very little is actual original thought.

First, set up ftplib, but with Phil Schwartz's patch to support the 
callback argument.  

############## begin code ###############################

import ftplib

def my_storlines(self, cmd, fp, callback=None):   # patched for callback
    '''Store a file in line mode.'''
    CRLF = ftplib.CRLF                            # patched for callback
    self.voidcmd('TYPE A')
    conn = self.transfercmd(cmd)
    while 1:
        buf = fp.readline()
        if not buf: break
        if buf[-2:] != CRLF:
            if buf[-1] in CRLF: buf = buf[:-1]
            buf = buf + CRLF
        conn.sendall(buf)
        if callback: callback(buf)                 # patched for callback
    conn.close()
    return self.voidresp()

ftplib.FTP.storlines = my_storlines  # use the patched version

############## end code ###############################

In the above, I just copied storlines out of ftplib.py, and edited it
where the "patched for callback" comments are.  Note: this is for a text
file upload; the same would work for a binary file by patching storbinary
instead.


Now: set up a class that will start a wxPython ProgressDialog, but with 
a callback method added:


############## begin code ###############################
class FTPProgressDialog:
    
    def __init__(self, fname):
        import wx, os
        statinfo = os.stat(fname)
        self.filesize = statinfo.st_size
        self.so_far = 0
        self.app = wx.PySimpleApp()
        self.dlg = wx.ProgressDialog("Upload progress",
                       fname+":",
                       maximum = self.filesize,
                       style = wx.PD_APP_MODAL
                        | wx.PD_ELAPSED_TIME
                        | wx.PD_ESTIMATED_TIME
                        | wx.PD_REMAINING_TIME
                        )

    def asciicallback(self, buffer):
        """
        just used for testing, w/o wxPython
        """
        self.so_far = self.so_far+len(buffer)-1
        pct = float(self.so_far)/self.filesize
        print "so far:", self.so_far, pct
        return

    def wxcallback(self, buffer):
        self.so_far = self.so_far+len(buffer)-1
        self.dlg.Update(self.so_far)
        return

    def close(self):
        self.dlg.Destroy()
        self.app.Destroy()

############## end code ###############################

The code above is not pretty; and it would have been cleaner to 
have FTPProgressDialog inherit from wx.ProgressDialog.  Because the 
class actually starts a wx app, I'll bet you'd run into trouble if you 
tried to use this in an existing wx application.  But that didn't 
occur to me until I was nearly done and starting to get bored.  :-)

Now, to use them:


############## begin code ###############################

filename = "samplefile.txt"

ftpconn = ftplib.FTP('127.0.0.1')  # small local FTP server
ftpconn.set_pasv(False)            # my server doesn't support PASV
ftpconn.login()
trans_file = open(filename)
FTPprogress = FTPProgressDialog(filename)
ftpconn.storlines("STOR "+filename, trans_file, callback=FTPprogress.wxcallback)
ftpconn.quit
FTPprogress.close()

############## end code ###############################

And that, as they say, is that.


From carroll at tjc.com  Wed Feb  7 00:57:51 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 6 Feb 2007 15:57:51 -0800 (PST)
Subject: [Tutor] How to make ftplib show progress while uploading a
 large file
In-Reply-To: <45C8E2D2.9050705@tds.net>
Message-ID: <Pine.LNX.4.44.0702061556170.20128-100000@violet.rahul.net>

On Tue, 6 Feb 2007, Kent Johnson wrote:

> Well, the options seem to be
> - take Martin L. Lowis up on his review 5 / get 1 reviewed offer
> - beg on python-dev
> - beg privately to a committer of your choice
> - become a committer and fix it yourself ;-)

Well, I don't have the development skills for the first or fourth option; 
or for that matter, to be at home hanging on python-dev.  That just leaves 
finding some random committer to stalk, I guess.


From cappy2112 at gmail.com  Wed Feb  7 04:17:50 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 6 Feb 2007 19:17:50 -0800
Subject: [Tutor] How does this work?
Message-ID: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>

I saw a snippet of python which is used to execute another python
script, and I'm trying to understand the mechanism. Simple as it is, I
don't understand how it works :-)


this is the caller
##############################
callee=open("tester.py").read()
exec(callee)
eval("main(['', 'argument'])")

##############################


this is the callee which is saved in tester.py
##############################
import sys

def main(arg):
   if arg != []:
      print"\nArgument is %s" % arg

if __name__ == "__main__"":
   main(sys.argv)
##############################

When the caller is executed

Argument is ['argument']
is displayed, as if the user had typed python tester.py

So I looked a the docs for read() in the file module for a clue-
didn't see anything obvious.
I usually use readlines() myself, so I thought read() might have some
hidden magic I wasn't aware of.

I understand exec() and eval() (in general), but I don't understand
how the entire tester.py gets read in when only a single call to
read() occurs.

Also- I don't understand how the call to eval() executes "in the scope
of" the main in tester.py. If  the main in the eval call were
*somehow* qualified with something to provide scope to tester.py, It
would probably make sense.

Let's assume that the caller also has a main(). How does eval() know
to execute main in the scope of tester.py, and not in the scope of the
caller?

This is pretty cool and confusing ;-)


Is this a useful thing to do, or bad in practice?

thanks

From dyoo at WPI.EDU  Wed Feb  7 04:33:59 2007
From: dyoo at WPI.EDU (Daniel Yoo)
Date: Tue, 6 Feb 2007 22:33:59 -0500 (EST)
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0702062224510.3422@CCC1.WPI.EDU>



On Tue, 6 Feb 2007, Tony Cappellini wrote:

> this is the caller
> ##############################
> callee=open("tester.py").read()
> exec(callee)
> eval("main(['', 'argument'])")
>
> ##############################

> this is the callee which is saved in tester.py
> ##############################
> import sys
>
> def main(arg):
>   if arg != []:
>      print"\nArgument is %s" % arg
>
> if __name__ == "__main__"":
>   main(sys.argv)
> ##############################

Hi Tony,

Ack!

This is not safe.  I would strongly recommend not to do this.  There is a 
much simpler way for the caller to be written:

############################
import tester
tester.main([], "argument")
############################

Done.  No tricks, no eval() or exec() necessary.


> Is this a useful thing to do, or bad in practice?

Very Bad to do in practice.  It seems to be deliberately trying to be 
obfuscated.


Best of wishes!

From dyoo at WPI.EDU  Wed Feb  7 04:37:16 2007
From: dyoo at WPI.EDU (Daniel Yoo)
Date: Tue, 6 Feb 2007 22:37:16 -0500 (EST)
Subject: [Tutor] How does this work?
In-Reply-To: <Pine.LNX.4.64.0702062224510.3422@CCC1.WPI.EDU>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
	<Pine.LNX.4.64.0702062224510.3422@CCC1.WPI.EDU>
Message-ID: <Pine.LNX.4.64.0702062235560.3422@CCC1.WPI.EDU>



On Tue, 6 Feb 2007, Daniel Yoo wrote:

>> this is the callee which is saved in tester.py
>> ##############################
>> import sys
>>
>> def main(arg):
>>   if arg != []:
>>      print"\nArgument is %s" % arg
>>
>> if __name__ == "__main__"":
>>   main(sys.argv)
>> ##############################
>
> This is not safe.  I would strongly recommend not to do this.  There is a
> much simpler way for the caller to be written:
>
> ############################
> import tester
> tester.main([], "argument")
> ############################
>
> Done.  No tricks, no eval() or exec() necessary.

... and also not right.  *sigh*


Sorry, I meant to write:

#########################
import tester
tester.main(["argument"])
#########################


My apologies!

From cappy2112 at gmail.com  Wed Feb  7 04:43:56 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 6 Feb 2007 19:43:56 -0800
Subject: [Tutor] How does this work?
In-Reply-To: <Pine.LNX.4.64.0702062224510.3422@CCC1.WPI.EDU>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
	<Pine.LNX.4.64.0702062224510.3422@CCC1.WPI.EDU>
Message-ID: <8249c4ac0702061943x59bc1b84kbf7330cde7b12801@mail.gmail.com>

Hi Danny,


>
>
> Hi Tony,
>
> Ack!
>
> This is not safe.  I would strongly recommend not to do this.  There is a
> much simpler way for the caller to be written:
What is not safe about doing it this way ?

> ############################
> import tester
> tester.main([], "argument")
> ############################
>
> Done.  No tricks, no eval() or exec() necessary.

> Very Bad to do in practice.  It seems to be deliberately trying to be
> obfuscated.

thanks

From kim.branson at gmail.com  Wed Feb  7 05:14:00 2007
From: kim.branson at gmail.com (Kim Branson)
Date: Tue, 6 Feb 2007 20:14:00 -0800
Subject: [Tutor] get cpu time used by a python script
Message-ID: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>

Hi

whats the simplest cross platform way of getting the cpu time used by  
a python script?

Kim

From clucas916 at gmail.com  Wed Feb  7 05:35:23 2007
From: clucas916 at gmail.com (Christopher Lucas)
Date: Tue, 6 Feb 2007 21:35:23 -0700
Subject: [Tutor] get cpu time used by a python script
In-Reply-To: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>
References: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>
Message-ID: <3ABC8189-9F5E-4F83-A063-F35E3916DBAE@cjlucas.net>


On Feb 6, 2007, at 9:14 PM, Kim Branson wrote:

> Hi
>
> whats the simplest cross platform way of getting the cpu time used by
> a python script?
>
> Kim

What do you mean by cpu time, Kim?

-Chris

From kim.branson at gmail.com  Wed Feb  7 05:37:23 2007
From: kim.branson at gmail.com (Kim Branson)
Date: Tue, 6 Feb 2007 20:37:23 -0800
Subject: [Tutor] get cpu time used by a python script
In-Reply-To: <CF632068-7A7C-4B81-8C6B-C0BA5A1A537C@cjlucas.net>
References: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>
	<CF632068-7A7C-4B81-8C6B-C0BA5A1A537C@cjlucas.net>
Message-ID: <03E78498-7843-45E1-AC9E-613EA0550704@gmail.com>


The time in used by the cpu for the execution of the script, rather  
than the wall clock time.

CPU execution time for program = Clock Cycles for program x Clock  
Cycle Time

But i'm interested in the cpu cycles used purely for the python app,  
regardless of what other processes may be running.

kim


On Feb 6, 2007, at 8:20 PM, Christopher Lucas wrote:

>
> On Feb 6, 2007, at 9:14 PM, Kim Branson wrote:
>
>> Hi
>>
>> whats the simplest cross platform way of getting the cpu time used by
>> a python script?
>>
>> Kim
>
> What do you mean by "cpu time", Kim?


From clucas916 at gmail.com  Wed Feb  7 05:57:45 2007
From: clucas916 at gmail.com (Christopher Lucas)
Date: Tue, 6 Feb 2007 21:57:45 -0700
Subject: [Tutor] get cpu time used by a python script
In-Reply-To: <03E78498-7843-45E1-AC9E-613EA0550704@gmail.com>
References: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>
	<CF632068-7A7C-4B81-8C6B-C0BA5A1A537C@cjlucas.net>
	<03E78498-7843-45E1-AC9E-613EA0550704@gmail.com>
Message-ID: <EB98A1FC-8000-47B8-9AE5-3F90D9F6F0DA@cjlucas.net>


On Feb 6, 2007, at 9:37 PM, Kim Branson wrote:

>
> On Feb 6, 2007, at 8:20 PM, Christopher Lucas wrote:
>
>>
>> On Feb 6, 2007, at 9:14 PM, Kim Branson wrote:
>>
>>> Hi
>>>
>>> whats the simplest cross platform way of getting the cpu time  
>>> used by
>>> a python script?
>>>
>>> Kim
>>
>> What do you mean by "cpu time", Kim?
>
> The time in used by the cpu for the execution of the script, rather  
> than the wall clock time.
>
> CPU execution time for program = Clock Cycles for program x Clock  
> Cycle Time
>
> But i'm interested in the cpu cycles used purely for the python  
> app, regardless of what other processes may be running.
>
> kim
>

I'm not sure, but this link may be of use. http://www.gossamer- 
threads.com/lists/python/python/545797?page=last


From clucas916 at gmail.com  Wed Feb  7 05:58:45 2007
From: clucas916 at gmail.com (Christopher Lucas)
Date: Tue, 6 Feb 2007 21:58:45 -0700
Subject: [Tutor] get cpu time used by a python script
In-Reply-To: <03E78498-7843-45E1-AC9E-613EA0550704@gmail.com>
References: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>
	<CF632068-7A7C-4B81-8C6B-C0BA5A1A537C@cjlucas.net>
	<03E78498-7843-45E1-AC9E-613EA0550704@gmail.com>
Message-ID: <565967CF-38BB-40FD-A482-6B7CA777C213@cjlucas.net>

This link may be of use to you. http://www.gossamer-threads.com/lists/ 
python/python/545797?page=last

-Chris


On Feb 6, 2007, at 9:37 PM, Kim Branson wrote:

>
> The time in used by the cpu for the execution of the script, rather  
> than the wall clock time.
>
> CPU execution time for program = Clock Cycles for program x Clock  
> Cycle Time
>
> But i'm interested in the cpu cycles used purely for the python  
> app, regardless of what other processes may be running.
>
> kim
>
>
> On Feb 6, 2007, at 8:20 PM, Christopher Lucas wrote:
>
>>
>> On Feb 6, 2007, at 9:14 PM, Kim Branson wrote:
>>
>>> Hi
>>>
>>> whats the simplest cross platform way of getting the cpu time  
>>> used by
>>> a python script?
>>>
>>> Kim
>>
>> What do you mean by "cpu time", Kim?
>


From kim.branson at gmail.com  Wed Feb  7 06:05:00 2007
From: kim.branson at gmail.com (Kim Branson)
Date: Tue, 6 Feb 2007 21:05:00 -0800
Subject: [Tutor] get cpu time used by a python script
In-Reply-To: <565967CF-38BB-40FD-A482-6B7CA777C213@cjlucas.net>
References: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>
	<CF632068-7A7C-4B81-8C6B-C0BA5A1A537C@cjlucas.net>
	<03E78498-7843-45E1-AC9E-613EA0550704@gmail.com>
	<565967CF-38BB-40FD-A482-6B7CA777C213@cjlucas.net>
Message-ID: <A2F5CE66-4538-49CE-BAA0-BFB0604A9103@gmail.com>

Hi Chris,

that seems to be exactly what i need.

Cheers

Kim



 >>> import resource
 >>> def cpu_time():
... return resource.getrusage(resource.RUSAGE_SELF)[0]
...

Now try this out

 >>> def f():
... for i in xrange(100000):
... pass
...
 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt
0.008001
 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt
0.012001

On Feb 6, 2007, at 8:58 PM, Christopher Lucas wrote:

> python/python/545797?page=las


From johan at accesstel.co.za  Wed Feb  7 06:41:10 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Wed, 7 Feb 2007 07:41:10 +0200
Subject: [Tutor] CRC calculation with python
In-Reply-To: <20070206172735.GA13268@cutter.rexx.com>
Message-ID: <20070207053515.14C8C164DB@mail.accesstel.co.za>

Thanks for all the replies,

I got this code from a protocol spec that I must use for communications to a
RS232 interface and this the way they calculate the CRC for the data in the
packet.

I have never done any C programming and thought that somebody in this list
may be able to assist.

The idea that I get from the replies is that I should rather use a Python
module for calculating the CRC, thanks Dave for the suggestion. I'll rather
go and look at that than to use a translated C code snippet.

Every now and again I come across C code that is compared with Python code
and since I don't know C, I can't follow the comparison. I never use C in my
work, so for me to go and study the syntax and code layout is something I
wouldn't really use a lot.

Johan

 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Dave Kuhlman
Sent: 06 February 2007 07:28 PM
To: tutor at python.org
Subject: Re: [Tutor] CRC calculation with python

On Tue, Feb 06, 2007 at 12:10:36PM -0500, Chris Calloway wrote:
> First, you need to find the preprocessor define for CCITT_POLY. The 
> code is incomplete without it.
> 
> Second, where did this code come from? It defines an unused local 
> named cval, which will usually cause at least a compilation warning.
> 
> This looks like a snippet, not a complete CCITT CRC calculation.

Also, see the crcmod module:

    http://crcmod.sourceforge.net/

But, the README that comes with crcmod recommends the md5 module in the
Python standard library.

Dave


--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.25/669 - Release Date: 2007/02/04
09:58 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.25/669 - Release Date: 2007/02/04
09:58 PM
 


From alan.gauld at btinternet.com  Wed Feb  7 09:50:33 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 7 Feb 2007 08:50:33 -0000
Subject: [Tutor] How does this work?
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
Message-ID: <eqc3t0$ncm$1@sea.gmane.org>

"Tony Cappellini" <cappy2112 at gmail.com> wrote

>I saw a snippet of python which is used to execute another python
> script, and I'm trying to understand the mechanism. Simple as it is, 
> I
> don't understand how it works :-)

Danny has explained that it is evil and shouldn't be used
but here goes on the explanation.

> ##############################
> callee=open("tester.py").read()

read)() reads the *entire* file in as a string
(complete with embedded newlines etc)

> exec(callee)

executes the file with any function/class definitions left
for future use.

> eval("main(['', 'argument'])")

calls the main function defined by the exec() operation,
passing in the string 'argument'

> ##############################
> import sys
>
> def main(arg):
>   if arg != []:
>      print"\nArgument is %s" % arg

defines the main function that is to be called.

> if __name__ == "__main__"":
>   main(sys.argv)
> ##############################


> Let's assume that the caller also has a main(). How does eval() know
> to execute main in the scope of tester.py, and not in the scope of 
> the
> caller?

It doesn't. It relies on there being a main function in the
"imported" script and the caller not having created one himself.

> This is pretty cool and confusing ;-)
> Is this a useful thing to do, or bad in practice?

As Danny said, its very very bad.
Imagine someone replacing tester.py with something like:

##############
import os
if os.system('format c:'):   # kill DOS
   os.system('rm -rf /')      # kill *nix

def main(): print "Sucker!!!"
###############

HTH,

-- 
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 Feb  7 10:25:15 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 7 Feb 2007 09:25:15 -0000
Subject: [Tutor] get cpu time used by a python script
References: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>
Message-ID: <eqc5u2$u3q$1@sea.gmane.org>


"Kim Branson" <kim.branson at gmail.com> wrote

> whats the simplest cross platform way of getting the cpu time used 
> by
> a python script?

Does the os.times() function give you enough?
Its not strictly cpu time...

Alan G. 



From kent37 at tds.net  Wed Feb  7 12:06:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 06:06:56 -0500
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
Message-ID: <45C9B2D0.60407@tds.net>

Tony Cappellini wrote:
> I saw a snippet of python which is used to execute another python
> script, and I'm trying to understand the mechanism. Simple as it is, I
> don't understand how it works :-)

A few more points missed by Danny and Alan. Not to be taken as an 
endorsement of this strategy...

> this is the caller
> ##############################
> callee=open("tester.py").read()
> exec(callee)

I think these two lines could be written as
execfile("tester.py")

and exec is a statement, not a function, so you can write
exec callee

> So I looked a the docs for read() in the file module for a clue-
> didn't see anything obvious.

Hmm. You didn't find this?
http://docs.python.org/lib/bltin-file-objects.html#l2h-302

> Also- I don't understand how the call to eval() executes "in the scope
> of" the main in tester.py. If  the main in the eval call were
> *somehow* qualified with something to provide scope to tester.py, It
> would probably make sense.

The exec is done in the scope of the caller as well, so the names 
defined in tester.py become names in the global namespace of the caller. 
You can provide optional parameters to both exec and eval() to change 
the namespace they use.

http://docs.python.org/ref/exec.html

> Let's assume that the caller also has a main(). How does eval() know
> to execute main in the scope of tester.py, and not in the scope of the
> caller?

It doesn't. The main() in tester.py would replace the main() in the 
scope of the caller.
> 
> This is pretty cool and confusing ;-)
> 
> 
> Is this a useful thing to do, or bad in practice?

Bad. There is usually a better way.

PS To import a file whose name is in a variable (string), see __import__().

Kent


From kent37 at tds.net  Wed Feb  7 12:10:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 06:10:28 -0500
Subject: [Tutor] get cpu time used by a python script
In-Reply-To: <A2F5CE66-4538-49CE-BAA0-BFB0604A9103@gmail.com>
References: <5E8AB140-31DA-4985-A017-55CEDFC70211@gmail.com>	<CF632068-7A7C-4B81-8C6B-C0BA5A1A537C@cjlucas.net>	<03E78498-7843-45E1-AC9E-613EA0550704@gmail.com>	<565967CF-38BB-40FD-A482-6B7CA777C213@cjlucas.net>
	<A2F5CE66-4538-49CE-BAA0-BFB0604A9103@gmail.com>
Message-ID: <45C9B3A4.7000501@tds.net>

Kim Branson wrote:
> Hi Chris,
> 
> that seems to be exactly what i need.

The resource module is Unix-only, not cross-platform as you originally 
requested.

Kent


From anilmrn at yahoo.com  Wed Feb  7 09:25:01 2007
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 7 Feb 2007 00:25:01 -0800 (PST)
Subject: [Tutor] I m trying to understand why we need Co-routines
Message-ID: <20070207082501.21565.qmail@web55212.mail.re4.yahoo.com>

Hello 

Yesterday I spoke to an employee of yahoo egroups and he was explaining that they used coroutines to send mails in egroups
because each thread was 2mb in size...

Can you point me to resources on how to use co-routines in python or if you have code samples it would be great

thanks
Anil

 
---------------------------------
Now that's room service! Choose from over 150,000 hotels 
in 45,000 destinations on Yahoo! Travel to find your fit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070207/07a724ce/attachment.html 

From govindgoyal at gmail.com  Wed Feb  7 13:25:36 2007
From: govindgoyal at gmail.com (govind goyal)
Date: Wed, 7 Feb 2007 17:55:36 +0530
Subject: [Tutor] Input from and output to a file
Message-ID: <f96f96bc0702070425w6449da68k531526530ae0435b@mail.gmail.com>

hi,

1) I want to read data not from <STDIN> but from a file which is in
specified directory.
2) I want to redirect my output(which is by default STDOUT) to a file.

Can anybody suggest these queries?

Thanks
Regards,
Govind
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070207/5f65b587/attachment.htm 

From govindgoyal at gmail.com  Wed Feb  7 14:32:46 2007
From: govindgoyal at gmail.com (govind goyal)
Date: Wed, 7 Feb 2007 19:02:46 +0530
Subject: [Tutor] python books
Message-ID: <f96f96bc0702070532m24dca1f2iedb17e969f38ae99@mail.gmail.com>

Hi,

I want to purchase a python book but confused of which authur?I need
suggestion.
How is "Teach yoursef python in 24 hours by Ivan van laningham"?

Regards,
Govind
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070207/e0eae49a/attachment.html 

From kent37 at tds.net  Wed Feb  7 14:49:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 08:49:51 -0500
Subject: [Tutor] python books
In-Reply-To: <f96f96bc0702070532m24dca1f2iedb17e969f38ae99@mail.gmail.com>
References: <f96f96bc0702070532m24dca1f2iedb17e969f38ae99@mail.gmail.com>
Message-ID: <45C9D8FF.9090400@tds.net>

govind goyal wrote:
> Hi,
>  
> I want to purchase a python book but confused of which authur?I need 
> suggestion.
> How is "Teach yoursef python in 24 hours by Ivan van laningham"?

Do you have any programming background or is Python your first 
programming language?

Kent


From challman at gmail.com  Wed Feb  7 15:33:03 2007
From: challman at gmail.com (Chris Hallman)
Date: Wed, 7 Feb 2007 09:33:03 -0500
Subject: [Tutor] python24dll not found
Message-ID: <9f68812f0702070633i2bc051bcp30e5c94c57b4fe34@mail.gmail.com>

My apologies if this isn't the correct forum for such a question, however I
was having a problem with Python and couldn't find the cause. I have two
systems running Python. My laptop and a server:

laptop:
WinXP SP2 x86
Python 2.5
pymssql 0.8.0 (for 2.5)
pywin32-210 (for 2.5)

server:
Win2003 no SP dual XEON x86
Python 2.4.1

I develop and test my program on my laptop. I move them to my server and
test again. Then, they go into "production". The few programs I have running
on the server were operating fine until I tried to start running a program
with pymssql. I installed pymssql 0.8.0 (for 2.5) on my laptop so that I
could write and test a new program. When it was ready to move to the server,
I upgraded the server to Python 2.5 and installed pymssql 0.8.0 (for 2.5). I
uninstaled Python 2.4.. The first running of this program gave me a pop-up
error stating that the program failed to start because python24.dll wasn't
found and it recommended reinstalling Python. Python output an error stating
that it couldn't "import _socket". I don't have the exact error because I
was under pressure to restore normal operations. I performed the following:

1. Reinstalled Python 2.5 and execute the program. I received the same
error.
2. Uninstall Python 2.5 and pymssql. Ensure the Python25 directory was
removed. Reinstall Python 2.5 and pymssql. I received the same error.
3. Uninstall Python and pymssql. Ensure the Python25 directory was removed.
Reboot. Reinstall Python 2.5 and pymssql. I received the same error.
4. Uninstall Python 2.5 and pymssql. Ensure the Python25 directory was
removed. Install Python 2.4.2 and pymssql 0.8.0 (for 2.4). The error went
away.


Now all my programs, including the new one, are working again. I have no
clue what caused this. I've searched Google but I can't find a hit similar
to my configuration and situation. Does anyone have an idea as to what could
have caused this?




Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070207/6f8c1be1/attachment.html 

From kent37 at tds.net  Wed Feb  7 15:55:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 09:55:23 -0500
Subject: [Tutor] python books
In-Reply-To: <f96f96bc0702070554j6a7a324dha53828481a51a3b6@mail.gmail.com>
References: <f96f96bc0702070532m24dca1f2iedb17e969f38ae99@mail.gmail.com>	
	<45C9D8FF.9090400@tds.net>
	<f96f96bc0702070554j6a7a324dha53828481a51a3b6@mail.gmail.com>
Message-ID: <45C9E85B.3080506@tds.net>

govind goyal wrote:
> hi,
>  
> In regards to programming language I know C,C++ and little of perl syntax.

"Learning Python" is good for people with some programming background.
"Dive into Python" is popular but IMO it focuses too much on flashy
features and not enough on the basics. "Beginning Python" and "Core
Python Programming" are also good choices.

These and other books listed here:
http://wiki.python.org/moin/IntroductoryBooks

Good online resources here:
http://wiki.python.org/moin/BeginnersGuide/Programmers

"Teach yoursef python in 24 hours" is old and gets very poor reviews on
Amazon.com.

Kent

> 
> 
>  
> On 2/7/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
> 
>     govind goyal wrote:
>      > Hi,
>      >
>      > I want to purchase a python book but confused of which authur?I need
>      > suggestion.
>      > How is "Teach yoursef python in 24 hours by Ivan van laningham"?
> 
>     Do you have any programming background or is Python your first
>     programming language?
> 
>     Kent
> 
> 




From cappy2112 at gmail.com  Wed Feb  7 16:44:19 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 7 Feb 2007 07:44:19 -0800
Subject: [Tutor] How does this work?
In-Reply-To: <45C9B2D0.60407@tds.net>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
	<45C9B2D0.60407@tds.net>
Message-ID: <8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>

>
> PS To import a file whose name is in a variable (string), see __import__().

I've started doing the import instead of exec/eval , but the person
who wrote the module being called, started using the logging module.
Now I can't capture the output of the module I'm calling, and display
it in a GUI. I was using popen() previously and that worked fine,
until he started using logging

From kent37 at tds.net  Wed Feb  7 17:08:31 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 11:08:31 -0500
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>	
	<45C9B2D0.60407@tds.net>
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
Message-ID: <45C9F97F.6060004@tds.net>

Tony Cappellini wrote:
>> PS To import a file whose name is in a variable (string), see __import__().
> 
> I've started doing the import instead of exec/eval , but the person
> who wrote the module being called, started using the logging module.
> Now I can't capture the output of the module I'm calling, and display
> it in a GUI. I was using popen() previously and that worked fine,
> until he started using logging

I'm not sure what this question has to do with the previous one. You are 
running an external script using popen() and you want to show stdout in 
your gui? Can you configure the logging in the external script to 
include console output?

Kent


From kent37 at tds.net  Wed Feb  7 17:12:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 11:12:04 -0500
Subject: [Tutor] Input from and output to a file
In-Reply-To: <f96f96bc0702070425w6449da68k531526530ae0435b@mail.gmail.com>
References: <f96f96bc0702070425w6449da68k531526530ae0435b@mail.gmail.com>
Message-ID: <45C9FA54.2070503@tds.net>

govind goyal wrote:
> hi,
>  
> 1) I want to read data not from <STDIN> but from a file which is in 
> specified directory.
> 2) I want to redirect my output(which is by default STDOUT) to a file.
>  
> Can anybody suggest these queries?

One way to redirect stdin and stdout is just to do it on the commandline:
python myscript.py < myinput.txt > myoutput.txt

It is easy to read and write files in Python:
f = open('myinput.txt')
data = f.read()
f.close()

gets the contents of myinput.txt into data

f = open('myoutput.txt', 'w')
f.write(data)
f.close()

writes the contents of data to myoutput.txt.

There are many variations on this, any good tutorial will cover file I/O.

It is also possible to directly assign to sys.stdin and sys.stdout but 
I'm not sure that is the best solution for you...

Kent


From kent37 at tds.net  Wed Feb  7 17:34:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 11:34:53 -0500
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>	
	<45C9B2D0.60407@tds.net>
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
Message-ID: <45C9FFAD.3040005@tds.net>

Tony Cappellini wrote:
>> PS To import a file whose name is in a variable (string), see __import__().
> 
> I've started doing the import instead of exec/eval , but the person
> who wrote the module being called, started using the logging module.
> Now I can't capture the output of the module I'm calling, and display
> it in a GUI. I was using popen() previously and that worked fine,
> until he started using logging

Rereading your past postings a little bit, what you really have is bad 
architecture.

If I understand you, you have a python cmdline app that does something 
useful. You have users who aren't comfortable with the command line, so 
you are writing a GUI wrapper that calls the cmdline app with popen().

A better approach is to turn the functional part of the cmdline app - 
the code that does the real work - into an importable module. Then your 
GUI app can import and use this module directly, instead of doing hacks 
with popen() and stdout.

You don't even need a separate module for the cmdline app if it is 
written correctly - the command-line-specific part can be in an main() 
function that is only called if the module is run as main.

Kent


From mail at timgolden.me.uk  Wed Feb  7 17:52:11 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 7 Feb 2007 16:52:11 -0000 (GMT)
Subject: [Tutor] python24dll not found
In-Reply-To: <9f68812f0702070633i2bc051bcp30e5c94c57b4fe34@mail.gmail.com>
References: <9f68812f0702070633i2bc051bcp30e5c94c57b4fe34@mail.gmail.com>
Message-ID: <19491.81.171.156.66.1170867131.squirrel@81.171.156.66>

[... snip slightly complex problem involving different
versions of Python and possibly mismatched module imports ...]

> Now all my programs, including the new one, are working again. I have no
> clue what caused this. I've searched Google but I can't find a hit similar
> to my configuration and situation. Does anyone have an idea as to what
> could have caused this?

While I don't, a useful debugging aid here is the -v/-vv switch
to the Python interpreter. If you start python with -vv, you'll
get the most verbose output showing exactly where the interpreter
is trying to find your module (and every other module it needs
to get going). You'd best redirect the output to a log file,
but it can be very helpful:

python -vv -c "import pymssql" 2> temp.log
grep pymssql temp.log

(or open it in an editor or whatever).

The -v switch gives less output, but isn't as useful if
the import fails.

HTH
TJG

From cappy2112 at gmail.com  Wed Feb  7 18:25:32 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 7 Feb 2007 09:25:32 -0800
Subject: [Tutor] How does this work?
In-Reply-To: <45C9FFAD.3040005@tds.net>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
	<45C9B2D0.60407@tds.net>
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
	<45C9FFAD.3040005@tds.net>
Message-ID: <8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>

> If I understand you, you have a python cmdline app that does something
> useful. You have users who aren't comfortable with the command line, so
> you are writing a GUI wrapper that calls the cmdline app with popen().
That is correct

> A better approach is to turn the functional part of the cmdline app -
> the code that does the real work - into an importable module.
it already is importable

>>Then your GUI app can import and use this module directly, instead
of doing hacks
> with popen() and stdout.

This all worked fine, until the author of the cmd line app stopped
using stdout and started using the logging module. Now I cannot
capture any output from his module.

> You don't even need a separate module for the cmdline app if it is
> written correctly - the command-line-specific part can be in an main()
> function that is only called if the module is run as main.

not totally true. It must be a stand-alone app, because there are
people using it now and many don't want to use the gui.
It is maintained completely independent of the gui by people other
than myself.. Any changes in the cmdline app should not affect the
gui. That was the intent by the author anyway. The use of the logging
module happens to be an exception to this.

Using popen() in a thread was a nice clean way to capture it's output.
Perhaps the exec/eval isn't so clean it's just what first came to mind.

I've already switched the exec/eval code to the import style.

From paulino1 at sapo.pt  Wed Feb  7 18:30:26 2007
From: paulino1 at sapo.pt (Paulino)
Date: Wed, 07 Feb 2007 17:30:26 +0000
Subject: [Tutor] same output on diferent sys.stdout.encodings
In-Reply-To: <mailman.11117.1170806101.32030.tutor@python.org>
References: <mailman.11117.1170806101.32030.tutor@python.org>
Message-ID: <45CA0CB2.3000905@sapo.pt>

Hi everyone!

I have some strings that include special characters, to be displayed in 
widget labels ( PyQt4 ).
The output changes in diferent OS's due to diferent sys.stdout encoding

Not only the labels in the GUI change, but the source file strings are 
altered when I move from win to linux and vice-versa.

The solution I found for now was to replace the special characters in 
the source file string for their representation:
I replaced "?" (e acute ) by "\xe9" wich correpsond to chr(233) in the 
cp1252 encoding.

The character ? (e acute) in linux is not recognized in the source file, 
neither in IDLE nor in Kate
My win sys.stdout.encoding is cp850 and the linux one is utf-8

Now I have "d\xe9bito" instead of "d?bito" (debit in portuguese). By 
passing the string through unicode with the convinient encoding, I 
ensure the labels are exibithed the same  in every OS but, this way the 
code is not very readable.

Is there a way of solving this, keeping the more readable?

From rabidpoobear at gmail.com  Wed Feb  7 19:06:11 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 07 Feb 2007 12:06:11 -0600
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>	<45C9B2D0.60407@tds.net>	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>	<45C9FFAD.3040005@tds.net>
	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
Message-ID: <45CA1513.7020507@gmail.com>

Tony Cappellini wrote:
>> If I understand you, you have a python cmdline app that does something
>> useful. You have users who aren't comfortable with the command line, so
>> you are writing a GUI wrapper that calls the cmdline app with popen().
>>     
> That is correct
>
>   
>> A better approach is to turn the functional part of the cmdline app -
>> the code that does the real work - into an importable module.
>>     
> it already is importable
>
>   
>>> Then your GUI app can import and use this module directly, instead
>>>       
> of doing hacks
>   
>> with popen() and stdout.
>>     
>
> This all worked fine, until the author of the cmd line app stopped
> using stdout and started using the logging module. Now I cannot
> capture any output from his module.
>
>   
>> You don't even need a separate module for the cmdline app if it is
>> written correctly - the command-line-specific part can be in an main()
>> function that is only called if the module is run as main.
>>     
>
> not totally true. It must be a stand-alone app, because there are
> people using it now and many don't want to use the gui.
> It is maintained completely independent of the gui by people other
> than myself.. Any changes in the cmdline app should not affect the
> gui. That was the intent by the author anyway. The use of the logging
> module happens to be an exception to this.
>   
The application needs to be rewritten if this is true.  The author's 
implementation is not logical,
if I'm inferring correctly that he knows there are other apps depending 
on this.
consider this:

class Foo(object):
    def __init__(self):
        print "we're creating a new Foo and doing something useful here."

if __name__ == "__main__":
    f = Foo()
    #we can do stuff with our Foo instance here.

Notice that if this program is run as a regular script -- not imported 
-- we create a Foo and we can use it for whatever.
All the functionality of the cmdline app is contained in the Foo class.  
All that we have to do is propagate our data into it.

Now if we want to write a GUI for this, we just import this script, and 
use the Foo object to do whatever we were doing in the
cmdline version -- no separate processes, threads, or any of that nastiness.
Because it's imported, the contents of the 'if __name__...' conditional 
statement are never executed, so the cmdline functionality is disabled.

Hope that helps,
-Luke
> Using popen() in a thread was a nice clean way to capture it's output.
> Perhaps the exec/eval isn't so clean it's just what first came to mind.
>
> I've already switched the exec/eval code to the import style.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From kent37 at tds.net  Wed Feb  7 19:39:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 13:39:47 -0500
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>	
	<45C9B2D0.60407@tds.net>	
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>	
	<45C9FFAD.3040005@tds.net>
	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
Message-ID: <45CA1CF3.4050402@tds.net>

Tony Cappellini wrote:
>> A better approach is to turn the functional part of the cmdline app -
>> the code that does the real work - into an importable module.
> it already is importable
> 
>>> Then your GUI app can import and use this module directly, instead
> of doing hacks
>> with popen() and stdout.
> 
> This all worked fine, until the author of the cmd line app stopped
> using stdout and started using the logging module. Now I cannot
> capture any output from his module.

You should be able to make the logging module work with you, it is very 
flexible. You should hook into the logging module. Write a custom 
handler that pushes log methods into your GUI. Add the handler to the 
root logger.

>> You don't even need a separate module for the cmdline app if it is
>> written correctly - the command-line-specific part can be in an main()
>> function that is only called if the module is run as main.
> 
> not totally true. It must be a stand-alone app, because there are
> people using it now and many don't want to use the gui.
> It is maintained completely independent of the gui by people other
> than myself.

Right, but the stand-alone stuff can be wrapped with
if __name__=='__main__':
leaving the part you care about available for import in the same module. 
The logging configuration should be in the main code as well, then when 
you import the module you can configure logging the way you want.

Kent


From cappy2112 at gmail.com  Wed Feb  7 19:44:44 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 7 Feb 2007 10:44:44 -0800
Subject: [Tutor] How does this work?
In-Reply-To: <45CA1513.7020507@gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
	<45C9B2D0.60407@tds.net>
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
	<45C9FFAD.3040005@tds.net>
	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
	<45CA1513.7020507@gmail.com>
Message-ID: <8249c4ac0702071044l59d7f872td3637120d9c6a952@mail.gmail.com>

> The application needs to be rewritten if this is true.  The author's
> implementation is not logical,
regardless- I won't ask him to do this, it's just the way it is. I
don't know why it was written this way.

> if I'm inferring correctly that he knows there are other apps depending
> on this.
Yes he knows, but the gui aspect of it didn't come into play until the
app was deployed and already in use. He favors cmd line apps that can
be dasiy chained or piped together in the typical unix fashion.

> consider this:

> class Foo(object):
>     def __init__(self):
>         print "we're creating a new Foo and doing something useful here."
>
> if __name__ == "__main__":
>     f = Foo()
>     #we can do stuff with our Foo instance here.
I agree with this approach, and is how most of my apps begin.

> Now if we want to write a GUI for this, we just import this script, and
> use the Foo object to do whatever we were doing in the
> cmdline version -- no separate processes, threads, or any of that nastiness.
> Because it's imported, the contents of the 'if __name__...' conditional
> statement are never executed, so the cmdline functionality is disabled.

actually- after importing I call main directly and pass the cmd line
args specified by the user, through the gui

import targetapp

targetapp.main( [arg1, arg2]) # arg1 arg2 passed in through edit box in the gui
(this syntax may not be totally correct, just consider the concept. I
dont have my source in front of me.

> Hope that helps,
I understand your proposal, and agree with it. But I cannot change the
author's code, as he is the sole maintainer.

However, the problem now is more of an issue with the recent use of
the logging module in the target app, and not being able to capture
it's output, even though it is displayed on the screen.

Regardless of how the gui calls the target app, either by
instantiating a class or by calling main() after importing it- I am at
a loss as to how to "capture" the output on the screen which is now
put there by the logger, into put into a TextBox.

If implementing the target app as a class as you have suggested will
change this issue, then I am at a loss how it will work. I have used
the logging module at work, but in a more straightforward application,
and never had to deal with this kind of issue.

thanks

From cappy2112 at gmail.com  Wed Feb  7 19:49:43 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 7 Feb 2007 10:49:43 -0800
Subject: [Tutor] How does this work?
In-Reply-To: <45CA1CF3.4050402@tds.net>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
	<45C9B2D0.60407@tds.net>
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
	<45C9FFAD.3040005@tds.net>
	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
	<45CA1CF3.4050402@tds.net>
Message-ID: <8249c4ac0702071049j19c4fcefp16407ac3332b3038@mail.gmail.com>

> You should be able to make the logging module work with you, it is very
> flexible. You should hook into the logging module. Write a custom
> handler that pushes log methods into your GUI. Add the handler to the
> root logger.

The cmd line app already uses the logging module- this is where the
problem started.

At the moment- due to the author's implementation, I can't pass in
anything to modify ho the logger gets initialized. I have been
thinking about asking him to let me pass in an instance of the logger
to his main(), once I understand how to get the output from the logger
into a string variable


> Right, but the stand-alone stuff can be wrapped with
> if __name__=='__main__':

It already is. The cmd line app was written like this since day 1.
I am now importing it and calling his main() via the module import
import targetapp

targetapp.main([arg1, arg2]) or whatever

> leaving the part you care about available for import in the same module.

> The logging configuration should be in the main code as well, then when
> you import the module you can configure logging the way you want.

I think the hooks for the logging need to be changed, so I can pass
them in or call them.

Ok- now I will ask him to make his app a class

From kent37 at tds.net  Wed Feb  7 20:02:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 14:02:47 -0500
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702071049j19c4fcefp16407ac3332b3038@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>	
	<45C9B2D0.60407@tds.net>	
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>	
	<45C9FFAD.3040005@tds.net>	
	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>	
	<45CA1CF3.4050402@tds.net>
	<8249c4ac0702071049j19c4fcefp16407ac3332b3038@mail.gmail.com>
Message-ID: <45CA2257.8070102@tds.net>

Tony Cappellini wrote:
>> You should be able to make the logging module work with you, it is very
>> flexible. You should hook into the logging module. Write a custom
>> handler that pushes log methods into your GUI. Add the handler to the
>> root logger.
> 
> The cmd line app already uses the logging module- this is where the
> problem started.
> 
> At the moment- due to the author's implementation, I can't pass in
> anything to modify ho the logger gets initialized. I have been
> thinking about asking him to let me pass in an instance of the logger
> to his main(), once I understand how to get the output from the logger
> into a string variable
> 
> 
>> Right, but the stand-alone stuff can be wrapped with
>> if __name__=='__main__':
> 
> It already is. The cmd line app was written like this since day 1.
> I am now importing it and calling his main() via the module import
> import targetapp
> 
> targetapp.main([arg1, arg2]) or whatever

You are still calling his code at too high a level. See if you can get 
him to write his main() something like this:

def main(argv=sys.argv):
   options = parse_options(argv)
   configure_logging()
   do_the_work(options)
or do_the_work(**options)
or do_the_work(options[0], options[1])
or...

where options is a list or dict or whatever kind of container makes 
sense to hold the options. Then your code does the initialization that 
makes sense for you - including hooking up the logging module to the GUI 
- and calls do_the_work().
> 
>> leaving the part you care about available for import in the same module.
> 
>> The logging configuration should be in the main code as well, then when
>> you import the module you can configure logging the way you want.
> 
> I think the hooks for the logging need to be changed, so I can pass
> them in or call them.
> 
> Ok- now I will ask him to make his app a class

That is not needed, he just needs to make it more fine-grained so it has 
a real API into the functional part that is distinct from the packaging 
as a command-line app.


From nospamformeSVP at gmail.com  Wed Feb  7 20:14:37 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Wed, 07 Feb 2007 14:14:37 -0500
Subject: [Tutor] What should go in a module?
Message-ID: <eqd8f2$80c$1@sea.gmane.org>

I am looking for advice on module size.

When I first came upon Python my initial thought was to package very
closely-related things into modules. Modules would be small, and may
contain a single class or function.  An application would consist of
lots of modules.

Now I am wondering if this is the best strategy.   Is it better to 
package everything together into a single module and use separate 
modules only when that code might usefully be shared between different 
applications.

I am really just asking about applications here, not libraries or 
frameworks.

TIA.

Don.






From rschroev_nospam_ml at fastmail.fm  Wed Feb  7 21:02:49 2007
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Wed, 07 Feb 2007 21:02:49 +0100
Subject: [Tutor] How does this work?
In-Reply-To: <8249c4ac0702071044l59d7f872td3637120d9c6a952@mail.gmail.com>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>	<45C9B2D0.60407@tds.net>	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>	<45C9FFAD.3040005@tds.net>	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>	<45CA1513.7020507@gmail.com>
	<8249c4ac0702071044l59d7f872td3637120d9c6a952@mail.gmail.com>
Message-ID: <eqdb99$ilq$1@sea.gmane.org>

Tony Cappellini schreef:
> However, the problem now is more of an issue with the recent use of
> the logging module in the target app, and not being able to capture
> it's output, even though it is displayed on the screen.

I don't know a lot about the logging module, but doesn't it send its 
output to stderr? Maybe you just have to capture stderr instead of 
stdout to get the output.

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

Roel Schroeven


From tim at johnsons-web.com  Wed Feb  7 12:09:46 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 07 Feb 2007 11:09:46 +0000
Subject: [Tutor] Problem with Reference Manual (duplicate ISBN)
Message-ID: <200702071109.46601.tim@johnsons-web.com>

Nope, I'm not criticizing the writing or the technical info at...
Just the sloppy publishing.

I ordered the Reference Manual for Version 2.5 and got Version 2.3
instead. 
Reason, they have the same ISBN. The vendor said that this is
very unusual.

This should be corrected, don't you think?
regards
-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From kent37 at tds.net  Wed Feb  7 22:30:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Feb 2007 16:30:25 -0500
Subject: [Tutor] How does this work?
In-Reply-To: <45CA1CF3.4050402@tds.net>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>		<45C9B2D0.60407@tds.net>		<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>		<45C9FFAD.3040005@tds.net>	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
	<45CA1CF3.4050402@tds.net>
Message-ID: <45CA44F1.9060803@tds.net>

Kent Johnson wrote:
> You should be able to make the logging module work with you, it is very 
> flexible. You should hook into the logging module. Write a custom 
> handler that pushes log methods into your GUI. Add the handler to the 
> root logger.

Here is a simple, working example of this. It creates a custom log 
handler that logs to a wx.TextCtrl and sets up the logging module to log 
to the custom handler and also to the console.

This is pretty much my first wx program and I whipped it together *very* 
quickly (mostly copy-and-paste from the "wxPython in Action" sample 
code) so no points for style, but it does work. Every time you click the 
button it will generate a log event.

Kent


import logging, wx, sys

class LogToText(logging.Handler):
     def __init__(self, textCtl):
         logging.Handler.__init__(self)
         self.textCtl = textCtl

     def emit(self, record):
         self.textCtl.AppendText(self.format(record))
         self.textCtl.AppendText('\n')


class TextFrame(wx.Frame):

     def __init__(self):
         wx.Frame.__init__(self, None, -1, 'Text Entry Example',
                 size=(300, 250))
         panel = wx.Panel(self, -1)
         multiLabel = wx.StaticText(panel, -1, "Multi-line")
         self.multiText = wx.TextCtrl(panel, -1,
                "",
                size=(200, 100), style=wx.TE_MULTILINE)
         self.multiText.SetInsertionPoint(0)

         self.button = wx.Button(panel, -1, "Click Me")
         self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
         self.button.SetDefault()

         sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
         sizer.AddMany([multiLabel, self.multiText, self.button])
         panel.SetSizer(sizer)

     def OnClick(self, event):
         logging.error("Clicked")

if __name__ == '__main__':
     app = wx.PySimpleApp()
     frame = TextFrame()


     handler = LogToText(frame.multiText)
     logger=logging.getLogger()
     logger.addHandler(handler)

     stdout_handler = logging.StreamHandler(sys.stdout)
     formatter = logging.Formatter('%(name)s :%(asctime)s %(filename)s 
%(lineno)s %(levelname)s  %(message)s')
     stdout_handler.setFormatter(formatter)
     logger.addHandler(stdout_handler)

     frame.Show()
     app.MainLoop()



From bgailer at alum.rpi.edu  Wed Feb  7 22:34:54 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 07 Feb 2007 13:34:54 -0800
Subject: [Tutor] Problem with Reference Manual (duplicate ISBN)
In-Reply-To: <200702071109.46601.tim@johnsons-web.com>
References: <200702071109.46601.tim@johnsons-web.com>
Message-ID: <45CA45FE.1000801@alum.rpi.edu>

Tim Johnson wrote:
> Nope, I'm not criticizing the writing or the technical info at...
> Just the sloppy publishing.
>
> I ordered the Reference Manual for Version 2.5 and got Version 2.3
> instead. 
> Reason, they have the same ISBN. The vendor said that this is
> very unusual.
>
> This should be corrected, don't you think?
>   
Who is the publisher? They'd be the ones to correct this.

-- 
Bob Gailer
510-978-4454


From cappy2112 at gmail.com  Wed Feb  7 22:50:12 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 7 Feb 2007 13:50:12 -0800
Subject: [Tutor] How does this work?
In-Reply-To: <45CA44F1.9060803@tds.net>
References: <8249c4ac0702061917h72147322ve5ce251cb37f6b29@mail.gmail.com>
	<45C9B2D0.60407@tds.net>
	<8249c4ac0702070744j10bedca6sa9fd612876a53d10@mail.gmail.com>
	<45C9FFAD.3040005@tds.net>
	<8249c4ac0702070925r7b10477es74bc56bc74987963@mail.gmail.com>
	<45CA1CF3.4050402@tds.net> <45CA44F1.9060803@tds.net>
Message-ID: <8249c4ac0702071350o1d3c5653kc25ca8582a1e342b@mail.gmail.com>

Thanks. I'm not using wx, but that doesn't matter.
I'll see if there's some way I can get the author to let me pass in the
logging handler to his main.

On 2/7/07, Kent Johnson <kent37 at tds.net> wrote:
> Kent Johnson wrote:
> > You should be able to make the logging module work with you, it is very
> > flexible. You should hook into the logging module. Write a custom
> > handler that pushes log methods into your GUI. Add the handler to the
> > root logger.
>

From alan.gauld at btinternet.com  Wed Feb  7 17:35:55 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 7 Feb 2007 16:35:55 -0000
Subject: [Tutor] I m trying to understand why we need Co-routines
References: <20070207082501.21565.qmail@web55212.mail.re4.yahoo.com>
Message-ID: <eqdhm4$d1c$1@sea.gmane.org>

"anil maran" <anilmrn at yahoo.com> wrote

> Yesterday I spoke to an employee of yahoo egroups and
> he was explaining that they used coroutines to send mails in egroups
> because each thread was 2mb in size...
>
> Can you point me to resources on how to use co-routines in python
> or if you have code samples it would be great

A coroutine is just a generic computing science term for
any technique that runs multiple tasks 'concurrently' within a
single process.

The normal way to do that nowadays is using threads, which
are supported in Python. Other approaches which are also
considered to be coroutines include generators (which allow
a task to be 'paused' in mid flow for example) and action lists
(lists of functions which are executed in turn by a top level
function. Common in real-time and embedded apps where
precise control of schedulling is needed). Coroutine programming
was common in the days of assembler where multi tasking
OS's and threading did not exist.

Interestingly the examples given in Wikipedia are closest to
the python generator example but those are not the most common
approach to coroutines in my experience...

HTH,

Alan G 



From alan.gauld at btinternet.com  Wed Feb  7 17:43:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 7 Feb 2007 16:43:05 -0000
Subject: [Tutor] python books
References: <f96f96bc0702070532m24dca1f2iedb17e969f38ae99@mail.gmail.com>
Message-ID: <eqdhm5$d1c$2@sea.gmane.org>

"govind goyal" <govindgoyal at gmail.com> wrote

> I want to purchase a python book but confused of which authur?
> I need suggestion.
> How is "Teach yoursef python in 24 hours by Ivan van laningham"?

Its aimed at the beginning programmer with no knowlege of 
other programming languages. It is based on the very old
version 1.5.1 of Python. It is a tutorial not a reference.

OTOH I found it quite an accessible book, and particularly 
good on the Tkinter GUI framework,  with 3 full chapters.
And if you are interested in Mayan calendars and Python 
it's essential reading. And the Mandelbrot example is fun too.

Given your other post I'd reckon that Learning Python or 
Core Python might be better bets. Both will last longer as 
references after you know the basics.

I assume you have already tackled the official Python 
web tutorial which is execellent?

HTH,

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


From frank.hoffsummer at gmail.com  Wed Feb  7 22:57:14 2007
From: frank.hoffsummer at gmail.com (frank h.)
Date: Wed, 7 Feb 2007 22:57:14 +0100
Subject: [Tutor] min max confusion
Message-ID: <60fae7c30702071357l277f89a6o610f7d3deca1881a@mail.gmail.com>

hello all
here is a disturbing session with min() and max() for which I have
absolutely no explanation

>>> t = (952L, 945L, 941L, 939L, 949L, 972L, 956L, 965L, 973L, 965L)
>>> min(t)
939L
>>> max(t)
exceptions.TypeError                                 Traceback (most recent
call last)
TypeError: 'int' object is not callable


why doesn't max(t) work?! I am using python 2.4.4
thanks for any insight you might have
-frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070207/f1d1a927/attachment-0001.html 

From frank.hoffsummer at gmail.com  Wed Feb  7 23:00:13 2007
From: frank.hoffsummer at gmail.com (frank h.)
Date: Wed, 7 Feb 2007 23:00:13 +0100
Subject: [Tutor] min max confusion
In-Reply-To: <60fae7c30702071357l277f89a6o610f7d3deca1881a@mail.gmail.com>
References: <60fae7c30702071357l277f89a6o610f7d3deca1881a@mail.gmail.com>
Message-ID: <60fae7c30702071400wd29717ft365fad84bc94bf51@mail.gmail.com>

:-))
turns out I found the problem: max was a local integer variable in my
namespace. as such it was obviously not callable....

On 2/7/07, frank h. <frank.hoffsummer at gmail.com> wrote:
>
> hello all
> here is a disturbing session with min() and max() for which I have
> absolutely no explanation
>
> >>> t = (952L, 945L, 941L, 939L, 949L, 972L, 956L, 965L, 973L, 965L)
> >>> min(t)
> 939L
> >>> max(t)
> exceptions.TypeError                                 Traceback (most
> recent call last)
> TypeError: 'int' object is not callable
>
>
> why doesn't max(t) work?! I am using python 2.4.4
> thanks for any insight you might have
> -frank
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070207/10336d69/attachment.htm 

From tim at johnsons-web.com  Wed Feb  7 14:23:29 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 7 Feb 2007 13:23:29 +0000
Subject: [Tutor] Problem with Reference Manual (duplicate ISBN)
In-Reply-To: <45CA45FE.1000801@alum.rpi.edu>
References: <200702071109.46601.tim@johnsons-web.com>
	<45CA45FE.1000801@alum.rpi.edu>
Message-ID: <200702071323.29436.tim@johnsons-web.com>

On Wednesday 07 February 2007 09:34 pm, Bob Gailer wrote:
> Tim Johnson wrote:
> > Nope, I'm not criticizing the writing or the technical info at...
> > Just the sloppy publishing.
> >
> > I ordered the Reference Manual for Version 2.5 and got Version 2.3
> > instead.
> > Reason, they have the same ISBN. The vendor said that this is
> > very unusual.
> >
> > This should be corrected, don't you think?
>
> Who is the publisher? They'd be the ones to correct this.

  Looks like it is "Network Theory Ltd" for both versions.
-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From alan.gauld at btinternet.com  Thu Feb  8 01:06:11 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 8 Feb 2007 00:06:11 -0000
Subject: [Tutor] What should go in a module?
References: <eqd8f2$80c$1@sea.gmane.org>
Message-ID: <eqdphq$7je$1@sea.gmane.org>


"Don Taylor" <nospamformeSVP at gmail.com> wrote

>I am looking for advice on module size.

There is no absolute answer to this.

> When I first came upon Python my initial thought was to package very
> closely-related things into modules. Modules would be small, and may
> contain a single class or function.  An application would consist of
> lots of modules.

Thats probably not the best approachj.
Remember that a module is basically a unit of reuse.
If you can't use a module simply by importting it then
its too small.

> package everything together into a single module and use separate
> modules only when that code might usefully be shared between 
> different
> applications.

Thats the critical factor. Split it up into reusable chunks.
If you have some functions and classes that together can be used
by another application make them into a module. If the module
can only be used by also importing some other module then keep
the two modules together as a single unit.

In other words modules should be as small as possible but
no smaller...

> I am really just asking about applications here, not libraries or
> frameworks.

The same rules apply. A module is a library in Python terms.

HTH,

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



From carroll at tjc.com  Thu Feb  8 02:26:33 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 7 Feb 2007 17:26:33 -0800 (PST)
Subject: [Tutor] python books
In-Reply-To: <eqdhm5$d1c$2@sea.gmane.org>
Message-ID: <Pine.LNX.4.44.0702071726040.12783-100000@violet.rahul.net>

On Wed, 7 Feb 2007, Alan Gauld wrote:

> And if you are interested in Mayan calendars and Python 
> it's essential reading. 

I think this should be nominated for QOTW.




From bgailer at alum.rpi.edu  Thu Feb  8 02:50:03 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 07 Feb 2007 17:50:03 -0800
Subject: [Tutor] Problem with Reference Manual (duplicate ISBN)
In-Reply-To: <200702071109.46601.tim@johnsons-web.com>
References: <200702071109.46601.tim@johnsons-web.com>
Message-ID: <45CA81CB.6000703@alum.rpi.edu>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070207/53d231e0/attachment.html 

From tim at johnsons-web.com  Wed Feb  7 19:31:44 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 7 Feb 2007 18:31:44 +0000
Subject: [Tutor] Problem with Reference Manual (duplicate ISBN)
In-Reply-To: <45CA81CB.6000703@alum.rpi.edu>
References: <200702071109.46601.tim@johnsons-web.com>
	<45CA81CB.6000703@alum.rpi.edu>
Message-ID: <200702071831.44682.tim@johnsons-web.com>

On Thursday 08 February 2007 01:50 am, Bob Gailer wrote:
 
> libraries, universities, wholesalers and distributors." IMHO the revision
> should be considered a new edition therefore have a new ISBN.
 
Right on! 

Hopefully this gets to someone with some contact with the
publisher.

thanks
tj

-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From rikard.bosnjakovic at gmail.com  Thu Feb  8 05:50:19 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 8 Feb 2007 05:50:19 +0100
Subject: [Tutor] What should go in a module?
In-Reply-To: <eqdphq$7je$1@sea.gmane.org>
References: <eqd8f2$80c$1@sea.gmane.org> <eqdphq$7je$1@sea.gmane.org>
Message-ID: <d9e88eaf0702072050q7ee04dfcle142b8bd5a42912c@mail.gmail.com>

On 2/8/07, Alan Gauld <alan.gauld at btinternet.com> wrote:

> > I am really just asking about applications here, not libraries or
> > frameworks.
> The same rules apply. A module is a library in Python terms.

I think he meant that he's developing applications only.

-- 
- Rikard.

From janos.juhasz at VELUX.com  Thu Feb  8 08:06:22 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 8 Feb 2007 08:06:22 +0100
Subject: [Tutor] min max confusion
In-Reply-To: <mailman.11288.1170885445.32030.tutor@python.org>
Message-ID: <OF880F366B.E3976370-ONC125727C.00264C48-C125727C.00270971@velux.com>

Hi Frank,


> From: "frank h." <frank.hoffsummer at gmail.com>
> Subject: [Tutor] min max confusion

> >>> t = (952L, 945L, 941L, 939L, 949L, 972L, 956L, 965L, 973L, 965L)
> >>> min(t)
> 939L
> >>> max(t)
> exceptions.TypeError                                 Traceback (most 
recent
> call last)
> TypeError: 'int' object is not callable

> 
> why doesn't max(t) work?! I am using python 2.4.4
> thanks for any insight you might have
> -frank


>>> t = (952L, 945L, 941L, 939L, 949L, 972L, 956L, 965L, 973L, 965L)
>>> min(t)
939L
>>> max(t)
973L

So it should works fine.

>>> help(max)
Help on built-in function max in module __builtin__:

max(...)
    max(sequence) -> value
    max(a, b, c, ...) -> value
 
    With a single sequence argument, return its largest item.
    With two or more arguments, return the largest argument.

The max() function should be overwritten like this:

>>> def max(a, b):
...     print b
... 

And it can be checked easy.

>>> help(max)
Help on function max in module __main__:

max(a, b)

>>> 

In this case, you can use the original builtin max() so:

>>> __builtin__.max()


Best regards,
Janos Juhasz

From thomas.coopman at gmail.com  Thu Feb  8 12:36:24 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Thu, 8 Feb 2007 12:36:24 +0100
Subject: [Tutor] comparing almost equal strings
Message-ID: <20070208123624.10a6e36e@localhost>

Hi,

I need a function that groups almost equal strings.  It seems most easy
to me, to do this with a hash function.

So I would write a hash function like this:
string = string.replace(" ", "").lower()[0:6]

and then hash the string chars, but it should detect minor typo's, so
words with one different char in the 6 chars, should have the same hash.

I think I once read something about it, but I can't find it, 
does somebody know how to do this?

Also do you think this is a good way, or do some of you have experience
with this and know a better way?

Thanks

From klappnase at freenet.de  Thu Feb  8 11:01:27 2007
From: klappnase at freenet.de (Michael Lange)
Date: Thu, 8 Feb 2007 11:01:27 +0100
Subject: [Tutor] same output on diferent sys.stdout.encodings
In-Reply-To: <45CA0CB2.3000905@sapo.pt>
References: <mailman.11117.1170806101.32030.tutor@python.org>
	<45CA0CB2.3000905@sapo.pt>
Message-ID: <20070208110127.61851750.klappnase@freenet.de>

On Wed, 07 Feb 2007 17:30:26 +0000
Paulino <paulino1 at sapo.pt> wrote:

> Hi everyone!
> 
> I have some strings that include special characters, to be displayed in 
> widget labels ( PyQt4 ).
> The output changes in diferent OS's due to diferent sys.stdout encoding
> 
> Not only the labels in the GUI change, but the source file strings are 
> altered when I move from win to linux and vice-versa.
> 
> The solution I found for now was to replace the special characters in 
> the source file string for their representation:
> I replaced "?" (e acute ) by "\xe9" wich correpsond to chr(233) in the 
> cp1252 encoding.
> 
> The character ? (e acute) in linux is not recognized in the source file, 
> neither in IDLE nor in Kate
> My win sys.stdout.encoding is cp850 and the linux one is utf-8
> 
> Now I have "d\xe9bito" instead of "d?bito" (debit in portuguese). By 
> passing the string through unicode with the convinient encoding, I 
> ensure the labels are exibithed the same  in every OS but, this way the 
> code is not very readable.
> 
> Is there a way of solving this, keeping the more readable?
> _______________________________________________

Have you tried to declare the encoding in use at the top of your Python source file, like:

# -*- coding: iso-8859-1 -*-

If you put this at the first line of your .py files (of course replace iso-8859-1 with whatever
encoding you use) I think this should do the trick.

I hope this helps

Michael

From yqiang at gmail.com  Thu Feb  8 08:18:33 2007
From: yqiang at gmail.com (Yi Qiang)
Date: Wed, 7 Feb 2007 23:18:33 -0800
Subject: [Tutor] resetting the python interpreter through manipulating
	globals()
Message-ID: <D682081E-92A7-4056-8E41-0A546FBFADC6@gmail.com>

Hi,
I have a program that talks to a python interpreter through pexpect  
(don't bother asking why ;).  What I would like to do is occasionally  
"reset" the interpreter to the state it would be in if it had just  
been launched.  I assumed I could simply clear out the globals()  
dictionary, minus '__builtins__' and some other important stuff, and  
recreate the globals.  But even a simple attempt has failed quite badly:

def reset_interpreter():
     r"""This method will reset a python interpreters globals  
dictionary with
         the one provided as the input parameter.
     """

     # This will just try to delete all non important keys in globals
     for k in globals().keys():
         print k
         if k == '__builtins__':
             continue
         else:
             try:
                 del globals()[k]
                 del locals()[k]
             except:
                 continue
     print globals()

This does not seem to work at all, any suggestions?


Yi




From kubota2550 at gmail.com  Thu Feb  8 12:28:57 2007
From: kubota2550 at gmail.com (kubota2550 at gmail.com)
Date: Thu, 8 Feb 2007 06:28:57 -0500
Subject: [Tutor] Program Control
Message-ID: <5900d730702080328x6c34cdewd4ee59056480a5d9@mail.gmail.com>

I am learning Python and have written several small programs of increasing
complexity but so far they are all "linear" programs meaning that they are
meant to do one thing.  I have yet to fully understand program control in
order to go to and return form modules (I think this is the correct term).
In other words, I have a menu which offers several options, I would like to
be able to combine several of my programs into seperate modules and put in
one larger program.  Then the user could select a menu item, be sent to a
module and return to the menu for another selection.  Can someone show me
how to do module or program control to accomplish the basic example below:

Main Menu
Select 1 for subtraction
Select 2 for addition
Select 3 to quit

***********************************
Subtraction module:
Enter a number
Enter a second number
Answer =Number1-Number2

Menu:

Select 1 to return to main menu
Select 2 to subract again

************************************
Addition module:
Enter a number
Enter a second number
Answer = Number1+Number2

Menu

Select 1 to return to main menu
Select 2 to add again
********************************************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070208/550d7c2a/attachment.htm 

From chris.arndt at web.de  Thu Feb  8 13:07:41 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 08 Feb 2007 13:07:41 +0100
Subject: [Tutor] comparing almost equal strings
In-Reply-To: <20070208123624.10a6e36e@localhost>
References: <20070208123624.10a6e36e@localhost>
Message-ID: <45CB128D.7040101@web.de>

thomas coopman schrieb:
> I need a function that groups almost equal strings.  It seems most easy
> to me, to do this with a hash function.

What do you mean be "almost equal"? By which criterium? Spelling,
Pronounciation? Semantics?

> I think I once read something about it, but I can't find it, 
> does somebody know how to do this?

Maybe you mean the "soundex" algorithm? See, for example, here:

http://diveintopython.org/performance_tuning/index.html

Chris

From johan at accesstel.co.za  Thu Feb  8 14:43:56 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 8 Feb 2007 15:43:56 +0200
Subject: [Tutor] Range of float value
Message-ID: <20070208133759.D52071792E@mail.accesstel.co.za>

Hi all,
 
I have a value that ranges between 48.01 and 48.57. a Float value in other
words.
 
I want to look at changes in the value. If my normal range is between 48.35
and 48.45, how will I identify the value below 48.35 and above 48.45?
 
Something I tried was:
 
for a in range(48.35, 48.45):
    print a
 
It gives me a value of 100.
 
Is it possible to get a range of a float value?
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.30/674 - Release Date: 2007/02/07
03:33 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070208/b7d2a61f/attachment.htm 

From kent37 at tds.net  Thu Feb  8 15:33:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 09:33:18 -0500
Subject: [Tutor] Program Control
In-Reply-To: <5900d730702080328x6c34cdewd4ee59056480a5d9@mail.gmail.com>
References: <5900d730702080328x6c34cdewd4ee59056480a5d9@mail.gmail.com>
Message-ID: <45CB34AE.50106@tds.net>

kubota2550 at gmail.com wrote:
> I am learning Python and have written several small programs of 
> increasing complexity but so far they are all "linear" programs meaning 
> that they are meant to do one thing.  I have yet to fully understand 
> program control in order to go to and return form modules (I think this 
> is the correct term).  In other words, I have a menu which offers 
> several options, I would like to be able to combine several of my 
> programs into seperate modules and put in one larger program.

See for example
"Modules and Functions" in http://www.freenetpages.co.uk/hp/alan.gauld/
http://swaroopch.info/text/Byte_of_Python:Modules#Making_your_own_modules
http://docs.python.org/tut/node8.html

Kent


From kent37 at tds.net  Thu Feb  8 15:35:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 09:35:15 -0500
Subject: [Tutor] Range of float value
In-Reply-To: <20070208133759.D52071792E@mail.accesstel.co.za>
References: <20070208133759.D52071792E@mail.accesstel.co.za>
Message-ID: <45CB3523.4040908@tds.net>

Johan Geldenhuys wrote:
> Hi all,
>  
> I have a value that ranges between 48.01 and 48.57. a Float value in 
> other words.
>  
> I want to look at changes in the value. If my normal range is between 
> 48.35 and 48.45, how will I identify the value below 48.35 and above 48.45?
>  
> Something I tried was:
>  
> for a in range(48.35, 48.45):
>     print a
>  
> It gives me a value of 100.
>  
> Is it possible to get a range of a float value?

You can't generate all the float values in a range. (OK, you probably 
could, but it would not be practical or useful.) You can test for a 
value in a range, e.g.
if 48.35 <= a <= 48.45:
   # do something

Kent


From kent37 at tds.net  Thu Feb  8 15:38:46 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 09:38:46 -0500
Subject: [Tutor] same output on diferent sys.stdout.encodings
In-Reply-To: <45CA0CB2.3000905@sapo.pt>
References: <mailman.11117.1170806101.32030.tutor@python.org>
	<45CA0CB2.3000905@sapo.pt>
Message-ID: <45CB35F6.8000201@tds.net>

Paulino wrote:
> Hi everyone!
> 
> I have some strings that include special characters, to be displayed in 
> widget labels ( PyQt4 ).
> The output changes in diferent OS's due to diferent sys.stdout encoding
> 
> Not only the labels in the GUI change, but the source file strings are 
> altered when I move from win to linux and vice-versa.
> 
> The solution I found for now was to replace the special characters in 
> the source file string for their representation:
> I replaced "?" (e acute ) by "\xe9" wich correpsond to chr(233) in the 
> cp1252 encoding.
> 
> The character ? (e acute) in linux is not recognized in the source file, 
> neither in IDLE nor in Kate
> My win sys.stdout.encoding is cp850 and the linux one is utf-8
> 
> Now I have "d\xe9bito" instead of "d?bito" (debit in portuguese). By 
> passing the string through unicode with the convinient encoding, I 
> ensure the labels are exibithed the same  in every OS but, this way the 
> code is not very readable.
> 
> Is there a way of solving this, keeping the more readable?

I think the problem you are having is with the source code encoding, not 
sys.stdout.encoding. Probably your editor on linux expects a different 
file encoding than what you are using in Windows. Your windows editor is 
probably using cp1252; perhaps the linux editor expects utf-8.

You need to get the editors to agree on the source code encoding. Then 
put the coding declaration at the top of the file as Michael suggested.

Kent


From kubota2550 at gmail.com  Thu Feb  8 16:11:40 2007
From: kubota2550 at gmail.com (kubota2550 at gmail.com)
Date: Thu, 8 Feb 2007 10:11:40 -0500
Subject: [Tutor] Program Control
In-Reply-To: <45CB34AE.50106@tds.net>
References: <5900d730702080328x6c34cdewd4ee59056480a5d9@mail.gmail.com>
	<45CB34AE.50106@tds.net>
Message-ID: <5900d730702080711r76d3b3e4gf7418e0ca0df05a2@mail.gmail.com>

Maybe I'm asking the wrong question.  This appears that a module is a
external program.  What I've seen on some programs but don't fully
understand is something of the sort: def main() and a def  sub() and def
add().  It appears that the program has calls to each of these sections.
The term module may be incorrect here.  I would  like to have all of my code
in one program but be able to call sections of code and return from them to
the main app.  That's where I'm lost.

On 2/8/07, Kent Johnson <kent37 at tds.net> wrote:
>
> kubota2550 at gmail.com wrote:
> > I am learning Python and have written several small programs of
> > increasing complexity but so far they are all "linear" programs meaning
> > that they are meant to do one thing.  I have yet to fully understand
> > program control in order to go to and return form modules (I think this
> > is the correct term).  In other words, I have a menu which offers
> > several options, I would like to be able to combine several of my
> > programs into seperate modules and put in one larger program.
>
> See for example
> "Modules and Functions" in http://www.freenetpages.co.uk/hp/alan.gauld/
> http://swaroopch.info/text/Byte_of_Python:Modules#Making_your_own_modules
> http://docs.python.org/tut/node8.html
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070208/ffa27499/attachment.htm 

From paulino1 at sapo.pt  Thu Feb  8 16:29:45 2007
From: paulino1 at sapo.pt (Paulino)
Date: Thu, 08 Feb 2007 15:29:45 +0000
Subject: [Tutor] same output on diferent sys.stdout.encodings
In-Reply-To: <mailman.53.1170932412.24678.tutor@python.org>
References: <mailman.53.1170932412.24678.tutor@python.org>
Message-ID: <45CB41E9.9060500@sapo.pt>

Yes I have that declaration in my script.

Paulino


> Send Tutor mailing list submissions to
> 	tutor at python.org
>
>   

# -*- coding: iso-8859-1 -*-

If you put this at the first line of your .py files (of course replace iso-8859-1 with whatever
encoding you use) I think this should do the trick.

I hope this helps

Michael


------------------------------


From paulino1 at sapo.pt  Thu Feb  8 16:35:22 2007
From: paulino1 at sapo.pt (Paulino)
Date: Thu, 08 Feb 2007 15:35:22 +0000
Subject: [Tutor] same output on diferent sys.stdout.encodings
In-Reply-To: <45CB35F6.8000201@tds.net>
References: <mailman.11117.1170806101.32030.tutor@python.org>
	<45CA0CB2.3000905@sapo.pt> <45CB35F6.8000201@tds.net>
Message-ID: <45CB433A.60507@sapo.pt>

Yes that is the problem.

But I canot control all the the encodings in every PC that the script is 
to be run...

Paulino


Kent Johnson escreveu:
>
> I think the problem you are having is with the source code encoding, 
> not sys.stdout.encoding. Probably your editor on linux expects a 
> different file encoding than what you are using in Windows. Your 
> windows editor is probably using cp1252; perhaps the linux editor 
> expects utf-8.
>
> You need to get the editors to agree on the source code encoding. Then 
> put the coding declaration at the top of the file as Michael suggested.
>
> Kent
>
>
>


From eike.welk at gmx.net  Thu Feb  8 16:48:16 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Thu, 08 Feb 2007 16:48:16 +0100
Subject: [Tutor] same output on diferent sys.stdout.encodings
In-Reply-To: <45CA0CB2.3000905@sapo.pt>
References: <mailman.11117.1170806101.32030.tutor@python.org>
	<45CA0CB2.3000905@sapo.pt>
Message-ID: <200702081648.16713.eike.welk@gmx.net>

The Kate editor has also modelines, similar to the python interpreter:
http://kate-editor.org/article/katepart_modelines

HTH,
Eike.


From kent37 at tds.net  Thu Feb  8 17:09:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 11:09:05 -0500
Subject: [Tutor] same output on diferent sys.stdout.encodings
In-Reply-To: <45CB433A.60507@sapo.pt>
References: <mailman.11117.1170806101.32030.tutor@python.org>
	<45CA0CB2.3000905@sapo.pt> <45CB35F6.8000201@tds.net>
	<45CB433A.60507@sapo.pt>
Message-ID: <45CB4B21.7030300@tds.net>

Paulino wrote:
> Yes that is the problem.
> 
> But I canot control all the the encodings in every PC that the script is 
> to be run...

The problem is in your *editor* not in Python. You have to control the 
encoding the *editor* expects. At least that is my guess - your 
complaint is that you can't find a way to represent the character that 
displays correctly in editors on both platforms.

In other words, if you have a Python file that includes characters in 
cp1252 and you open the file in an editor that expects utf-8, it will 
not display correctly.

Kent


From kent37 at tds.net  Thu Feb  8 17:10:30 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 11:10:30 -0500
Subject: [Tutor] Program Control
In-Reply-To: <5900d730702080711r76d3b3e4gf7418e0ca0df05a2@mail.gmail.com>
References: <5900d730702080328x6c34cdewd4ee59056480a5d9@mail.gmail.com>	
	<45CB34AE.50106@tds.net>
	<5900d730702080711r76d3b3e4gf7418e0ca0df05a2@mail.gmail.com>
Message-ID: <45CB4B76.2080600@tds.net>

kubota2550 at gmail.com wrote:
> Maybe I'm asking the wrong question.  This appears that a module is a 
> external program.  What I've seen on some programs but don't fully 
> understand is something of the sort: def main() and a def  sub() and def 
> add().  It appears that the program has calls to each of these 
> sections.  The term module may be incorrect here.  I would  like to have 
> all of my code in one program but be able to call sections of code and 
> return from them to the main app.  That's where I'm lost.

Then it sounds like you need to learn about functions. The same 
tutorials, different sections.

Kent


From rabidpoobear at gmail.com  Thu Feb  8 17:29:56 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 08 Feb 2007 10:29:56 -0600
Subject: [Tutor] Range of float value
In-Reply-To: <45CB3523.4040908@tds.net>
References: <20070208133759.D52071792E@mail.accesstel.co.za>
	<45CB3523.4040908@tds.net>
Message-ID: <45CB5004.30706@gmail.com>

Kent Johnson wrote:
> Johan Geldenhuys wrote:
>   
>> Hi all,
>>  
>> I have a value that ranges between 48.01 and 48.57. a Float value in 
>> other words.
>>  
>> I want to look at changes in the value. If my normal range is between 
>> 48.35 and 48.45, how will I identify the value below 48.35 and above 48.45?
>>  
>> Something I tried was:
>>  
>> for a in range(48.35, 48.45):
>>     print a
>>  
>> It gives me a value of 100.
>>  
>> Is it possible to get a range of a float value?
>>     
>
> You can't generate all the float values in a range. (OK, you probably 
> could, but it would not be practical or useful.) You can test for a 
> value in a range, e.g.
> if 48.35 <= a <= 48.45:
>   
Kent:
Why does this work?
In C++ this would go from

if (48.35 <= a <= 48.45)

to (assuming the right condition is met)

if (48.35 <= true)

because it evaluates these things right to left, doesn't it?
does python treat chained comparisons differently than C++ or is C++ 
behaving differently than I think it does?
Thanks for your help,
-Luke

From kent37 at tds.net  Thu Feb  8 17:41:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 11:41:40 -0500
Subject: [Tutor] Range of float value
In-Reply-To: <45CB5004.30706@gmail.com>
References: <20070208133759.D52071792E@mail.accesstel.co.za>
	<45CB3523.4040908@tds.net> <45CB5004.30706@gmail.com>
Message-ID: <45CB52C4.8030107@tds.net>

Luke Paireepinart wrote:
> Kent Johnson wrote:

>> You can't generate all the float values in a range. (OK, you probably 
>> could, but it would not be practical or useful.) You can test for a 
>> value in a range, e.g.
>> if 48.35 <= a <= 48.45:
>>   
> Kent:
> Why does this work?

It is explicitly supported in Python. See
file:///C:/Python25/Doc/ref/comparisons.html

which says, "Comparisons can be chained arbitrarily, e.g., x < y <= z is 
equivalent to x < y and y <= z, except that y is evaluated only once 
(but in both cases z is not evaluated at all when x < y is found to be 
false)."

Kent

> In C++ this would go from
> 
> if (48.35 <= a <= 48.45)
> 
> to (assuming the right condition is met)
> 
> if (48.35 <= true)
> 
> because it evaluates these things right to left, doesn't it?
> does python treat chained comparisons differently than C++ or is C++ 
> behaving differently than I think it does?
> Thanks for your help,
> -Luke
> 
> 



From andreengels at gmail.com  Thu Feb  8 18:16:49 2007
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 8 Feb 2007 18:16:49 +0100
Subject: [Tutor] Range of float value
In-Reply-To: <20070208133759.D52071792E@mail.accesstel.co.za>
References: <20070208133759.D52071792E@mail.accesstel.co.za>
Message-ID: <6faf39c90702080916ta3bc50ag39b64c5cd3029019@mail.gmail.com>

2007/2/8, Johan Geldenhuys <johan at accesstel.co.za>:
>
>  Hi all,
>
> I have a value that ranges between 48.01 and 48.57. a Float value in other
> words.
>
> I want to look at changes in the value. If my normal range is between
> 48.35 and 48.45, how will I identify the value below 48.35 and above 48.45
> ?
>
> Something I tried was:
>
> for a in range(48.35, 48.45):
>     print a
>
> It gives me a value of 100.
>
> Is it possible to get a range of a float value?
>

It depends. What would you like it to be? All numbers in that range? They're
uncountably infinite, so no way we could ever get that out of the computer.
All actual float values? Depends too much on the implementation of the
specific machine you're working on to be workable.

Identifying values below 48.35 and above 48.45 is simply done by:
if value < 48.35 or value > 48.45 then...

No need to first create the range of values

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070208/c0d6f1f8/attachment.htm 

From rabidpoobear at gmail.com  Thu Feb  8 18:48:23 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 08 Feb 2007 11:48:23 -0600
Subject: [Tutor] Range of float value
In-Reply-To: <45CB52C4.8030107@tds.net>
References: <20070208133759.D52071792E@mail.accesstel.co.za>
	<45CB3523.4040908@tds.net> <45CB5004.30706@gmail.com>
	<45CB52C4.8030107@tds.net>
Message-ID: <45CB6267.7080706@gmail.com>

Kent Johnson wrote:
> Luke Paireepinart wrote:
>> Kent Johnson wrote:
>
>>> You can't generate all the float values in a range. (OK, you 
>>> probably could, but it would not be practical or useful.) You can 
>>> test for a value in a range, e.g.
>>> if 48.35 <= a <= 48.45:
>>>   
>> Kent:
>> Why does this work?
>
> It is explicitly supported in Python. See
> file:///C:/Python25/Doc/ref/comparisons.html
Do you mean http://docs.python.org/ref/comparisons.html ?
:)

From kent37 at tds.net  Thu Feb  8 19:04:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 13:04:15 -0500
Subject: [Tutor] Range of float value
In-Reply-To: <45CB6267.7080706@gmail.com>
References: <20070208133759.D52071792E@mail.accesstel.co.za>
	<45CB3523.4040908@tds.net> <45CB5004.30706@gmail.com>
	<45CB52C4.8030107@tds.net> <45CB6267.7080706@gmail.com>
Message-ID: <45CB661F.7000608@tds.net>

Luke Paireepinart wrote:
> Kent Johnson wrote:
>> Luke Paireepinart wrote:
>>> Kent Johnson wrote:
>>>> You can't generate all the float values in a range. (OK, you 
>>>> probably could, but it would not be practical or useful.) You can 
>>>> test for a value in a range, e.g.
>>>> if 48.35 <= a <= 48.45:
>>>>   
>>> Kent:
>>> Why does this work?
>> It is explicitly supported in Python. See
>> file:///C:/Python25/Doc/ref/comparisons.html
> Do you mean http://docs.python.org/ref/comparisons.html ?

Jeez. I try so hard to bust out of here and every turn I take just 
brings me back to file://.

Now where did I put that internet, anyway?

Kent


From johan at accesstel.co.za  Thu Feb  8 20:09:04 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 8 Feb 2007 21:09:04 +0200
Subject: [Tutor] Range of float value
In-Reply-To: <6faf39c90702080916ta3bc50ag39b64c5cd3029019@mail.gmail.com>
Message-ID: <200702081903.l18J3lKv002453@mail.mtn.co.za>

OK, this what I wanted:
 
I have a value: a = 48.41
 
My lowValue is: lowValue = 48.35
My highValue is : highvalue = 48.45
 
if a <= lowValue:
    print 'value below limit'
 
if a >= highValue:
    print value above limit'
 
I though that it could be possible to have a range between 48.35 and 48.45
that could have a step of 0.1
 
This works fine with normal intgers:
 
>>> def lookAtRange(a):
...     if a in range(40, 110, 10):        #Would like to have: if a in
range(48.35, 48.45, 0.1):
...         print 'In limits'
...     else:
...         print 'Out of limits'
...         
>>> lookAtRange(40)
In limits
>>> lookAtRange(50)
In limits
>>> 
>>> lookAtRange(20)
Out of limits
>>> 
>>> lookAtRange(120)
Out of limits
>>> 
 
Johan
 

   _____  

From: Andre Engels [mailto:andreengels at gmail.com] 
Sent: 08 February 2007 07:17 PM
To: johan at accesstel.co.za
Cc: tutor at python.org
Subject: Re: [Tutor] Range of float value


2007/2/8, Johan Geldenhuys <HYPERLINK
"mailto:johan at accesstel.co.za"johan at accesstel.co.za>: 

Hi all,
 
I have a value that ranges between 48.01 and 48.57. a Float value in other
words.
 
I want to look at changes in the value. If my normal range is between 48.35
and 48.45, how will I identify the value below 48.35 and above 48.45?
 
Something I tried was:
 
for a in range(48.35, 48.45):
    print a
 
It gives me a value of 100.
 
Is it possible to get a range of a float value?


It depends. What would you like it to be? All numbers in that range? They're
uncountably infinite, so no way we could ever get that out of the computer.
All actual float values? Depends too much on the implementation of the
specific machine you're working on to be workable. 

Identifying values below 48.35 and above 48.45 is simply done by:
if value < 48.35 or value > 48.45 then...

No need to first create the range of values

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


--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.30/674 - Release Date: 2007/02/07
03:33 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.30/674 - Release Date: 2007/02/07
03:33 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070208/8aef4d3c/attachment.html 

From kent37 at tds.net  Thu Feb  8 20:32:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Feb 2007 14:32:47 -0500
Subject: [Tutor] Range of float value
In-Reply-To: <200702081903.l18J3lKv002453@mail.mtn.co.za>
References: <200702081903.l18J3lKv002453@mail.mtn.co.za>
Message-ID: <45CB7ADF.6060506@tds.net>

Johan Geldenhuys wrote:
> OK, this what I wanted:
>  
> I have a value: a = 48.41
>  
> My lowValue is: lowValue = 48.35
> My highValue is : highvalue = 48.45
>  
> if a <= lowValue:
>     print 'value below limit'
>  
> if a >= highValue:
>     print value above limit'
>  
> I though that it could be possible to have a range between 48.35 and 
> 48.45 that could have a step of 0.1

What is wrong with
def lookAtRange(a):
   if lowValue <= a <= highValue:
     print 'In limits'
..etc
??

>  
> This works fine with normal intgers:
>  
> *>>> def lookAtRange(a):
> ...     if a in range(40, 110, 10):        *#Would like to have: if a in 
> range(48.35, 48.45, 0.1):
> *...         print 'In limits'
> ...     else:
> ...         print 'Out of limits'
> ...        
>> >> lookAtRange(40)
> In limits
>> >> lookAtRange(50)
> In limits
>> >>
>> >> lookAtRange(20)
> Out of limits
>> >>
>> >> lookAtRange(120)
> Out of limits
>> >> *

Are you sure this is what you want? Have you tried lookAtRange(45) for 
example?

The range function creates a list of integers:
In [1]: range(40, 110, 10)
Out[1]: [40, 50, 60, 70, 80, 90, 100]

The 'in' operator tests for membership. 40 is in the list; 20 and 45 are 
not.

I think even in the case of integers the range test with < is what you want.

Kent


From pytutmail at gmail.com  Fri Feb  9 00:03:18 2007
From: pytutmail at gmail.com (Toon Pieton)
Date: Fri, 9 Feb 2007 00:03:18 +0100
Subject: [Tutor] Debugging
Message-ID: <7c3104d20702081503m46e829efu6f6f8760d136b3b7@mail.gmail.com>

Hey friendly users!

I have a question considering debugging: is it possible to get the current
code line that is being executed?

Thanks in advance!
Toon Pieton
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070209/c7b77801/attachment.htm 

From john at fouhy.net  Fri Feb  9 00:08:30 2007
From: john at fouhy.net (John Fouhy)
Date: Fri, 9 Feb 2007 12:08:30 +1300
Subject: [Tutor] Debugging
In-Reply-To: <7c3104d20702081503m46e829efu6f6f8760d136b3b7@mail.gmail.com>
References: <7c3104d20702081503m46e829efu6f6f8760d136b3b7@mail.gmail.com>
Message-ID: <5e58f2e40702081508q3029ca92ub3736a730f04b369@mail.gmail.com>

On 09/02/07, Toon Pieton <pytutmail at gmail.com> wrote:
> Hey friendly users!
>
> I have a question considering debugging: is it possible to get the current
> code line that is being executed?

Are you using pdb [the python debugger]?

If you have a script 'myscript.py', you can start the script like this:

  python -m pdb myscript.py

You can then set breakpoints and step through the code line-by-line using pdb.

(brief summary:

'break module:line' -- set breakpoint, eg: 'break mymodule:23'
'r' -- run program
'n' -- move to next line
's' -- move to next line, or step into function call
'c' -- continue running until next breakpoint
'p' -- print; used to inspect variables, etc.
)

Note that pdb has difficulties with multithreaded programs.

-- 
John.

From jalilsan at gmail.com  Fri Feb  9 00:16:27 2007
From: jalilsan at gmail.com (Jalil)
Date: Thu, 8 Feb 2007 15:16:27 -0800
Subject: [Tutor] file open error
Message-ID: <5850ed90702081516q51f85dfam1d011f05a7581d9f@mail.gmail.com>

Hey guys,

I have this simple code and i cant seem to get it to run.
here is the code.


from os import *
import re

hostname =raw_input("Host name : ") or '<unknown>'
mac_addr =input("Mac address : ")

filename='/etc/dhcpd.conf'
fh=open(filename)

m = re.match(hostname,fh.readlines())
if m!=None:
    m.group()


Here is the error I get when i try to run the code


monkeysee% python sys_wireless.py
Host name :
Mac address : 1234567
Traceback (most recent call last):
  File "sys_wireless.py", line 8, in ?
    fh=open("/etc/dhcpd.conf","r")
TypeError: an integer is required



I dont know what the issue is?

any hints ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070208/3ea0737b/attachment.html 

From john at fouhy.net  Fri Feb  9 00:33:14 2007
From: john at fouhy.net (John Fouhy)
Date: Fri, 9 Feb 2007 12:33:14 +1300
Subject: [Tutor] file open error
In-Reply-To: <5850ed90702081516q51f85dfam1d011f05a7581d9f@mail.gmail.com>
References: <5850ed90702081516q51f85dfam1d011f05a7581d9f@mail.gmail.com>
Message-ID: <5e58f2e40702081533n45bbd094p4a4c34e726b22f7d@mail.gmail.com>

On 09/02/07, Jalil <jalilsan at gmail.com> wrote:

Hi Jalil,

Because you're doing this:

> from os import *

It means that when you get to this line:

> fh=open(filename)

You're actually calling os.open, which is lower-level than the
standard open() and expects different arguments.

Many people recommend not doing "from .. import *" if you can possibly
avoid it because of this precise problem!

-- 
John.

From bill at celestial.net  Fri Feb  9 00:34:51 2007
From: bill at celestial.net (Bill Campbell)
Date: Thu, 8 Feb 2007 15:34:51 -0800
Subject: [Tutor] file open error
In-Reply-To: <5850ed90702081516q51f85dfam1d011f05a7581d9f@mail.gmail.com>
References: <5850ed90702081516q51f85dfam1d011f05a7581d9f@mail.gmail.com>
Message-ID: <20070208233451.GA10804@ayn.mi.celestial.com>

On Thu, Feb 08, 2007, Jalil wrote:
>
>   Hey guys,
>   I have this simple code and i cant seem to get it to run.
>   here is the code.
>   from os import *
>   import re
>   hostname =raw_input("Host name : ") or '<unknown>'
>   mac_addr =input("Mac address : ")
>   filename='/etc/dhcpd.conf'
>   fh=open(filename)
>   m = re.match(hostname,fh.readlines())
>   if m!=None:
>       m.group()
>   Here is the error I get when i try to run the code
>   monkeysee% python sys_wireless.py
>   Host name :
>   Mac address : 1234567
>   Traceback (most recent call last):
>     File "sys_wireless.py", line 8, in ?
>       fh=open("/etc/dhcpd.conf","r")
>   TypeError: an integer is required
>   I dont know what the issue is?
>   any hints ?

It appears to me that your ``from os import *'' is biting you in
the butt as the os.open command is being executed instead of the
normal open.

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

``Liberty don't work as good in practice as it does in speeches.''
    Will Rogers

From sudarshana.ks at gmail.com  Fri Feb  9 01:39:27 2007
From: sudarshana.ks at gmail.com (Sudarshana KS)
Date: Fri, 9 Feb 2007 06:09:27 +0530
Subject: [Tutor] Converting \x0e to string 0e in python
Message-ID: <8036f2bb0702081639x7a149bc2yc7e5beabcb5c9c4f@mail.gmail.com>

Hi,

Currently i have data with the following type - Which is a x509 certificate
obtained from SSL server done. I need this to be converted to normal string,
so that i can use the load_certificate method of OpenSSL, which takes string
as the argument.

Kindly help me.


cert=
'\x00\x01\xa20\x82\x01\x9e0\x82\x01(\x02\x01\x000\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05\x000:1
\x120\x10\x06\x03U\x04\x03\x13\tConst2-
2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r
\x01\t\x02\x16\tConst2-
2.0\x1e\x17\r070207210438Z\x17\r170204210438Z0:1\x120\x10\x06\x03U\x04\x03
\x13\tConst2-
2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r\x01\t\x02\x16\tConst2-2.0|0\r
\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03k\x000h\x02a\x00\xc2\x99e2\xd0\xa5\xb67\x80iv.\x12I\x17
\xaa\xee9S\xdc\xee\xa1!\xb4\x94/\xf8\xe2\x0e%V\xdc\xa8%\x04\x03\x8dl\\\x8cJ\xec\x13\xd7\xe2\x96\x1b\xa8`
\xdf$\xfe\xb9\x9a\xf9\xb7[\x8f\xe6\xc7U?&l\x04D\xfc\xd7\x96\x99\x04\xb1\x8c\xcd\xc3[\x17\xba\xb2+g5L
\x08~3B\xf9\x1dV\x1a\x84\x0eW\x94\x1f\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05
\x00\x03a\x009f\x8c\xf8C\xcb0\xc8\x8e\xa2\xaeV\xc8 at .<\xae\xc7\xf6l\xeam2\x8f[Z\xde\xd0\xbf\xd7\xd1/
\xbd\x14\x89\xd1 at s\x97\x02\x887\xcb\xf6#hNIG\xdb\x10\xe5A\x04\x19~8\x7f\xf3T\xaf\xdeY%\xc5if\xe4
\x88\xce|v\xb2\xc35#\xc5\xa7\xec\xdca\x12\xd8*\xc3k\xf8\x911}!\x861\xe2;\xd7'


-- 
Regards,
Sudarshana K S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070209/4f2c487d/attachment.html 

From Barry.Carroll at psc.com  Fri Feb  9 03:07:40 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Thu, 8 Feb 2007 18:07:40 -0800
Subject: [Tutor] Property Question (Was: RE: Overloading assignment operator)
In-Reply-To: <8249c4ac0702081741s7b331d62xafdc5a3917438a66@mail.gmail.com>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595AE5@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> From: Tony Cappellini [mailto:cappy2112 at gmail.com]
> Sent: Thursday, February 08, 2007 5:41 PM
> To: Carroll, Barry
> Subject: re:Overloading assignment operator
> 
> Hello Barry
> 
> I'm trying to understand you post
> 
> my question is, should this line
> 
> result = property(get_result, set_result)
> 
> actually be
> 
> self.result = property(get_result, set_result)
> 
> if result is an instance variable?
> 
> Or did you intend it to be a class variable?
> 
> Properties always confused me.
> 
> 
> thanks
> 
> Overloading assignment operator
> Carroll, Barry Barry.Carroll at psc.com
> Wed Jan 24 00:32:34 CET 2007
> 
> Hello, Achim,
> 
> * ...here is where
> * properties become useful.  you can create a getter, setter, and even
a
> * deleter and doc string if you want. here's how you use it... add the
> * following to your class:
> 
> * def get_result(self):
> *     return self.__result
> *
> * def set_result (self, expression):
> *     self.__result = expression
> *
> * result = property(get_result, set_ result, doc='result of
operations')
> *
> * -----
> *
> 
> I have tested this using the admittedly simple-minded code snipped
> below.
> 
> >>>>>>>>>>
> @BCARROLL[Python]|3> class Aclass:
>                  |.>     def __init__(self):
>                  |.>         __result = None
>                  |.>     def get_result(self):
>                  |.>         return self.__result
>                  |.>     def set_result (self, result):
>                  |.>         self.__result = result
>                  |.>     result = property(get_result, set_result,
> doc='result of expression')
>                  |.>
> @BCARROLL[Python]|5> a = Aclass()
> @BCARROLL[Python]|7> a.result = 2*3
> @BCARROLL[Python]|8> a.result
>                  <8> 6
> @BCARROLL[Python]|9> a.result = 25.0 * 5.25
> @BCARROLL[Python]|10> a.result
>                  <10> 131.25
> @BCARROLL[Python]|11>
Hello, Tony:

First off, it's always a good idea to respond to the mailing list
instead of directly to an individual.  Everyone benefits from the
information instead of just one person.  Besides, if I make a mistake
(something I fo depressingly often) someone else on the list can correct
it so you get the right info.

Anyway, to your question: "result" vs "self.result".  Look at the
interpreter session snippet above.  The assignment to "result" is inside
the class definition, so it is an attribute of Aclass.  At this point
"Aclass.result" is indeed a class variable.  Or, perhaps more correctly,
a class property.  

However, when "a" is set to "Aclass()", an instance of Aclass is created
and given the name "a".  "a.result" is therefore an instance variable.
I never use the class variable "Aclass.result".  

Does that help any?

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 kent37 at tds.net  Fri Feb  9 06:19:11 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Feb 2007 00:19:11 -0500
Subject: [Tutor] Converting \x0e to string 0e in python
In-Reply-To: <8036f2bb0702081639x7a149bc2yc7e5beabcb5c9c4f@mail.gmail.com>
References: <8036f2bb0702081639x7a149bc2yc7e5beabcb5c9c4f@mail.gmail.com>
Message-ID: <45CC044F.9080905@tds.net>

Sudarshana KS wrote:
> Hi,
> 
> Currently i have data with the following type - Which is a x509 
> certificate obtained from SSL server done. I need this to be converted 
> to normal string, so that i can use the load_certificate method of 
> OpenSSL, which takes string as the argument.

The below data is a string. It contains lots of non-ascii values which 
are printed as \x escapes, but it is still a string. Have you tried 
passing it to load_certificate? What happened?

Kent

> 
> Kindly help me.
> 
> 
> cert= 
> '\x00\x01\xa20\x82\x01\x9e0\x82\x01(\x02\x01\x000\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05\x000:1
> \x120\x10\x06\x03U\x04\x03\x13\tConst2-2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r 
> 
> \x01\t\x02\x16\tConst2-2.0\x1e\x17\r070207210438Z\x17\r170204210438Z0:1\x120\x10\x06\x03U\x04\x03
> \x13\tConst2-2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r\x01\t\x02\x16\tConst2-2.0|0\r
> \x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03k\x000h\x02a\x00\xc2\x99e2\xd0\xa5\xb67\x80iv.\x12I\x17 
> 
> \xaa\xee9S\xdc\xee\xa1!\xb4\x94/\xf8\xe2\x0e%V\xdc\xa8%\x04\x03\x8dl\\\x8cJ\xec\x13\xd7\xe2\x96\x1b\xa8`
> \xdf$\xfe\xb9\x9a\xf9\xb7[\x8f\xe6\xc7U?&l\x04D\xfc\xd7\x96\x99\x04\xb1\x8c\xcd\xc3[\x17\xba\xb2+g5L
> \x08~3B\xf9\x1dV\x1a\x84\x0eW\x94\x1f\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05 
> 
> \x00\x03a\x009f\x8c\xf8C\xcb0\xc8\x8e\xa2\xaeV\xc8 at .<\xae\xc7\xf6l\xeam2\x8f[Z\xde\xd0\xbf\xd7\xd1/
> \xbd\x14\x89\xd1 at s\x97\x02\x887\xcb\xf6#hNIG\xdb\x10\xe5A\x04\x19~8\x7f\xf3T\xaf\xdeY%\xc5if\xe4
> \x88\xce|v\xb2\xc35#\xc5\xa7\xec\xdca\x12\xd8*\xc3k\xf8\x911}!\x861\xe2;\xd7' 
> 
> 
> 
> -- 
> Regards,
> Sudarshana K S
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From dyoo at cs.wpi.edu  Thu Feb  8 23:23:04 2007
From: dyoo at cs.wpi.edu (Daniel Yoo)
Date: Thu, 8 Feb 2007 17:23:04 -0500 (EST)
Subject: [Tutor] Range of float value
In-Reply-To: <200702081903.l18J3lKv002453@mail.mtn.co.za>
References: <200702081903.l18J3lKv002453@mail.mtn.co.za>
Message-ID: <Pine.LNX.4.63.0702081532070.27841@cs.wpi.edu>



On Thu, 8 Feb 2007, Johan Geldenhuys wrote:

> OK, this what I wanted:
>
> I have a value: a = 48.41
>
> My lowValue is: lowValue = 48.35
> My highValue is : highvalue = 48.45

Range does not work on floats: it's meant to work on integers.



> I though that it could be possible to have a range between 48.35 and 48.45
> that could have a step of 0.1

There's an unsafe assumption here: in general, comparing floats for 
equality won't work unless you are very very careful.  See:

     http://www.python.org/doc/tut/node16.html

Because floats aren't directly comparable (at least under normal cases), 
that negates the idea of build a list of floats and comparing for equality 
against one of them.

However, Kent mentioned a solution that should work better, a chained 
comparison:

     a <= b <= c

which is true if b is squeezed between a and b.

From thomas.coopman at gmail.com  Fri Feb  9 07:44:43 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Fri, 9 Feb 2007 07:44:43 +0100
Subject: [Tutor] comparing almost equal strings
In-Reply-To: <45CB128D.7040101@web.de>
References: <20070208123624.10a6e36e@localhost>
	<45CB128D.7040101@web.de>
Message-ID: <20070209074443.4950bf8a@localhost>

Hi,

On Thu, 08 Feb
2007 13:07:41 +0100
Christopher Arndt <chris.arndt at web.de> wrote:

> thomas coopman schrieb:
> > I need a function that groups almost equal strings.  It seems most
> > easy to me, to do this with a hash function.
> 
> What do you mean be "almost equal"? By which criterium? Spelling,
> Pronounciation? Semantics?
> 
> > I think I once read something about it, but I can't find it, 
> > does somebody know how to do this?
> 
> Maybe you mean the "soundex" algorithm? See, for example, here:
> 
> http://diveintopython.org/performance_tuning/index.html

This is what I was looking for!
> 
> Chris
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Thanks!

Thomas

From jfabiani at yolo.com  Fri Feb  9 17:15:39 2007
From: jfabiani at yolo.com (johnf)
Date: Fri, 9 Feb 2007 08:15:39 -0800
Subject: [Tutor] Python referrence
Message-ID: <200702090815.39687.jfabiani@yolo.com>

Hi,
In the Visual Fox Pro world there is a help file that allows look ups / 
searchs for functions, etc... just plain reference infomation.  I.e. if I 
were interested in the MAX() function I would just type Max() and get a page 
that contained a description of how to use MAX() and what it returned along 
with other similar type functions and maybe a few examples.

Is there a Python tool/document that is similar?  Just a simple way to help 
understand.
-- 
John Fabiani

From sudarshana.ks at gmail.com  Fri Feb  9 18:03:04 2007
From: sudarshana.ks at gmail.com (Sudarshana KS)
Date: Fri, 9 Feb 2007 22:33:04 +0530
Subject: [Tutor] Converting \x0e to string 0e in python
In-Reply-To: <45CC044F.9080905@tds.net>
References: <8036f2bb0702081639x7a149bc2yc7e5beabcb5c9c4f@mail.gmail.com>
	<45CC044F.9080905@tds.net>
Message-ID: <8036f2bb0702090903j26c576bdsbaa01a71777d16fb@mail.gmail.com>

Thanks for your reply.

The following is the error message :

>>> a
'\x00\x01\xa20\x82\x01\x9e0\x82\x01(\x02\x01\x000\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05\x000:1\x120\x10\x06\x03U\x04\x03\x13\tConst2-
2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r\x01\t\x02\x16\tConst2-2.0\x1e\x17\r070207210438Z\x17\r170204210438Z0:1\x120\x10\x06\x03U\x04\x03\x13\tConst2-2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r\x01\t\x02\x16\tConst2-2.0|0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03k\x000h\x02a\x00\xc2\x99e2\xd0\xa5\xb67\x80iv.\x12I\x17\xaa\xee9S\xdc\xee\xa1!\xb4\x94/\xf8\xe2\x0e%V\xdc\xa8%\x04\x03\x8dl\\\x8cJ\xec\x13\xd7\xe2\x96\x1b\xa8`\xdf$\xfe\xb9\x9a\xf9\xb7
[\x8f\xe6\xc7U?&l\x04D\xfc\xd7\x96\x99\x04\xb1\x8c\xcd\xc3[\x17\xba\xb2+g5L\x08~3B\xf9\x1dV\x1a\x84\x0eW\x94\x1f\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05\x00\x03a\x009f\x8c\xf8C\xcb0\xc8\x8e\xa2\xaeV\xc8 at .<\xae\xc7\xf6l\xeam2\x8f[
Z\xde\xd0\xbf\xd7\xd1/\xbd\x14\x89\xd1 at s
\x97\x02\x887\xcb\xf6#hNIG\xdb\x10\xe5A\x04\x19~8\x7f\xf3T\xaf\xdeY%\xc5if\xe4\x88\xce|v\xb2\xc35#\xc5\xa7\xec\xdca\x12\xd8*\xc3k\xf8\x911}!\x861\xe2;\xd7'
>>> crypto.load_certificate(crypto.FILETYPE_PEM,a)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OpenSSL.crypto.Error: [('PEM routines', 'PEM_read_bio', 'no start line')]
>>>

Could you please let me know what needs to be done.

Thanks in advance,
Sudks


On 2/9/07, Kent Johnson < kent37 at tds.net > wrote:
>
> Sudarshana KS wrote:
> > Hi,
> >
> > Currently i have data with the following type - Which is a x509
> > certificate obtained from SSL server done. I need this to be converted
> > to normal string, so that i can use the load_certificate method of
> > OpenSSL, which takes string as the argument.
>
> The below data is a string. It contains lots of non-ascii values which
> are printed as \x escapes, but it is still a string. Have you tried
> passing it to load_certificate? What happened?
>
> Kent
>
> >
> > Kindly help me.
> >
> >
> > cert=
> >
> '\x00\x01\xa20\x82\x01\x9e0\x82\x01(\x02\x01\x000\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05\x000:1
>
> > \x120\x10\x06\x03U\x04\x03\x13\tConst2-
> 2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r
> >
> > \x01\t\x02\x16\tConst2-
> 2.0\x1e\x17\r070207210438Z\x17\r170204210438Z0:1\x120\x10\x06\x03U\x04\x03
> > \x13\tConst2-
> 2.1$0\n\x06\x03U\x04\x05\x13\x0339B0\x16\x06\t*\x86H\x86\xf7\r\x01\t\x02\x16\tConst2-2.0|0\r
> >
> \x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03k\x000h\x02a\x00\xc2\x99e2\xd0\xa5\xb67\x80iv.\x12I\x17
>
> >
> >
> \xaa\xee9S\xdc\xee\xa1!\xb4\x94/\xf8\xe2\x0e%V\xdc\xa8%\x04\x03\x8dl\\\x8cJ\xec\x13\xd7\xe2\x96\x1b\xa8`
> >
> \xdf$\xfe\xb9\x9a\xf9\xb7[\x8f\xe6\xc7U?&l\x04D\xfc\xd7\x96\x99\x04\xb1\x8c\xcd\xc3[\x17\xba\xb2+g5L
>
> >
> \x08~3B\xf9\x1dV\x1a\x84\x0eW\x94\x1f\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05
> >
> >
> \x00\x03a\x009f\x8c\xf8C\xcb0\xc8\x8e\xa2\xaeV\xc8 at .<\xae\xc7\xf6l\xeam2\x8f[Z\xde\xd0\xbf\xd7\xd1/
>
> >
> \xbd\x14\x89\xd1 at s\x97\x02\x887\xcb\xf6#hNIG\xdb\x10\xe5A\x04\x19~8\x7f\xf3T\xaf\xdeY%\xc5if\xe4
> >
> \x88\xce|v\xb2\xc35#\xc5\xa7\xec\xdca\x12\xd8*\xc3k\xf8\x911}!\x861\xe2;\xd7'
> >
> >
> >
> > --
> > Regards,
> > Sudarshana K S
> >
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > Tutor maillist  -   Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
Regards,
Sudarshana K S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070209/4e6f9e50/attachment.htm 

From rikard.bosnjakovic at gmail.com  Fri Feb  9 19:20:24 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 9 Feb 2007 19:20:24 +0100
Subject: [Tutor] Python referrence
In-Reply-To: <200702090815.39687.jfabiani@yolo.com>
References: <200702090815.39687.jfabiani@yolo.com>
Message-ID: <d9e88eaf0702091020t4a8ecbb0j906f29d1f396823d@mail.gmail.com>

On 2/9/07, johnf <jfabiani at yolo.com> wrote:

> Is there a Python tool/document that is similar?  Just a simple way to help
> understand.

Yes, use the __doc__ property.

>>> print list.__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>> import os.path
>>> print os.path.__doc__
Common operations on Posix pathnames.



-- 
- Rikard.

From chris.arndt at web.de  Fri Feb  9 19:56:35 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 09 Feb 2007 19:56:35 +0100
Subject: [Tutor] Python referrence
In-Reply-To: <d9e88eaf0702091020t4a8ecbb0j906f29d1f396823d@mail.gmail.com>
References: <200702090815.39687.jfabiani@yolo.com>
	<d9e88eaf0702091020t4a8ecbb0j906f29d1f396823d@mail.gmail.com>
Message-ID: <45CCC3E3.3080804@web.de>

Rikard Bosnjakovic schrieb:
> On 2/9/07, johnf <jfabiani at yolo.com> wrote:
> 
>> Is there a Python tool/document that is similar?  Just a simple way to help
>> understand.
> 
> Yes, use the __doc__ property.

Which is made a lot easier by using the 'help' function in the interactive
interpreter:

>>> import os.path
>>> help(os.path)

---> os.path module description is shown

Chris

P.S. I also use the Python docs sidebar a lot:

http://projects.edgewall.com/python-sidebar/

From jfabiani at yolo.com  Fri Feb  9 20:09:34 2007
From: jfabiani at yolo.com (johnf)
Date: Fri, 9 Feb 2007 11:09:34 -0800
Subject: [Tutor] Python referrence
In-Reply-To: <45CCC3E3.3080804@web.de>
References: <200702090815.39687.jfabiani@yolo.com>
	<d9e88eaf0702091020t4a8ecbb0j906f29d1f396823d@mail.gmail.com>
	<45CCC3E3.3080804@web.de>
Message-ID: <200702091109.34243.jfabiani@yolo.com>

On Friday 09 February 2007 10:56, Christopher Arndt wrote:
> Rikard Bosnjakovic schrieb:
> > On 2/9/07, johnf <jfabiani at yolo.com> wrote:
> >> Is there a Python tool/document that is similar?  Just a simple way to
> >> help understand.
> >
> > Yes, use the __doc__ property.
>
> Which is made a lot easier by using the 'help' function in the interactive
>
> interpreter:
> >>> import os.path
> >>> help(os.path)
>
> ---> os.path module description is shown
>
> Chris
>
> P.S. I also use the Python docs sidebar a lot:
>
> http://projects.edgewall.com/python-sidebar/

that sidebar link is cool.  It is more of what I'm looking for.

-- 
John Fabiani

From nospamformeSVP at gmail.com  Fri Feb  9 20:18:58 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Fri, 09 Feb 2007 14:18:58 -0500
Subject: [Tutor] Generating pdf files in epydoc on Windows
Message-ID: <eqihfa$1d4$1@sea.gmane.org>

Does anyone know what is needed to install to get epydoc to generate pdf 
files on Windows.  Besides epydoc itself of course.

Thanks,

Don.


From kent37 at tds.net  Fri Feb  9 20:54:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Feb 2007 14:54:57 -0500
Subject: [Tutor] Python referrence
In-Reply-To: <200702090815.39687.jfabiani@yolo.com>
References: <200702090815.39687.jfabiani@yolo.com>
Message-ID: <45CCD191.4010700@tds.net>

johnf wrote:
> Hi,
> In the Visual Fox Pro world there is a help file that allows look ups / 
> searchs for functions, etc... just plain reference infomation.  I.e. if I 
> were interested in the MAX() function I would just type Max() and get a page 
> that contained a description of how to use MAX() and what it returned along 
> with other similar type functions and maybe a few examples.
> 
> Is there a Python tool/document that is similar?  Just a simple way to help 
> understand.

I just keep a couple of browser bookmarks to pages in the HTML docs. Any 
thing I want to know is just a few clicks away. It helps that I know 
where to find what I want in the docs, though.

Kent


From tim at johnsons-web.com  Fri Feb  9 12:42:10 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Fri, 9 Feb 2007 11:42:10 +0000
Subject: [Tutor] Python referrence
In-Reply-To: <200702090815.39687.jfabiani@yolo.com>
References: <200702090815.39687.jfabiani@yolo.com>
Message-ID: <200702091142.10528.tim@johnsons-web.com>

On Friday 09 February 2007 04:15 pm, johnf wrote:
  
> Is there a Python tool/document that is similar?  Just a simple way to help
> understand.

I make use of /usr/local/lib/python2.5/pydoc.py
(your path may be different, depending on OS and version)

On linux, I invoke it as a "server" as 
     pydoc -p 1234 &
(where 1234 is the non-conflicting port number of your choice)

And then point my browser to http://localhost:1234 (subsititute your port 
number)

This will pick up your own docstrings, libraries and classes as well as the
installed python system.
 
-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From bgailer at alum.rpi.edu  Fri Feb  9 22:49:47 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 09 Feb 2007 13:49:47 -0800
Subject: [Tutor] Python referrence
In-Reply-To: <200702090815.39687.jfabiani@yolo.com>
References: <200702090815.39687.jfabiani@yolo.com>
Message-ID: <45CCEC7B.8060409@alum.rpi.edu>

johnf wrote:
> Hi,
> In the Visual Fox Pro world there is a help file that allows look ups / 
> searchs for functions, etc... just plain reference infomation.  I.e. if I 
> were interested in the MAX() function I would just type Max() and get a page 
> that contained a description of how to use MAX() and what it returned along 
> with other similar type functions and maybe a few examples.
>
> Is there a Python tool/document that is similar?  Just a simple way to help 
> understand.
>   
On my windows box I open ..\Python25\Doc\Python25.chm and there are on 
the left side the "usual" Contents Index Search Favorites Tabs.

-- 
Bob Gailer
510-978-4454


From nephish at gmail.com  Fri Feb  9 22:50:08 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 9 Feb 2007 15:50:08 -0600
Subject: [Tutor] question about importing threads
In-Reply-To: <en90an$rnc$1@sea.gmane.org>
References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com>
	<45967EB5.3020902@tds.net>
	<384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com>
	<en6dri$hj8$1@sea.gmane.org>
	<384c93600612310646v63e958cdjdf4e72f15f35b8c0@mail.gmail.com>
	<en90an$rnc$1@sea.gmane.org>
Message-ID: <384c93600702091350t122471b5tcc7a48ef74e06338@mail.gmail.com>

ok, i have started doing this with my 4000 + line file. So far its been
working out.
i have another question about it.

i have two classes in my program that use a global object that is a socket
connection.

example:
global  my_sockobj
serverhost = 'mehost.com'
serverport = 9100
my_sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_sockobj.connect((serverhost,serverport))

then i use my_socket.recv to get stuff from the socket in one class
and my_socket.send to send stuff from another class.

is there something tricky about passing this as a global object to different
modules that would need to use it?
Or does this go along with what you wrote a while back about having classes
that depend on each other ?

One runs as a thread, the other responds to gui input.

thanks for any tips.

shawn

On 12/31/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "shawn bright" <nephish at gmail.com> wrote
>
> > Yes, the thing is getting to be a pain to deal with at this size, i
> > am
> > in-process of splitting out the classes into their own files.
>
> One thing to watch is that while its easy and tempting to create
> one file per class it's often better to keep dependant classes
> together.
> In other words if class A can only be used together with class B
> then it is often better to keep A and B in the same module.
> Anyone who needs B can import the module and anyone who
> needs A needs B too so it saves them having to import two
> modules.
>
> As in all things in programming a little bit of thought is often
> better than the first "obvious" strategy. Grady Booch described
> the above strategy by saying that "the unit of reuse is the category"
> (which in his OO notation was a set of related classes) and in
> Python that means the module.
>
> Regards,
>
> Alan G.
>
>
> _______________________________________________
> 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/20070209/5329af12/attachment.htm 

From gsf at panix.com  Sat Feb 10 00:24:24 2007
From: gsf at panix.com (Gabriel Farrell)
Date: Fri, 9 Feb 2007 18:24:24 -0500
Subject: [Tutor] A complete, functioning small web app: code for review
Message-ID: <20070209232424.GA13067@panix.com>

Greetings,

I've written the attached simple web app.  It serves as a more
pleasant user interface to a file located on our journal proxy
server.  It relies on the Paramiko library for sftp and Mako for
templating.  Basic file functions are as follows:
* ule: The user starts here.  A page is produced based on the
  template, which includes the deciphered output of any GET 
  messages received.
* ule_post: The view/controller for any posted actions.  Acts on POST
  and redirects the user to "ule".
* ule_model.py: The model -- all the real data handling goes on here.
* sftp_wrapper.py: A wrapper for the Paramiko library to simplify 
  sftp calls.
* ule_template.html: The Mako template for the main page of the app.
* redirect.html: Another Mako template for the redirect.

It functions without any major bugs that I'm aware of.  I took
advantage of the manageable scale of this project to really focus on
writing clean code.  I hope it will help others looking to do
anything similar.  I would appreciate any comments on its style
and organization.

Gabe

-------------- next part --------------
#!/usr/bin/python
'''
ule -- page display for the EZProxy User List Editor -- reads GET 
form to determine variables for display.  Processing is sent via
POST to ulepost.
'''

# uncomment cgitb for testing
#import cgitb; cgitb.enable()

import cgi
import sys
sys.path.insert(0, 'lib/python')
from mako.template import Template

from ule_model import UserList

# this form should be GET
form = cgi.FieldStorage()

ul = UserList()

def main():
    try:
        userpass_list = ul.getList()

        if form.getvalue('submit') == 'please wait':
            userpass_list = ul.check_against_innopac()
    finally:
        ul.closeSFTP()

    tmpl = Template(filename='ule_template.html')
    out_stream = tmpl.render(
        form = form,
        userpass_list = userpass_list,
    )

    print 'Content-Type: text/html\n'
    print out_stream

if __name__ == '__main__':
    main()
-------------- next part --------------
#!/usr/bin/python
'''
ule_post -- for handling POST from ule and redirecting back to ule with
proper GET.
'''

# uncomment cgitb for testing
#import cgitb; cgitb.enable()
import cgi
import re
from urllib import urlencode
import sys
sys.path.insert(0, 'lib/python')
from mako.template import Template

from ule_model import UserList, UleError

form = cgi.FieldStorage()
# initialize GET list -- will be appended to ule url
GET_params = []

ul = UserList()

def add():
    username = ''
    password = ''
    username_valid = None
    password_valid = None
    not_allowed = re.compile(r'[^%s]' % ul.allowed)

    if 'username' not in form:
        GET_params.append(('username_status', 'empty'))
    else:
        username = form['username'].value
        if not_allowed.search(username):
            GET_params.append(('username_status', 'illegal'))
        else:
            for userpass in ul.getList():
                if username == userpass[0]:
                    GET_params.append(('username_status', 'in_list'))
                    break
                else:
                    username_valid = True
    
    if 'password' not in form:
        GET_params.append(('password_status', 'empty'))
    else:
        password = form['password'].value
        if not_allowed.search(password):
            GET_params.append(('password_status', 'illegal'))
        else:
            password_valid = True
            
    if username_valid and password_valid:
        ul.add(username, password)
        GET_params.append(('username_status', 'added'))
        GET_params.append(('added', username))
    else:
        if username:
            GET_params.append(('username', username))
        if password:
            GET_params.append(('password', password))

def remove():
    if 'userlist' not in form:
        GET_params.append(('none_removed', True))
    else:
        user_list = form.getlist('userlist')
        removed_list = ul.remove(user_list)
        for username in removed_list:
            GET_params.append(('removed', username))

def undo():
    try:
        bak_days, bak_seconds = ul.undo()
        GET_params.append(('bak_days', bak_days))
        GET_params.append(('bak_seconds', bak_seconds))
    except UleError, e:
        if str(e) == 'no backups to revert to':
            GET_params.append(('no_backups', True))

def redirect():
    url_add = urlencode(GET_params)
    url = 'ule?' + url_add
    print '''Status: 303 See Other
Location: %s
Pragma: no-cache
Content-Type: text/html
''' % url
    redirect_template = Template(filename='redirect.html')
    print redirect_template.render(
        url = url,
    )

def main():
    try:
        if form.getvalue('submit') == 'add':
            add()
        if form.getvalue('submit') == 'remove':
            remove()
        if form.getvalue('submit') == 'undo':
            undo()
        redirect()
        # sync after everything else so render doesn't wait for it
        ul.sync()
    finally:
        ul.closeSFTP()

if __name__ == '__main__':
    main()

-------------- next part --------------
'''
ule_model -- for maintaining the integrity of ule's data.
'''

import re
from datetime import datetime
import os
from time import strptime
from sftp_wrapper import Session

MAIN_SERVER = 'ezproxy.library.xxxxxx.edu'
USERNAME = 'xxxxxx'
PASSWORD = 'xxxxxxx'
LDAP_USR_PATH = '/usr/local/ezproxy/ldap.usr'
DUMPURL = 'http://innopac.library.xxxxxx.edu:4500/PATRONAPI/%s/dump'
SECONDARY_SERVER = 'ezproxy2.library.xxxxxx.edu'

class UleError(Exception):
    pass

class UserList(object):
    def __init__(self):
        # characters allowed in usernames and passwords 
        self.allowed = r'\w-' 

        # userpass is the regex to parse ldap.usr for usernames and 
        # passwords
        self.userpass_re = re.compile(r'''
                ^           # start of line
                ([%s]*)     # username
                :           # colon
                ([%s]*)     # password
                $           # end of line
                ''' % (self.allowed, self.allowed), re.VERBOSE | re.MULTILINE)

        self.openSFTP()

    def openSFTP(self):
        self.ss = Session(MAIN_SERVER, USERNAME, PASSWORD)

    def closeSFTP(self):
        self.ss.close()

    def getList(self):
        ldap_usr_file = self.ss.open(LDAP_USR_PATH)
        self.ldap_usr_file_str = ldap_usr_file.read()
        ldap_usr_file.close()
        return self.userpass_re.findall(self.ldap_usr_file_str)
    
    def _getAdministrativa(self):
        admin_section = self.userpass_re.split(self.ldap_usr_file_str, 
            maxsplit = 1)[0]
        return admin_section
    
    def _backup(self):
        now = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
        backup_file_name = LDAP_USR_PATH + '.' + now + '.bak'
        backup_file = self.ss.open(backup_file_name, 'w')
        backup_file.write(self.ldap_usr_file_str)
        backup_file.close()

    def _write(self, userpasses):
        self._backup()
        ldap_usr_file = self.ss.open(LDAP_USR_PATH, 'w')
        ldap_usr_file.write(self._getAdministrativa())
        userpass_lines = [username + ':' + password for (username, password) 
                in userpasses]
        ldap_usr_file.write('\n'.join(userpass_lines))
        ldap_usr_file.close()

    def add(self, username, password):
        userpasses = self.getList()
        userpasses.append((username, password))
        # Decorate-Sort-Undecorate
        dsu_list = [(x[0].lower(), x[0], x[1]) for x in userpasses]
        dsu_list.sort()
        userpasses = [(x[1], x[2]) for x in dsu_list]
        self._write(userpasses)

    def remove(self, user_list):
        userpasses = self.getList()
        removed_list = []
        for removal in user_list:
            removal_tuple = tuple(removal.split(':'))
            username = removal_tuple[0]
            if removal_tuple in userpasses:
                userpasses.remove(removal_tuple)
                removed_list.append(username)
        self._write(userpasses)
        return removed_list

    def getBackups(self):
        ldap_dir = os.path.dirname(LDAP_USR_PATH)
        file_list = self.ss.listdir(ldap_dir)
        backup_list = [x for x in file_list if x.startswith('ldap.usr.') 
            and x.endswith('.bak')]
        backup_list.sort()
        return (backup_list, ldap_dir)
        
    def undo(self):
        backup_list, ldap_dir = self.getBackups()
        try:
            most_recent = os.path.join(ldap_dir, backup_list.pop())
        except IndexError:
            raise UleError('no backups to revert to')
        bak_file = self.ss.open(most_recent)
        bak_file_str = bak_file.read()
        bak_file.close()
        ldap_usr_file = self.ss.open(LDAP_USR_PATH, 'w')
        ldap_usr_file.write(bak_file_str)
        self.ss.remove(most_recent)
        bak_time = most_recent.split('.')[2]
        now = datetime.now()
        bak_time_obj = datetime(*strptime(bak_time, "%Y-%m-%dT%H:%M:%S")[0:6])
        bak_time_delta = now - bak_time_obj
        return (bak_time_delta.days, bak_time_delta.seconds)

    def check_against_innopac(self):
        def innocheck(username):
            'check username against innopac dump'
            import urllib2
            dumpurl = DUMPURL % username
            dump = urllib2.urlopen(dumpurl)
            for line in dump:
                if 'REC INFO' in line:
                    return True

        new_userlist = []
        for userpass in self.getList():
            if not innocheck(userpass[0]):
                # the flag is len(userpass) == 3
                userpass = userpass + (1,)
            new_userlist.append(userpass)
        return new_userlist

    def _cleanup(self, max=10):
        'delete backups in excess of max'
        backup_list, ldap_dir = self.getBackups()
        backup_list.reverse()
        def cleanup_rec():
            if len(backup_list) > max:
                oldest = os.path.join(ldap_dir, backup_list.pop())
                self.ss.remove(oldest)
                cleanup_rec()
        cleanup_rec()
        
    def sync(self):
        'sync MAIN_SERVER and SECONDARY_SERVER'
        self._cleanup()
        ss2 = Session(SECONDARY_SERVER, USERNAME, PASSWORD)
        def remoteCopy(path):
            file1 = self.ss.open(path)
            file1_str = file1.read()
            file1.close()
            file2 = ss2.open(path, 'w')
            file2.write(file1_str)
            file2.close()
        # copy ldap.usr from main to secondary
        remoteCopy(LDAP_USR_PATH)

        # remove old backups and copy new
        backup_list, ldap_dir = self.getBackups()
        file_list2 = ss2.listdir(ldap_dir)
        backup_list2 = [x for x in file_list2 if x.startswith('ldap.usr.') 
            and x.endswith('.bak')]
        for backup in backup_list2:
            backup_path = os.path.join(ldap_dir, backup)
            ss2.remove(backup_path)
        for backup in backup_list:
            backup_path = os.path.join(ldap_dir, backup)
            remoteCopy(backup_path)

        ss2.close()

-------------- next part --------------
'''
sftp_wrapper is a wrapper class for the sftp portion of the 
paramiko library, located in lib/python/
'''

import sys
sys.path.insert(0, 'lib/python')

import paramiko

class Session(object):
    def __init__(self, hostname, username, password):
        self.make_sftp(hostname, username, password)
        # uncomment to save log -- for testing
        # hmm, doesn't seem to be working -- gsf 20061220
        #paramiko.util.log_to_file('sftp.log')
    
    def make_sftp(self, hostname, username, password):
        self.tunnel = paramiko.Transport((hostname, 22))
        hostkeys = paramiko.util.load_host_keys('known_hosts')
        hostkey = hostkeys[hostname]['ssh-rsa']
        self.tunnel.connect(username=username, password=password, 
            hostkey=hostkey)
        self.sftp = paramiko.SFTPClient.from_transport(self.tunnel)

    def open(self, filename, mode='r'):
        return self.sftp.open(filename, mode=mode)

    def chdir(self, dir):
        self.sftp.chdir(dir)

    def get(self, remote, local=None):
        if not local:
            local = remote
        self.sftp.get(remote, local)

    def put(self, local, remote=None):
        if not remote:
            remote = local
        self.sftp.put(local, remote)

    def listdir(self, remote):
        return self.sftp.listdir(remote)

    def remove(self, remote):
        self.sftp.remove(remote)

    def close(self):
        self.tunnel.close()

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

From alan.gauld at btinternet.com  Sat Feb 10 01:47:16 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sat, 10 Feb 2007 00:47:16 +0000 (GMT)
Subject: [Tutor] question about importing threads
Message-ID: <896668.54115.qm@web86104.mail.ird.yahoo.com>

> i have two classes in my program that use a global object 
> that is a socket connection.
> ... code snipped
> is there something tricky about passing this as a global object to 
> different modules that would need to use it?


Whiler its possible to use a global in this way its usually better to 
avoid global objects in a reusable component since otherwise it 
might clash with another global that the reuser already has. Its much 
better to use a parameter which can be provided by the user of the 
classes. In this case the socklet becomesc a parameter.

A good place to put this parameter would be the init method of both 
your classes, where they would store a reference to it as an internal 
attribute. (remember that in Python all attributes are references so if 
you pass the same socket to both constructors both classes will point 
at the same socket).

This approach also allows the user of your classes to suvbstitute 
any socketlike object that they mauy have, even their own bespoke 
version if needed. That greatly increases the flexibility of your code.

> Or does this go along with what you wrote a while back about 
> having classes that depend on each other ?

If you really must use a shared global then I would strongly consider 
putting both classes, the global variable and an initialisation function 
all in a single module. If however tyou can parameterise things as 
described then you need to consider whether anyone would be 
able to (and want to) use either of the classes without the other. 
If you always need them as a pair they still should go in one module, 
otherwise put them in separate modules.

> One runs as a thread, the other responds to gui input.

Does it respond to GUI input or just input? If it can be independant 
of the GUI (and you should really try hard to make it so) then its 
independant and best in its own module. The fact that the other runs 
in a thred is fairly irrelevant to this discussion, the real issue is 
whether it has hard coded dependencies on the other class. For 
example does it instantiate a copy within its methods? (in which 
case you must import the other module/class into this module) And 
more especially does it take an instance as a parameter of a method?
(in which case the *re-user* must import the other module.) In the second 
case I'd say definitely put them in a single module, in the first case 
consider it, but it's not essential.

I hope that makes sense,

Alan G.


On 12/31/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
"shawn bright" <nephish at gmail.com> wrote

> Yes, the thing is getting to be a pain to deal with at this size, i
> am
> in-process of splitting out the classes into their own files.


One thing to watch is that while its easy and tempting to create
one file per class it's often better to keep dependant classes
together.
In other words if class A can only be used together with class B

then it is often better to keep A and B in the same module.
Anyone who needs B can import the module and anyone who
needs A needs B too so it saves them having to import two
modules.

As in all things in programming a little bit of thought is often

better than the first "obvious" strategy. Grady Booch described
the above strategy by saying that "the unit of reuse is the category"
(which in his OO notation was a set of related classes) and in

Python that means the module.

Regards,

Alan G.


_______________________________________________
Tutor maillist  -  Tutor at python.org

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









	
	
		
___________________________________________________________ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070210/ea7a260b/attachment.htm 

From ebbaalm at uiuc.edu  Sat Feb 10 06:34:56 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Fri, 9 Feb 2007 23:34:56 -0600
Subject: [Tutor] Identity operator (basic types)
Message-ID: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>

Why does the identity operator return "True" in the below cases, that is
when assigning  the same value to basic variable types (float, integer,
string, bool..)? Are these rcopied by reference (shallow)? If so why?

>>> i = 10
>>> j = 10
>>> i is j
True


>>> a = 10
>>> b = a
>>> a is b
True

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070209/9199bc55/attachment.htm 

From clucas916 at gmail.com  Sat Feb 10 06:45:11 2007
From: clucas916 at gmail.com (Christopher Lucas)
Date: Fri, 9 Feb 2007 22:45:11 -0700
Subject: [Tutor] Identity operator (basic types)
In-Reply-To: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>
References: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>
Message-ID: <C7F3D61D-3A0A-4B9F-8830-0AE7041ADFE3@cjlucas.net>


On Feb 9, 2007, at 10:34 PM, Cecilia Alm wrote:

> Why does the identity operator return "True" in the below cases,  
> that is when assigning  the same value to basic variable types  
> (float, integer, string, bool..)? Are these rcopied by reference  
> (shallow)? If so why?
>
> >>> i = 10
> >>> j = 10
> >>> i is j
> True

Here you're saying that "i" is equal to 10 and that "j" is equal to  
10. Therefore "I' and "j" are the same

> >>> a = 10
> >>> b = a
> >>> a is b
> True
>

What you're saying here is that "a" is equal to 10. Then you say that  
the variable "b" is equal to the variable "a". Therefore you're  
saying that b equals 10 and that "a" and "b" are equal.

- Chris



From john at fouhy.net  Sat Feb 10 06:46:48 2007
From: john at fouhy.net (John Fouhy)
Date: Sat, 10 Feb 2007 18:46:48 +1300
Subject: [Tutor] Identity operator (basic types)
In-Reply-To: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>
References: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>
Message-ID: <5e58f2e40702092146u194d6b5do2d3a16a909c3c54b@mail.gmail.com>

On 10/02/07, Cecilia Alm <ebbaalm at uiuc.edu> wrote:
> Why does the identity operator return "True" in the below cases, that is
> when assigning  the same value to basic variable types (float, integer,
> string, bool..)? Are these rcopied by reference (shallow)? If so why?
>
>  >>> i = 10
>  >>> j = 10
>  >>> i is j
>  True

Effectively, yes.

Integers in python are immutable.  I'm not sure exactly what happens
under the hood, but you can think of it like there is only one 10 in
the interpreter's memory, and every name you give it is just a pointer
to that one 10.  Remember, python is fully OO -- _everything_ is a
reference :-)

(this is also why there is no ++ operator)

-- 
John.

From dyoo at cs.wpi.edu  Sat Feb 10 06:57:26 2007
From: dyoo at cs.wpi.edu (Daniel Yoo)
Date: Sat, 10 Feb 2007 00:57:26 -0500 (EST)
Subject: [Tutor] Identity operator (basic types)
In-Reply-To: <C7F3D61D-3A0A-4B9F-8830-0AE7041ADFE3@cjlucas.net>
References: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>
	<C7F3D61D-3A0A-4B9F-8830-0AE7041ADFE3@cjlucas.net>
Message-ID: <Pine.LNX.4.63.0702100047540.14948@cs.wpi.edu>



>> Why does the identity operator return "True" in the below cases,
>> that is when assigning  the same value to basic variable types
>> (float, integer, string, bool..)? Are these rcopied by reference
>> (shallow)? If so why?
>>
>>>>> i = 10
>>>>> j = 10
>>>>> i is j
>> True

The above you have here is not guaranteed behavior --- in fact, in the 
general case, you won't see this.  The thing is that numbers that are 
"small" (< 100) are cached in Python as a low-level optimization, so every 
time you say '10', you get the same value.


> Here you're saying that "i" is equal to 10 and that "j" is equal to 10. 
> Therefore "I' and "j" are the same

That may be "equal", but there is no guarantee that they will be 
identical.  Concretely:

################
>>> x = 1234567
>>> y = 1234567
>>> x is y
False
################



>>>>> a = 10
>>>>> b = a
>>>>> a is b
>> True

This, on the other hand, guarantees that 'is' will return true: the two 
names 'a' and 'b' refer to the same object.



I think we should be careful about using the word "equal" and "same", so 
let me make sure we agree on terms.

     a == b   "a's value equals b's value."

     a is b   "a and b refer to the same value."

From thomas.coopman at gmail.com  Sat Feb 10 12:39:30 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Sat, 10 Feb 2007 12:39:30 +0100
Subject: [Tutor] class methods as argument
Message-ID: <20070210123930.66a52189@localhost>

Hi,

I want to do something like this, don't know how to properly explain it,
so I just give you some example code

>>>class Foo(object):
>>>	def method(self, arg):
>>>		print arg

>>>def doSomething(object, func):
>>>	object.func("test")

>>>object = Foo()
>>>doSomething(object, Foo.method)

I want to execute the class method given as argument,
but this obvious doesn't work, but I don't know how to
get it work,
Is it possible?
and how?

Thanks


From thomas.coopman at gmail.com  Sat Feb 10 15:44:44 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Sat, 10 Feb 2007 15:44:44 +0100
Subject: [Tutor] class methods as argument
In-Reply-To: <1171109453.17277.6.camel@Copernicus>
References: <20070210123930.66a52189@localhost>
	<1171109453.17277.6.camel@Copernicus>
Message-ID: <20070210154444.4cb6c602@localhost>

On Sat, 10 Feb 2007 22:10:52 +1000
Jonathan McManus <jonathan at acss.net.au> wrote:

> It's pretty easy to make this work, actually. The issue is in the
> "doSomething" method.
> 
> > >>>class Foo(object):
> > >>>	def method(self, arg):
> > >>>		print arg
> > 
> > >>>def doSomething(object, func):
> > >>>	object.func("test")
> 
> Here, it's looking for a method of the "Foo" object (object) called
> "func" (AttributeError: 'Foo' object has no attribute 'func'), instead
> of replacing "func" with "Foo.method". 
> 
> What you need to do is:
> 
> >>> def doSomething (object, func):
> >>>	func(object, "test")
> 
> This means that you are calling the method (explicity passed as being
> a method of Foo), as well as supplying the actual object as the first
> argument (the required self for classes).
> 
> >>> object = Foo()
> >>> doSomething(object, Foo.method)
> test
> 
> Hope that helps.
> 


Thanks,
that I've didn't come up with that myself!
It's indeed easy!

From kent37 at tds.net  Sat Feb 10 13:55:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Feb 2007 07:55:54 -0500
Subject: [Tutor] class methods as argument
In-Reply-To: <20070210123930.66a52189@localhost>
References: <20070210123930.66a52189@localhost>
Message-ID: <45CDC0DA.5090204@tds.net>

thomas coopman wrote:
> Hi,
> 
> I want to do something like this, don't know how to properly explain it,
> so I just give you some example code
> 
>>>> class Foo(object):
>>>> 	def method(self, arg):
>>>> 		print arg
> 
>>>> def doSomething(object, func):
>>>> 	object.func("test")
> 
>>>> object = Foo()
>>>> doSomething(object, Foo.method)
> 
> I want to execute the class method given as argument,
> but this obvious doesn't work, but I don't know how to
> get it work,

First a quick note - don't use object as a parameter or variable name, 
it will hide the definition of the built-in object class.

You are very close. Foo.method is called an 'unbound method' of class 
Foo. The syntax for calling an unbound method is to pass a class 
instance as the first argument, followed by the actual argument list. It 
is actually the same argument list that you use when you declare the 
function (starting with self).

So your example can be written this way:

In [4]: class Foo(object):
    ...:     def method(self, arg):
    ...:         print arg

In [6]: o=Foo()

In [8]: def doSomething(obj, func):
    ...:     func(obj, "test")

In [9]: doSomething(o, Foo.method)
test


A more common way to do this is to use a 'bound method'. That is what 
you get when you refer to instance.method instead of Class.method. A 
bound method includes a reference to the particular instance and can be 
called like an ordinary function. Rather than passing the instance and 
the unbound method to doSomething(), just pass the bound method as a 
single argument:

In [10]: def doSomething(func):
    ....:     func("test")

In [12]: doSomething(o.method)
test

In summary:
Class.method => unbound method, call with instance as first arg
instance.method => bound method, call with normal argument list

Kent


From project5 at redrival.net  Sat Feb 10 13:56:49 2007
From: project5 at redrival.net (Andrei)
Date: Sat, 10 Feb 2007 13:56:49 +0100
Subject: [Tutor] class methods as argument
In-Reply-To: <20070210123930.66a52189@localhost>
References: <20070210123930.66a52189@localhost>
Message-ID: <eqkfe3$tpp$1@sea.gmane.org>

Hi Thomas,


thomas coopman wrote:
<snip>
> I want to execute the class method given as argument,
> but this obvious doesn't work, but I don't know how to
> get it work,

Pass the method reference of the class as argument, like this:

 >>> class A(object):
...     def __init__(self, x): self.x = x
...     def dostuff(self, arg):
...         print self.x
...         print arg
...
 >>> def dostuff(obj, method):
...     method(obj, 'blabla')
...
 >>> a = A(5)
 >>> dostuff(a, A.dostuff)
5 # this demonstates method has been called for instance a
blabla




Yours,

Andrei


From kent37 at tds.net  Sat Feb 10 14:00:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Feb 2007 08:00:35 -0500
Subject: [Tutor] Identity operator (basic types)
In-Reply-To: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>
References: <7a4620dc0702092134n7d456769yd171d559a45406ac@mail.gmail.com>
Message-ID: <45CDC1F3.6030502@tds.net>

Cecilia Alm wrote:
> Why does the identity operator return "True" in the below cases, that is 
> when assigning  the same value to basic variable types (float, integer, 
> string, bool..)? Are these rcopied by reference (shallow)? If so why?

Assignment in Python is always by reference. Variables in Python are not 
containers for values, they are names for values. See
http://effbot.org/zone/python-objects.htm

In general it is a bad idea to use 'is'; for several reasons it can 
yield surprising results. == is usually a better choice. One exception 
is when comparing to a known singleton object, for example
   if a is None:
is a good way to test for None.

Kent

> 
>  >>> i = 10
>  >>> j = 10
>  >>> i is j
> True
> 
> 
>  >>> a = 10
>  >>> b = a
>  >>> a is b
> True
> 
> Thanks!
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From thomas.coopman at gmail.com  Sat Feb 10 16:32:33 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Sat, 10 Feb 2007 16:32:33 +0100
Subject: [Tutor] class methods as argument
In-Reply-To: <45CDC0DA.5090204@tds.net>
References: <20070210123930.66a52189@localhost>
	<45CDC0DA.5090204@tds.net>
Message-ID: <20070210163233.219fd315@localhost>

On Sat, 10 Feb 2007 07:55:54 -0500
Kent Johnson <kent37 at tds.net> wrote:

> thomas coopman wrote:
> > Hi,
> > 
> > I want to do something like this, don't know how to properly
> > explain it, so I just give you some example code
> > 
> >>>> class Foo(object):
> >>>> 	def method(self, arg):
> >>>> 		print arg
> > 
> >>>> def doSomething(object, func):
> >>>> 	object.func("test")
> > 
> >>>> object = Foo()
> >>>> doSomething(object, Foo.method)
> > 
> > I want to execute the class method given as argument,
> > but this obvious doesn't work, but I don't know how to
> > get it work,
> 
> First a quick note - don't use object as a parameter or variable
> name, it will hide the definition of the built-in object class.
Yes, I know, it was a bad example
> 
> You are very close. Foo.method is called an 'unbound method' of class 
> Foo. The syntax for calling an unbound method is to pass a class 
> instance as the first argument, followed by the actual argument list.
> It is actually the same argument list that you use when you declare
> the function (starting with self).
> 
> So your example can be written this way:
> 
> In [4]: class Foo(object):
>     ...:     def method(self, arg):
>     ...:         print arg
> 
> In [6]: o=Foo()
> 
> In [8]: def doSomething(obj, func):
>     ...:     func(obj, "test")
> 
> In [9]: doSomething(o, Foo.method)
> test
> 
> 
> A more common way to do this is to use a 'bound method'. That is what 
> you get when you refer to instance.method instead of Class.method. A 
> bound method includes a reference to the particular instance and can
> be called like an ordinary function. Rather than passing the instance
> and the unbound method to doSomething(), just pass the bound method
> as a single argument:
> 

> In [10]: def doSomething(func):
>     ....:     func("test")
> 
> In [12]: doSomething(o.method)
> test
> 
> In summary:
> Class.method => unbound method, call with instance as first arg
> instance.method => bound method, call with normal argument list
> 
> Kent
> 

Thank you for the explanation of bound and unbound methods.
I understand that it is more common to use a bound method, but I don't
think that I can use this because at the time I save the method, I don't
know anything about the instances.

I use this for making a sorted list using any method you give as
argument when you create the list.  This class only gets to know it's
instances when you add them.

In [3]: class SortedList(object):
   ...:     def __init__(self, compare):
   ...:         self.compare = compare
   ...:     def __add_(self, object):
   ...:         for i in self.data:
   ...:             self.compare(object, i)
   ...:

In [4]: class FooList(SortedList):
   ...:     def __init__(self):
   ...:         self.compare = Foo.compare


__add__ doesn't do anything here of course, it is just an example,
but I don't think that I can use a bound method in this case?

also,
Is it better to use super in FooList? and how should I use it then?

Thomas

From kent37 at tds.net  Sat Feb 10 15:04:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Feb 2007 09:04:15 -0500
Subject: [Tutor] class methods as argument
In-Reply-To: <20070210163233.219fd315@localhost>
References: <20070210123930.66a52189@localhost>	<45CDC0DA.5090204@tds.net>
	<20070210163233.219fd315@localhost>
Message-ID: <45CDD0DF.6070208@tds.net>

thomas coopman wrote:

> Thank you for the explanation of bound and unbound methods.
> I understand that it is more common to use a bound method, but I don't
> think that I can use this because at the time I save the method, I don't
> know anything about the instances.

That would be an appropriate time to use unbound methods. From your 
original example it wasn't clear.
> 
> I use this for making a sorted list using any method you give as
> argument when you create the list.  This class only gets to know it's
> instances when you add them.
> 
> In [3]: class SortedList(object):
>    ...:     def __init__(self, compare):
>    ...:         self.compare = compare
>    ...:     def __add_(self, object):
>    ...:         for i in self.data:
>    ...:             self.compare(object, i)
>    ...:

That looks OK so far.
> 
> In [4]: class FooList(SortedList):
>    ...:     def __init__(self):
>    ...:         self.compare = Foo.compare
> 
> 
> __add__ doesn't do anything here of course, it is just an example,
> but I don't think that I can use a bound method in this case?

No. You can use an unbound method or an ordinary function with two 
arguments.
> 
> also,
> Is it better to use super in FooList? and how should I use it then?

Actually I would say that FooList is not pulling its weight. SortedList 
already allows specialization by the compare function, so to create the 
equivalent of a FooList you just call SortedList(Foo.compare).

If you do want to keep FooList then you should call 
SortedList.__init__() to set the compare function. SortedList.__init__ 
is an unbound function so you call it like this:
   SortedList.__init__(self, Foo.compare)

Another design you might want to consider - if you will always be 
sorting each type of list by the same compare method - is to define a 
__cmp__() method in each class that will be part of a SortedList and use 
plain comparison operators (< > etc) to do the compare.

Finally note that Python's sort() function is very fast and flexible and 
it might be better just to sort the list when you need it to be sorted, 
rather than keeping it sorted. Or maybe what you really need is a heap 
(see the heapq module). If you really want to keep a sorted list, you 
should look at the bisect module, it might help.

Kent


From thomas.coopman at gmail.com  Sat Feb 10 19:24:05 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Sat, 10 Feb 2007 19:24:05 +0100
Subject: [Tutor] class methods as argument
In-Reply-To: <45CDD0DF.6070208@tds.net>
References: <20070210123930.66a52189@localhost> <45CDC0DA.5090204@tds.net>
	<20070210163233.219fd315@localhost> <45CDD0DF.6070208@tds.net>
Message-ID: <20070210192405.7381df80@localhost>

On Sat, 10 Feb 2007 09:04:15 -0500
Kent Johnson <kent37 at tds.net> wrote:

> thomas coopman wrote:
> > 
> > also,
> > Is it better to use super in FooList? and how should I use it then?
> 
> Actually I would say that FooList is not pulling its weight.
> SortedList already allows specialization by the compare function, so
> to create the equivalent of a FooList you just call
> SortedList(Foo.compare).
I know that in this example it's rather useless to create FooList, but
the subclasses I have of SortedList have other specializations so I
will keep using them.

> 
> If you do want to keep FooList then you should call 
> SortedList.__init__() to set the compare function.
> SortedList.__init__ is an unbound function so you call it like this:
>    SortedList.__init__(self, Foo.compare)
This works.
I think I'll need to reed some more about super because I thought I had
to use super in this case.

> 
> Another design you might want to consider - if you will always be 
> sorting each type of list by the same compare method - is to define a 
> __cmp__() method in each class that will be part of a SortedList and
> use plain comparison operators (< > etc) to do the compare.
That's the problem.  I define for most of my classes a __cmp__() method
but, some classes have another way of being sorted, and that's why I
give the compare method as an argument in SortedList

> 
> Finally note that Python's sort() function is very fast and flexible
> and it might be better just to sort the list when you need it to be
> sorted, rather than keeping it sorted. Or maybe what you really need
> is a heap (see the heapq module). If you really want to keep a sorted
> list, you should look at the bisect module, it might help.
I now use sort() when there is some data initially.  After creation, I
insert data with my own bisect method, I also use it to search the data.

I mostly need the sorted list, because I want to detect when a object
is added with the same value of some item in the list and take
appropriate actions.

> 
> Kent
> 

Thomas

From kent37 at tds.net  Sat Feb 10 17:50:20 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Feb 2007 11:50:20 -0500
Subject: [Tutor] class methods as argument
In-Reply-To: <20070210192405.7381df80@localhost>
References: <20070210123930.66a52189@localhost>	<45CDC0DA.5090204@tds.net>	<20070210163233.219fd315@localhost>	<45CDD0DF.6070208@tds.net>
	<20070210192405.7381df80@localhost>
Message-ID: <45CDF7CC.5080802@tds.net>

thomas coopman wrote:
> On Sat, 10 Feb 2007 09:04:15 -0500
> Kent Johnson <kent37 at tds.net> wrote:

>> If you do want to keep FooList then you should call 
>> SortedList.__init__() to set the compare function.
>> SortedList.__init__ is an unbound function so you call it like this:
>>    SortedList.__init__(self, Foo.compare)
> This works.
> I think I'll need to reed some more about super because I thought I had
> to use super in this case.

You can use super() also but for simple cases I think it is fine to just 
call the superclass method directly. super() is intended to help with 
some of the difficulties of multiple inheritance but it has some 
difficulties of its own.

> I mostly need the sorted list, because I want to detect when a object
> is added with the same value of some item in the list and take
> appropriate actions.

If you don't really care about the order, then a dict mapping the value 
of interest to a list of items with that value might be easier to work with.

Kent


From demonic.software at gmail.com  Sat Feb 10 18:45:10 2007
From: demonic.software at gmail.com (demonic.software at gmail.com)
Date: Sat, 10 Feb 2007 11:45:10 -0600
Subject: [Tutor] MSI Installers for python
Message-ID: <45CE04A6.7000806@gmail.com>

Hello,

I was wondering if anyone can offer any examples, pointers, tutorials, 
or howtos  on developing an MSI installer file for windows using Python. 
  I found the msilib reference in the Python 2.5 documents, but I am not 
familiar with this area and I am trying find any examples (code wise) 
that implement the msilib.  I did check Google, but there did not seem 
to be any good leads.  Thanks in advance,

ds

From les.hazlett at navteq.com  Sat Feb 10 19:58:19 2007
From: les.hazlett at navteq.com (Hazlett, Les)
Date: Sat, 10 Feb 2007 12:58:19 -0600
Subject: [Tutor] Creating an Identifier or Object Name from a String?
Message-ID: <B76F47F45A9B184781E0A41F711B516CADF8E9@NAEXC.ad.navteq.com>

Hi,

I read the information at http://mail.python.org/mailman/listinfo/tutor
but am still not sure how to properly send a question.  Will I get an
email response without joining the list?  

Thanks for any help.

Les

 

I thought when I read the 2002 thread with the subject (Creating an
Identifier or Object Name from a String?), that I had found a solution
to my problem.  But, I can't make the concept work for creating an
object identifier.  

THIS WORKS

	class nsf(object):
	    # name = ''
	    def __init__(self, id):
	        self.name = id 
	 
	# main
	Ireland = nsf('Ireland')

BUT - THIS DOESN'T

	class nsf(object):
	    # name = ''
	    def __init__(self, id):
	        self.name = id 
	 
	# main
	cmdstr = "Ireland = nsf('Ireland')"
	eval(cmdstr)

-------------------------

I get an error saying the following

      eval(cmdstr)
  File "(string)", line 1
      Ireland = nsf('Ireland')
              ^
SyntaxError: invalid syntax

-------------------------

For reference the thread message that I am referring to is:

Gregor Lingl wrote:

	I Tried it and it worked (?!)
	
	Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)]
on win32
	Type "copyright", "credits" or "license" for more information.
	IDLE 0.8 -- press F1 for help
	>>> class K:
	        pass
	
	>>> field1 = K()
	>>> field2 = K()
	>>> field3 = K()
	>>> for ct in range(1,4):
	        obj="field"+str(ct)
	        objTC=eval(obj)
	        objTC.text=['a','b',str(ct)]
	
	
	>>> field1.text
	['a', 'b', '1']
	>>> field2.text
	['a', 'b', '2']
	>>> field3.text
	['a', 'b', '3']
	>>>
	
	Gregor
	
	

What he did also works for me. Bur, I have tried many ways to use the
same idea for creating an object identifier.  I haven't found a way yet.

 

 

 


The information contained in this communication may be CONFIDENTIAL and is intended only for the use of the recipient(s) named above. If you are not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication, or any of its contents, is strictly prohibited. If you have received this communication in error, please notify the sender and delete/destroy the original message and any copy of it from your computer or paper files.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070210/9b685555/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/gif
Size: 145 bytes
Desc: Blank Bkgrd.gif
Url : http://mail.python.org/pipermail/tutor/attachments/20070210/9b685555/attachment.gif 

From rabidpoobear at gmail.com  Sat Feb 10 22:28:21 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 10 Feb 2007 15:28:21 -0600
Subject: [Tutor] Creating an Identifier or Object Name from a String?
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CADF8E9@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CADF8E9@NAEXC.ad.navteq.com>
Message-ID: <45CE38F5.60806@gmail.com>

Hazlett, Les wrote:
>
> Hi,
>
> I read the information at 
> http://mail.python.org/mailman/listinfo/tutor but am still not sure 
> how to properly send a question.  Will I get an email response without 
> joining the list?
>
You will get an e-mail response from me because I am using the reply-all 
feature which sends a copy to you and another to the list.  Other people 
who don't reply with this method will not have e-mails you can see. You 
should join the list.
>
> I thought when I read the 2002 thread with the subject (Creating an 
> Identifier or Object Name from a String?), that I had found a solution 
> to my problem.  But, I can't make the concept work for creating an 
> object identifier. 
>
> THIS WORKS   [snip]
>
> BUT - THIS DOESN'T
>
>     class nsf(object):
>         # name = ''
>         def __init__(self, id):
>             self.name = id
>      
>     # main
>     cmdstr = "Ireland = nsf('Ireland')"
>     eval(cmdstr)
>
 >>> exec('x = "hello"')
 >>> print x
hello

you're using the wrong function.
This is still a Very Bad Idea (tm) and you can almost always accomplish 
this in a safer way.
HTH,
-Luke

From dyoo at cs.wpi.edu  Sat Feb 10 23:04:51 2007
From: dyoo at cs.wpi.edu (Daniel Yoo)
Date: Sat, 10 Feb 2007 17:04:51 -0500 (EST)
Subject: [Tutor] Creating an Identifier or Object Name from a String?
In-Reply-To: <45CE38F5.60806@gmail.com>
References: <B76F47F45A9B184781E0A41F711B516CADF8E9@NAEXC.ad.navteq.com>
	<45CE38F5.60806@gmail.com>
Message-ID: <Pine.LNX.4.63.0702101642530.398@cs.wpi.edu>


>> I thought when I read the 2002 thread with the subject (Creating an 
>> Identifier or Object Name from a String?), that I had found a solution 
>> to my problem.

Wait.  But what was the solution you ended with?  If the conclusion of 
that thread was to use eval(), then that was the wrong lesson, and you 
needed to read more.  *grin*


Read the thread in its entirety:

    http://mail.python.org/pipermail/tutor/2002-June/014923.html

The resolution should have been: don't use eval to dynamically create 
variable names from string.  Rather, keep all the new instances in a 
dictionary that's keyed by those strings.  Avoid eval unless you really 
understand what you're doing.


Avoid the very real dangers in eval():

* It's inconvenient.  You can't create variables like with names that
   you'd like:

#################################################################
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
>>> names = ['carmen sandiego', 'eva_luator']
>>> for n in names:
...     exec("%s = Person('%s')" % (n, n))
...
Traceback (most recent call last):
   File "<stdin>", line 2, in ?
   File "<string>", line 1
     carmen sandiego = Person('carmen sandiego')
                   ^
SyntaxError: invalid syntax
#################################################################

because Python's variable names are not allowed to have spaces in them.


In contrast:

############################
>>> people = {}
>>> for n in names:
...     people[n] = Person(n)
...
>>> people.keys()
['carmen sandiego', 'eva_luator']
#############################

just works, and anyone with elementary knowledge of dictionaries will know 
exactly what this is doing.  The code ends up simpler because it 
eliminates the need to construct some string to eval or execute that 
quotes its arguments correctly.


* It's insecure.  See:
   http://mail.python.org/pipermail/tutor/2004-December/033844.html


From anilmrn at yahoo.com  Sun Feb 11 01:52:12 2007
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 10 Feb 2007 16:52:12 -0800 (PST)
Subject: [Tutor] Geolocating objects
Message-ID: <634218.22046.qm@web55204.mail.re4.yahoo.com>

Hello

i m trying to use python to find the proximity of a person using lat long gps and zipcodes. I m using python. please point me to resources for this
thanks a lot 

Anil

 
---------------------------------
Cheap Talk? 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/20070210/947e194a/attachment.htm 

From rfquerin at gmail.com  Sun Feb 11 03:18:29 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Sat, 10 Feb 2007 21:18:29 -0500
Subject: [Tutor] Converting Filenames to Lower case
Message-ID: <7d81675b0702101818p794fb2e9xc1d8ec51b00adabe@mail.gmail.com>

Hi, I'm interested in a writing a quick python script for use on the command
line. I'm at the linux terminal inside a directory with a bunch of files.
The files have mixed case (some are .JPG and some are .jpg, etc..) I'd like
to be able to run a python script that will take all the files in the
directory I'm in and convert all the filenames and extensions to lower case.

Any ideas on where to look? I've fiddled quite a bit with very basic
scripting but nothing to do with getting files from the current directory
and processing their names. Can anybody point me in the right direction to
get started?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070210/d8e20be3/attachment.html 

From kent37 at tds.net  Sun Feb 11 03:27:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Feb 2007 21:27:01 -0500
Subject: [Tutor] Converting Filenames to Lower case
In-Reply-To: <7d81675b0702101818p794fb2e9xc1d8ec51b00adabe@mail.gmail.com>
References: <7d81675b0702101818p794fb2e9xc1d8ec51b00adabe@mail.gmail.com>
Message-ID: <45CE7EF5.4050103@tds.net>

Richard Querin wrote:
> Hi, I'm interested in a writing a quick python script for use on the 
> command line. I'm at the linux terminal inside a directory with a bunch 
> of files. The files have mixed case (some are .JPG and some are .jpg, 
> etc..) I'd like to be able to run a python script that will take all the 
> files in the directory I'm in and convert all the filenames and 
> extensions to lower case.
> 
> Any ideas on where to look? I've fiddled quite a bit with very basic 
> scripting but nothing to do with getting files from the current 
> directory and processing their names. Can anybody point me in the right 
> direction to get started?

os.listdir() will list the current dir. os.rename() will rename a file. 
filename.lower() converts to lower case.

Kent


From rfquerin at gmail.com  Sun Feb 11 04:26:56 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Sat, 10 Feb 2007 22:26:56 -0500
Subject: [Tutor] Trouble getting os.execl() command to work
Message-ID: <7d81675b0702101926q68500593qc59cd50d2deb5d5@mail.gmail.com>

I'm having a slight problem here. I've got a script (shown below) which is
run from the command line. I am converting the filenames to lowercase and
then, for each .cr2 file, I'm building a command line and running it. Seems
pretty simple. I print the resulting command line and it looks fine, but
os.execl() won't seem to execute it. It tells me "no such file or
directory". Yet I can cut and paste the printed line onto the command line
and execute it and it works fine. Am I missing something? Here's the code:


import os
import string

# get a list of the files in the current working directory

filelist = os.listdir(os.getcwd())

# run through the list and convert all of them to lowercase

for name in filelist:
    lowered_name = string.lower(name)
    print name + " -> " + lowered_name
    os.rename (name,lowered_name)


# run through the list again and for all .cr2 files run
# the exiftool command to copy the exif data from cr2 to jpg file


for name in filelist:

    #extract extension
    ext = name[-3:]

    if ext == 'cr2':
        jpg_dest = name[:-4]+".jpg"
        cmd_string = "/home/richard/ExifTool/exiftool -TagsFromFile " + name
+ " -exif:all " + jpg_dest
        print cmd_string    #this string looks correct
        os.execl(cmd_string)   #the resulting command throws an error ??
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070210/ade3f544/attachment.html 

From rabidpoobear at gmail.com  Sun Feb 11 07:07:38 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 11 Feb 2007 00:07:38 -0600
Subject: [Tutor] Trouble getting os.execl() command to work
In-Reply-To: <7d81675b0702101926q68500593qc59cd50d2deb5d5@mail.gmail.com>
References: <7d81675b0702101926q68500593qc59cd50d2deb5d5@mail.gmail.com>
Message-ID: <45CEB2AA.2010404@gmail.com>

See my comments in-line with the rest of the e-mail.
Richard Querin wrote:
> import os
> import string
>
> # get a list of the files in the current working directory
>
> filelist = os.listdir(os.getcwd())
Ok we have a list of all the files
>
> # run through the list and convert all of them to lowercase
>
> for name in filelist:
we loop over the list
>     lowered_name = string.lower(name)
>     print name + " -> " + lowered_name
>     os.rename (name,lowered_name)
and rename any that are not lowercase.
>
>
> # run through the list again and for all .cr2 files run
> # the exiftool command to copy the exif data from cr2 to jpg file
>
>
> for name in filelist:
oops! filelist still contains the non-normalized names of the files!
>
>     #extract extension
>     ext = name[-3:]
>
>     if ext == 'cr2':
>         jpg_dest = name[:-4]+".jpg"
>         cmd_string = "/home/richard/ExifTool/exiftool -TagsFromFile " 
> + name + " -exif:all " + jpg_dest        
>         print cmd_string    #this string looks correct
>         os.execl(cmd_string)   #the resulting command throws an error ??
It can't find the files because of this.

HTH,
-Luke

From digitalxero at gmail.com  Sun Feb 11 09:19:30 2007
From: digitalxero at gmail.com (Dj Gilcrease)
Date: Sun, 11 Feb 2007 00:19:30 -0800
Subject: [Tutor] token parser
Message-ID: <e9764b730702110019v49149far6047f1dd8d149139@mail.gmail.com>

How would I go about writing a fast token parser to parse a string like
"[4d6.takeHighest(3)+(2d6*3)-5.5]"

and get a list like
['+',
    ['takeHighest',
        ['d',
            4,
            6
        ],
        3
    ],
    ['-',
        ['*',
            ['d',
                2,
                6
            ],
            3
        ],
        5.5
    ]
]

back? ( I put it all separated and indented like that so it is easier
to read, it is for me anyways )

From alan.gauld at btinternet.com  Sun Feb 11 09:46:19 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Feb 2007 08:46:19 -0000
Subject: [Tutor] Converting Filenames to Lower case
References: <7d81675b0702101818p794fb2e9xc1d8ec51b00adabe@mail.gmail.com>
Message-ID: <eqml4s$721$1@sea.gmane.org>


"Richard Querin" <rfquerin at gmail.com> wrote

> Any ideas on where to look? I've fiddled quite a bit with very basic
> scripting but nothing to do with getting files from the current 
> directory
> and processing their names. Can anybody point me in the right 
> direction to
> get started?

Kent gave you the immediate amswers.

You might also like to read through my tutorial topic on Working
with the OS. It covers several other things to do with handling files,
folders and processes etc.

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



From alan.gauld at btinternet.com  Sun Feb 11 09:57:26 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Feb 2007 08:57:26 -0000
Subject: [Tutor] Trouble getting os.execl() command to work
References: <7d81675b0702101926q68500593qc59cd50d2deb5d5@mail.gmail.com>
Message-ID: <eqmlpn$8ab$1@sea.gmane.org>


"Richard Querin" <rfquerin at gmail.com> wrote

> I'm having a slight problem here. I've got a script (shown below) 
> which is
> run from the command line. I am converting the filenames to 
> lowercase and
> then, for each .cr2 file, I'm building a command line and running 
> it.
...
> os.execl() won't seem to execute it.

execl() is probably the wrong tool for this particular job.
os.system would be easier.
But better still is to use the new subprocess module.
Look at the subprocess documentation for examples of running
simple commands.

> # run through the list again and for all .cr2 files run
> # the exiftool command to copy the exif data from cr2 to jpg file
>
> for name in filelist:
>
>    #extract extension
>    ext = name[-3:]
>
>    if ext == 'cr2':

You could do this more easily and more reliably using the
glob module.

for name in glob.glob('*.cr2'):

And it avoids the problem of using the old list of
mixed case names too.

>        jpg_dest = name[:-4]+".jpg"

You could also use the os.path.splitext() function here if you want
to avoid the slicing, but the benefit is less obvious in this case...

>        cmd_string = "/home/richard/ExifTool/exiftool -TagsFromFile " 
> + name
> + " -exif:all " + jpg_dest
>        print cmd_string    #this string looks correct
>        os.execl(cmd_string)   #the resulting command throws an error 
> ??

HTH,


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



From atpridgen at mail.utexas.edu  Sun Feb 11 07:10:44 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Sun, 11 Feb 2007 00:10:44 -0600
Subject: [Tutor] Unpickling data after passing over the network
Message-ID: <45CEB364.5050904@mail.utexas.edu>

Hello,

I am having problems with unpickling data after I pass the data through 
a socket.   Right now, I am pickling a basic string base 64 encoding and 
sending the data over the network.  After the recipient client/server 
receives the data, it is decoded and then unpickled.  The unpickling 
fails with an EOFError, and I am not sure why.  I have tested the my 
process works between functions.  I have not been able to find anything 
on google relating to this problem.  Right now I am using Python 2.4.3 
on a 64bit Linux box.  Below is a stack trace and below that is the 
script.  To run the script start the server in one command line: python 
BegPython.py server and in another shell start the client with python 
BegClient.py client . Thanks in advance for your help.  -ds

Traceback (most recent call last):
  File "BegClient.py", line 77, in ?
    elif sys.argv[1].lower() == "client": BegClient()
  File "BegClient.py", line 41, in BegClient
    data = DeserialDecode(recv_basic(mySocket))
  File "BegClient.py", line 23, in DeserialDecode
    return cPickle.loads(base64.decodestring(data))
EOFError

BegClient.py:

# To Run client server start the server then the client:
# python BegClient.py Server
# python BegClient.py Client

def Test():
    import cPickle, base64
    str = "This is one thing that I just do not understand, \
            but I will give it a shot"
    print str
    str = SerialEncode(str)
    print str
    str = DeserialDecode(str)
    print str

def SerialEncode(data):
    import cPickle, base64
    return base64.encodestring(cPickle.dumps(data,2))

def DeserialDecode(data):
    import cPickle, base64
    return cPickle.loads(base64.decodestring(data))

def recv_basic(the_socket):
    total_data=[]
    while True:
        data = the_socket.recv(8192)
        print data
        if data != "": break
        total_data.append(data)
    print "Finished Recving data"
    return ''.join(total_data)
   
def BegClient():
   
    import socket, cPickle
    mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
   
    mySocket.connect ( ( "", 64268 ) )
    data = DeserialDecode(recv_basic(mySocket))
    print data
   
    mySocket.send( SerialEncode("Hello!"))
    data = DeserialDecode(recv_basic(mySocket))
    print data
   
    mySocket.send( SerialEncode("Bye!"))
    print data
    mySocket.close()

def BegServer():
    import socket, sys, __builtin__
    def myhook(code):
        return code;
    sys.displayhook = myhook
   
    mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
    mySocket.bind ( ( '', 64268 ) )
    mySocket.listen ( 1 )
    i = 0
   
    import cPickle
   
    while i < 10:
       i += 1
       channel, details = mySocket.accept()
       print 'We have opened a connection with', details
       channel.send ( SerialEncode("What's up"))
       code = DeserialDecode(recv_basic(channel))
       print code
      
      
if __name__ == "__main__":
    import sys
    if sys.argv[1].lower() == "server": BegServer()
    elif sys.argv[1].lower() == "client": BegClient()
    else:
        Test()

From kent37 at tds.net  Sun Feb 11 13:54:30 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Feb 2007 07:54:30 -0500
Subject: [Tutor] token parser
In-Reply-To: <e9764b730702110019v49149far6047f1dd8d149139@mail.gmail.com>
References: <e9764b730702110019v49149far6047f1dd8d149139@mail.gmail.com>
Message-ID: <45CF1206.3000905@tds.net>

Dj Gilcrease wrote:
> How would I go about writing a fast token parser to parse a string like
> "[4d6.takeHighest(3)+(2d6*3)-5.5]"
> 
> and get a list like
> ['+',
>     ['takeHighest',
>         ['d',
>             4,
>             6
>         ],
>         3
>     ],
>     ['-',
>         ['*',
>             ['d',
>                 2,
>                 6
>             ],
>             3
>         ],
>         5.5
>     ]
> ]
> 
> back? ( I put it all separated and indented like that so it is easier
> to read, it is for me anyways )

If your input is valid Python (which the above is not, 4d6 and 2d6 are 
not valid identifiers) then perhaps the compiler.parse() function would 
be a good starting point. It generates an abstract syntax tree which you 
could perhaps transform into the format you want:

In [13]: import compiler

In [19]: compiler.parse("[d6.takeHighest(3)+(d6*3)-5.5]")

Out[19]: Module(None, 
Stmt([Discard(List([Sub((Add((CallFunc(Getattr(Name('d6'), 
'takeHighest'), [Const(3)], None, None), Mul((Name('d6'), Const(3))))
), Const(5.5)))]))]))


If this doesn't work for you, then I would look to one of the many 
parser-generator packages available for Python. I don't know which is 
fastest; I have found pyparsing and PLY to be fairly easy to use. 
pyparsing comes with a lot of examples which might help you get started. 
Here are some summaries of the options:
http://www.nedbatchelder.com/text/python-parsers.html
http://wiki.python.org/moin/LanguageParsing
http://radio.weblogs.com/0100945/2004/04/24.html

Here is an article that gives some examples:
http://www.rexx.com/~dkuhlman/python_201/python_201.html#SECTION007000000000000000000
http://www-128.ibm.com/developerworks/linux/library/l-cpdpars.html?ca=dgr-lnxw02DParser
and the references in the above

Kent


From kent37 at tds.net  Sun Feb 11 14:04:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Feb 2007 08:04:41 -0500
Subject: [Tutor] Unpickling data after passing over the network
In-Reply-To: <45CEB364.5050904@mail.utexas.edu>
References: <45CEB364.5050904@mail.utexas.edu>
Message-ID: <45CF1469.4030101@tds.net>

Adam Pridgen wrote:
> Hello,
> 
> I am having problems with unpickling data after I pass the data through 
> a socket.   Right now, I am pickling a basic string base 64 encoding and 
> sending the data over the network.  After the recipient client/server 
> receives the data, it is decoded and then unpickled.  The unpickling 
> fails with an EOFError, and I am not sure why.  

I don't know what the problem is, but I suspect that the data is not 
arriving all at once at the client. I would put in some print statements 
so you can compare what you send to what you receive. (Adding the prints 
will change the timing; this may make it start to work. That in itself 
will be a clue.) Since you are just sending strings in this program, 
maybe you should strip out the base64 and pickle stuff for now and get 
it working with bare strings.

If you are trying to create a way to send objects over a socket you 
might want to look at what is already available. Pyro is well-regarded.
http://pyro.sourceforge.net/

Kent

> I have tested the my 
> process works between functions.  I have not been able to find anything 
> on google relating to this problem.  Right now I am using Python 2.4.3 
> on a 64bit Linux box.  Below is a stack trace and below that is the 
> script.  To run the script start the server in one command line: python 
> BegPython.py server and in another shell start the client with python 
> BegClient.py client . Thanks in advance for your help.  -ds
> 
> Traceback (most recent call last):
>   File "BegClient.py", line 77, in ?
>     elif sys.argv[1].lower() == "client": BegClient()
>   File "BegClient.py", line 41, in BegClient
>     data = DeserialDecode(recv_basic(mySocket))
>   File "BegClient.py", line 23, in DeserialDecode
>     return cPickle.loads(base64.decodestring(data))
> EOFError
> 
> BegClient.py:
> 
> # To Run client server start the server then the client:
> # python BegClient.py Server
> # python BegClient.py Client
> 
> def Test():
>     import cPickle, base64
>     str = "This is one thing that I just do not understand, \
>             but I will give it a shot"
>     print str
>     str = SerialEncode(str)
>     print str
>     str = DeserialDecode(str)
>     print str
> 
> def SerialEncode(data):
>     import cPickle, base64
>     return base64.encodestring(cPickle.dumps(data,2))
> 
> def DeserialDecode(data):
>     import cPickle, base64
>     return cPickle.loads(base64.decodestring(data))
> 
> def recv_basic(the_socket):
>     total_data=[]
>     while True:
>         data = the_socket.recv(8192)
>         print data
>         if data != "": break
>         total_data.append(data)
>     print "Finished Recving data"
>     return ''.join(total_data)
>    
> def BegClient():
>    
>     import socket, cPickle
>     mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
>    
>     mySocket.connect ( ( "", 64268 ) )
>     data = DeserialDecode(recv_basic(mySocket))
>     print data
>    
>     mySocket.send( SerialEncode("Hello!"))
>     data = DeserialDecode(recv_basic(mySocket))
>     print data
>    
>     mySocket.send( SerialEncode("Bye!"))
>     print data
>     mySocket.close()
> 
> def BegServer():
>     import socket, sys, __builtin__
>     def myhook(code):
>         return code;
>     sys.displayhook = myhook
>    
>     mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
>     mySocket.bind ( ( '', 64268 ) )
>     mySocket.listen ( 1 )
>     i = 0
>    
>     import cPickle
>    
>     while i < 10:
>        i += 1
>        channel, details = mySocket.accept()
>        print 'We have opened a connection with', details
>        channel.send ( SerialEncode("What's up"))
>        code = DeserialDecode(recv_basic(channel))
>        print code
>       
>       
> if __name__ == "__main__":
>     import sys
>     if sys.argv[1].lower() == "server": BegServer()
>     elif sys.argv[1].lower() == "client": BegClient()
>     else:
>         Test()
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From rfquerin at gmail.com  Sun Feb 11 14:05:28 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Sun, 11 Feb 2007 08:05:28 -0500
Subject: [Tutor] Trouble getting os.execl() command to work
In-Reply-To: <45CEB2AA.2010404@gmail.com>
References: <7d81675b0702101926q68500593qc59cd50d2deb5d5@mail.gmail.com>
	<45CEB2AA.2010404@gmail.com>
Message-ID: <7d81675b0702110505q64ba6c1ej502519e2f8d4ecde@mail.gmail.com>

On 2/11/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
>
> > for name in filelist:
> oops! filelist still contains the non-normalized names of the files!
> >


Dang! Thank you sir. I should have recaptured the file list before
continuing on.


Alan - thanks for the great info as well. I will check it out and hopefully
streamline it. I haven't worked with the os module much before, thanks for
pointing me in the right direction.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070211/96f8fb2f/attachment.htm 

From ebbaalm at uiuc.edu  Sun Feb 11 14:59:54 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sun, 11 Feb 2007 07:59:54 -0600
Subject: [Tutor] Follow-up Qs: Re: Identity operator (basic types)
Message-ID: <7a4620dc0702110559h130eb7bdifcd221554abd629a@mail.gmail.com>

Thanks for the respones. A few follow-up questions:

For these basic types (float, integer, string, char, bool) does python
always figure out the identity change when assigning a 'new value',
as it seems to do below?

>>> i = "hi"
>>> j = i
>>> print i, j, id(i), id(j)
hi hi 12235136 12235136
>>> j += i
>>> print i, j, id(i), id(j)
hi hihi 12235136 13579872

In other words, could there ever be a risk of overwriting the original value
when copying variables, like i=j?

Does one ever have to worry about using copy.deepcopy(i) for these basic
types (float, integer, string, char, bool) to avoid overwriting the
value of the original (like one may have to do for lists and dictionaries?)

When we copy any such data type (float, integer, string, char, bool) into a
function definition's local scope, does it always copy-by-value then? (so
one does not have to worry about the original variable's identity and value
being changed?)

>>> def sum(k):
    print k, id(k)
    k += 1
    print k, id(k)


>>> a = 1234
>>> print a, id(a)
1234 12536936
>>> sum(a)
1234 12536936
1235 12536876
>>> print a, id(a)
1234 12536936
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070211/8d0968c2/attachment.html 

From kent37 at tds.net  Sun Feb 11 15:34:20 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Feb 2007 09:34:20 -0500
Subject: [Tutor] Follow-up Qs: Re: Identity operator (basic types)
In-Reply-To: <7a4620dc0702110559h130eb7bdifcd221554abd629a@mail.gmail.com>
References: <7a4620dc0702110559h130eb7bdifcd221554abd629a@mail.gmail.com>
Message-ID: <45CF296C.8070404@tds.net>

Cecilia Alm wrote:
> Thanks for the respones. A few follow-up questions:
> 
> For these basic types (float, integer, string, char, bool) does python 
> always figure out the identity change when assigning a 'new value',
> as it seems to do below?
> 
>  >>> i = "hi"
>  >>> j = i
>  >>> print i, j, id(i), id(j)
> hi hi 12235136 12235136
>  >>> j += i
>  >>> print i, j, id(i), id(j)
> hi hihi 12235136 13579872
> 
> In other words, could there ever be a risk of overwriting the original 
> value when copying variables, like i=j?

No.

Did you read the article I pointed to before? Did you "reset your brain" 
as it requests :-) I don't think you understand what Python assignment 
does yet. Python assignment does not copy a value, it creates a new name 
for a value.
> 
> Does one ever have to worry about using copy.deepcopy(i) for these basic 
> types (float, integer, string, char, bool) to avoid overwriting the
> value of the original (like one may have to do for lists and dictionaries?)

No. You can't "overwrite" a value under an circumstances; the concept 
does not make sense in Python.

What you can do is have two names that refer to the same value. If the 
value is mutable, like a list or dict, then changing the value through 
one name will affect the value as seen through the other name. This is 
not overwriting, it is aliasing.

For immutable values you can't change the actual value, you can just 
bind a name to a new value, so the aliasing cannot have unexpected 
side-effects.
> 
> When we copy any such data type (float, integer, string, char, bool) 
> into a function definition's local scope, does it always copy-by-value 
> then? (so one does not have to worry about the original variable's 
> identity and value being changed?)

Again, parameter passing is not copying, it is name-binding. If you pass 
a mutable value to a function and change it in the function, the caller 
will see the change. But name binding inside a function will not affect 
name binding in the caller.

Sorry this is very brief, I don't have time for more explanation. Maybe 
someone else can jump in here.

Kent

> 
>  >>> def sum(k):
>     print k, id(k)
>     k += 1
>     print k, id(k)
> 
>    
>  >>> a = 1234
>  >>> print a, id(a)
> 1234 12536936
>  >>> sum(a)
> 1234 12536936
> 1235 12536876
>  >>> print a, id(a)
> 1234 12536936
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From eike.welk at gmx.net  Sun Feb 11 16:52:18 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Sun, 11 Feb 2007 16:52:18 +0100
Subject: [Tutor] token parser
In-Reply-To: <e9764b730702110019v49149far6047f1dd8d149139@mail.gmail.com>
References: <e9764b730702110019v49149far6047f1dd8d149139@mail.gmail.com>
Message-ID: <200702111652.18810.eike.welk@gmx.net>

A nice parsing library is pyparsing:
http://pyparsing.wikispaces.com/

It contains a parser for mathematical expressions.
There are examples in the source distribution.

HTH,
Eike.


From hgfernan at lsi.usp.br  Sun Feb 11 17:27:11 2007
From: hgfernan at lsi.usp.br (Hilton Garcia Fernandes)
Date: Sun, 11 Feb 2007 16:27:11 -0000
Subject: [Tutor] A doxygen-like tool for Python ?
Message-ID: <twig.1171211231.93638@lsi.usp.br>



-- 
Hilton Garcia Fernandes
Nucleo de Tecnologias sem Fio (NTSF) -- Wireless Technologies Team
Lab de Sistemas Integraveis Tecnologico (LSI) -- Integrable Systems Lab
Escola Politecnica (Poli) -- Engineering School
Univ S Paulo (USP)
Tel: (5511)3091-5676 (work)
     (5511)8131-5213 (mobile)
Av. Prof. Luciano Gualberto,158 trav.3 CEP 05508-900
S. Paulo -- SP -- Brazil
Pagina inicial: http://www.lsi.usp.br/~hgfernan



From hgfernan at lsi.usp.br  Sun Feb 11 17:34:06 2007
From: hgfernan at lsi.usp.br (Hilton Garcia Fernandes)
Date: Sun, 11 Feb 2007 16:34:06 -0000
Subject: [Tutor] A doxygen-like tool for Python ?
Message-ID: <twig.1171211646.88482@lsi.usp.br>

Dear all,

i've been using doxygen for quite a time to document softwares written in
C and C++, but could not found a similar tool for Python software.

Could you please point me to a suitable tool ? As we could see in a
previous thread, Python exposes its parsing in publically available APIs.
So, source documentation tool should be easier to write than languages
that don't have such a facility. 

Thanks, 
hilton


From chris.arndt at web.de  Sun Feb 11 17:58:09 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Sun, 11 Feb 2007 17:58:09 +0100
Subject: [Tutor] A doxygen-like tool for Python ?
In-Reply-To: <twig.1171211646.88482@lsi.usp.br>
References: <twig.1171211646.88482@lsi.usp.br>
Message-ID: <45CF4B21.2050800@web.de>

Hilton Garcia Fernandes schrieb:
> Dear all,
> 
> i've been using doxygen for quite a time to document softwares written in
> C and C++, but could not found a similar tool for Python software.
> 
> Could you please point me to a suitable tool ?

How about http://epydoc.sourceforge.net/ ?

Chris

From mail at timgolden.me.uk  Sun Feb 11 18:50:23 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Sun, 11 Feb 2007 17:50:23 +0000
Subject: [Tutor] A doxygen-like tool for Python ?
In-Reply-To: <45CF4B21.2050800@web.de>
References: <twig.1171211646.88482@lsi.usp.br> <45CF4B21.2050800@web.de>
Message-ID: <45CF575F.2050806@timgolden.me.uk>

Christopher Arndt wrote:
> Hilton Garcia Fernandes schrieb:
>> Dear all,
>>
>> i've been using doxygen for quite a time to document softwares written in
>> C and C++, but could not found a similar tool for Python software.
>>
>> Could you please point me to a suitable tool ?
> 
> How about http://epydoc.sourceforge.net/ ?

Or, possibly, Doxygen since it seems to handle
Python anyway. Or have I missed something?

http://www.stack.nl/~dimitri/doxygen/docblocks.html#pythonblocks

TJG

From kent37 at tds.net  Sun Feb 11 19:14:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Feb 2007 13:14:55 -0500
Subject: [Tutor] A doxygen-like tool for Python ?
In-Reply-To: <twig.1171211646.88482@lsi.usp.br>
References: <twig.1171211646.88482@lsi.usp.br>
Message-ID: <45CF5D1F.3000505@tds.net>

Hilton Garcia Fernandes wrote:
> Dear all,
> 
> i've been using doxygen for quite a time to document softwares written in
> C and C++, but could not found a similar tool for Python software.
> 
> Could you please point me to a suitable tool ? As we could see in a
> previous thread, Python exposes its parsing in publically available APIs.
> So, source documentation tool should be easier to write than languages
> that don't have such a facility. 

Many choices here:
http://epydoc.sourceforge.net/relatedprojects.html

I think pydoc, epydoc and maybe pythondoc are the most popular. Search 
comp.lang.python for epydoc, etc for lots of discussion.

Kent


From dyoo at cs.wpi.edu  Sun Feb 11 19:48:52 2007
From: dyoo at cs.wpi.edu (Daniel Yoo)
Date: Sun, 11 Feb 2007 13:48:52 -0500 (EST)
Subject: [Tutor] Unpickling data after passing over the network
In-Reply-To: <45CEB364.5050904@mail.utexas.edu>
References: <45CEB364.5050904@mail.utexas.edu>
Message-ID: <Pine.LNX.4.63.0702111339520.26531@cs.wpi.edu>

> a socket.  Right now, I am pickling a basic string base 64 encoding and 
> sending the data over the network.  After the recipient client/server 
> receives the data, it is decoded and then unpickled.  The unpickling 
> fails with an EOFError, and I am not sure why.

Hi Adam,

Did you "flush" the output buffer?  Network sockets are, like files, 
typically buffered, so you may need to tell the system to not wait for the 
buffer to fill.


Let me look at your functions to see if there's anything else you'll want 
to think about.


> def SerialEncode(data):
>    import cPickle, base64
>    return base64.encodestring(cPickle.dumps(data,2))
>
> def DeserialDecode(data):
>    import cPickle, base64
>    return cPickle.loads(base64.decodestring(data))


You can simplify by pulling the imports of 'cPickle' and 'base64' out to 
the top.



>    mySocket.send( SerialEncode("Hello!"))
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Ok, this is one source of a problem.

Remember what you did with the recv's earlier, with the looping?  Same 
thing: send() isn't guaranteed to write all the bytes out at once.  Read 
the documentation to send() a little closely, and you'll see the warning 
there:

     http://docs.python.org/lib/socket-objects.html#l2h-3696


One way to get around this is to work at a higher level of abstraction: 
sockets can also be treated as file-like objects which do the looping for 
you automatically, at the expense of having less control over the socket. 
See socket.makefile():

     http://docs.python.org/lib/socket-objects.html#l2h-3693


Otherwise, everything else looks ok from a casual glance.


Good luck!

From hgfernan at lsi.usp.br  Sun Feb 11 20:20:47 2007
From: hgfernan at lsi.usp.br (Hilton Garcia Fernandes)
Date: Sun, 11 Feb 2007 19:20:47 -0000
Subject: [Tutor] A doxygen-like tool for Python ?
In-Reply-To: <45CF575F.2050806@timgolden.me.uk>
References: <twig.1171211646.88482@lsi.usp.br> <45CF4B21.2050800@web.de>,
	<45CF4B21.2050800@web.de>
Message-ID: <twig.1171221647.70976@lsi.usp.br>

First of all, sorry for an empty message to the list. :-}

Second, thanks for the input. 

Concerning Doxygen for Python, the page shown tell how to make Doxygen
read Python documentation strings, but that's not practical for 3rd party,
undocumented programs. For programs using C and C++, Doxygen can parse the
code and make impressive callgraphs. Of course, besides being cute they're
very useful. :)

For Python, Doxygen relies on a filter. Please see page Helper tools &
scripts, in 

http://www.stack.nl/~dimitri/doxygen/helpers.html

It informs of a Python-to-C++ filter, based on class headers, but
unfortunately, this approach is very limited... 

Concerning Epydoc, last time i tried it was not as complete as Doxygen for
C/C++. The project is very active though, so maybe the new version is more
complete.

I'll try it and report to the list, if there's enough interest. 

All the best,
hilton

On Sun, Feb 11, 2007, Tim Golden <mail at timgolden.me.uk> said:

> Christopher Arndt wrote:
>> Hilton Garcia Fernandes schrieb:
>>> Dear all,
>>>
>>> i've been using doxygen for quite a time to document softwares written in
>>> C and C++, but could not found a similar tool for Python software.
>>>
>>> Could you please point me to a suitable tool ?
>> 
>> How about http://epydoc.sourceforge.net/ ?
> 
> Or, possibly, Doxygen since it seems to handle
> Python anyway. Or have I missed something?
> 
> http://www.stack.nl/~dimitri/doxygen/docblocks.html#pythonblocks
> 
> TJG
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Hilton Garcia Fernandes
Nucleo de Tecnologias sem Fio (NTSF) -- Wireless Technologies Team
Lab de Sistemas Integraveis Tecnologico (LSI) -- Integrable Systems Lab
Escola Politecnica (Poli) -- Engineering School
Univ S Paulo (USP)
Tel: (5511)3091-5676 (work)
     (5511)8131-5213 (mobile)
Av. Prof. Luciano Gualberto,158 trav.3 CEP 05508-900
S. Paulo -- SP -- Brazil
Pagina inicial: http://www.lsi.usp.br/~hgfernan



From nephish at gmail.com  Sun Feb 11 22:15:45 2007
From: nephish at gmail.com (shawn bright)
Date: Sun, 11 Feb 2007 15:15:45 -0600
Subject: [Tutor] question about importing threads
In-Reply-To: <896668.54115.qm@web86104.mail.ird.yahoo.com>
References: <896668.54115.qm@web86104.mail.ird.yahoo.com>
Message-ID: <384c93600702111315o23741c50l61385ee16367b252@mail.gmail.com>

Yes, Mr Gauld, this is a help. Even though i am still newbie enough to take
some time digesting it.

one last queston. if i have a class that i import as a module, say a script
that emails me when something goes wrong.
so i have a file called my_own_email.py and in it a class called MyOwnEmail.
Now MyOwnEmail needs the smtplib module. Do i need to import it just for the
my_own_email.py or do i need to import it in both that module and my program
that calls it. ?

thanks


On 2/9/07, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>
> > i have two classes in my program that use a global object
> > that is a socket connection.
> > ... code snipped
> > is there something tricky about passing this as a global object to
> > different modules that would need to use it?
>
> Whiler its possible to use a global in this way its usually better to
> avoid global objects in a reusable component since otherwise it
> might clash with another global that the reuser already has. Its much
> better to use a parameter which can be provided by the user of the
> classes. In this case the socklet becomesc a parameter.
>
> A good place to put this parameter would be the init method of both
> your classes, where they would store a reference to it as an internal
> attribute. (remember that in Python all attributes are references so if
> you pass the same socket to both constructors both classes will point
> at the same socket).
>
> This approach also allows the user of your classes to suvbstitute
> any socketlike object that they mauy have, even their own bespoke
> version if needed. That greatly increases the flexibility of your code.
>
> > Or does this go along with what you wrote a while back about
> > having classes that depend on each other ?
>
> If you really must use a shared global then I would strongly consider
> putting both classes, the global variable and an initialisation function
> all in a single module. If however tyou can parameterise things as
> described then you need to consider whether anyone would be
> able to (and want to) use either of the classes without the other.
> If you always need them as a pair they still should go in one module,
> otherwise put them in separate modules.
>
> > One runs as a thread, the other responds to gui input.
>
> Does it respond to GUI input or just input? If it can be independant
> of the GUI (and you should really try hard to make it so) then its
> independant and best in its own module. The fact that the other runs
> in a thred is fairly irrelevant to this discussion, the real issue is
> whether it has hard coded dependencies on the other class. For
> example does it instantiate a copy within its methods? (in which
> case you must import the other module/class into this module) And
> more especially does it take an instance as a parameter of a method?
> (in which case the *re-user* must import the other module.) In the second
> case I'd say definitely put them in a single module, in the first case
> consider it, but it's not essential.
>
> I hope that makes sense,
>
> Alan G.
>
>
> On 12/31/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
> >
> > "shawn bright" <nephish at gmail.com> wrote
> >
> > > Yes, the thing is getting to be a pain to deal with at this size, i
> > > am
> > > in-process of splitting out the classes into their own files.
> >
> > One thing to watch is that while its easy and tempting to create
> > one file per class it's often better to keep dependant classes
> > together.
> > In other words if class A can only be used together with class B
> > then it is often better to keep A and B in the same module.
> > Anyone who needs B can import the module and anyone who
> > needs A needs B too so it saves them having to import two
> > modules.
> >
> > As in all things in programming a little bit of thought is often
> > better than the first "obvious" strategy. Grady Booch described
> > the above strategy by saying that "the unit of reuse is the category"
> > (which in his OO notation was a set of related classes) and in
> > Python that means the module.
> >
> > Regards,
> >
> > Alan G.
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> ------------------------------
> New Yahoo! Mail is the ultimate force in competitive emailing. Find out
> more at the Yahoo! Mail Championships<http://uk.rd.yahoo.com/mail/uk/taglines/gmail_com/championships/games/*http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk/>.
> Plus: play games and win prizes.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070211/6a554ad1/attachment.htm 

From kent37 at tds.net  Sun Feb 11 22:39:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Feb 2007 16:39:45 -0500
Subject: [Tutor] question about importing threads
In-Reply-To: <384c93600702111315o23741c50l61385ee16367b252@mail.gmail.com>
References: <896668.54115.qm@web86104.mail.ird.yahoo.com>
	<384c93600702111315o23741c50l61385ee16367b252@mail.gmail.com>
Message-ID: <45CF8D21.1030802@tds.net>

shawn bright wrote:
> one last queston. if i have a class that i import as a module, say a 
> script that emails me when something goes wrong.
> so i have a file called my_own_email.py and in it a class called 
> MyOwnEmail. Now MyOwnEmail needs the smtplib module. Do i need to import 
> it just for the my_own_email.py or do i need to import it in both that 
> module and my program that calls it. ?

You only have to import a module in the module that uses it.

Kent


From nephish at gmail.com  Sun Feb 11 22:59:19 2007
From: nephish at gmail.com (shawn bright)
Date: Sun, 11 Feb 2007 15:59:19 -0600
Subject: [Tutor] question about importing threads
In-Reply-To: <45CF8D21.1030802@tds.net>
References: <896668.54115.qm@web86104.mail.ird.yahoo.com>
	<384c93600702111315o23741c50l61385ee16367b252@mail.gmail.com>
	<45CF8D21.1030802@tds.net>
Message-ID: <384c93600702111359m7d8f0706hf2c9a26587bd217b@mail.gmail.com>

great, saves me 15 lines.
thanks

sk

On 2/11/07, Kent Johnson <kent37 at tds.net> wrote:
>
> shawn bright wrote:
> > one last queston. if i have a class that i import as a module, say a
> > script that emails me when something goes wrong.
> > so i have a file called my_own_email.py and in it a class called
> > MyOwnEmail. Now MyOwnEmail needs the smtplib module. Do i need to import
> > it just for the my_own_email.py or do i need to import it in both that
> > module and my program that calls it. ?
>
> You only have to import a module in the module that uses it.
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070211/6abfb1b2/attachment.html 

From rabidpoobear at gmail.com  Sun Feb 11 23:35:27 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 11 Feb 2007 16:35:27 -0600
Subject: [Tutor] question about importing threads
In-Reply-To: <384c93600702111359m7d8f0706hf2c9a26587bd217b@mail.gmail.com>
References: <896668.54115.qm@web86104.mail.ird.yahoo.com>	<384c93600702111315o23741c50l61385ee16367b252@mail.gmail.com>	<45CF8D21.1030802@tds.net>
	<384c93600702111359m7d8f0706hf2c9a26587bd217b@mail.gmail.com>
Message-ID: <45CF9A2F.6090804@gmail.com>

shawn bright wrote:
> great, saves me 15 lines.
> thanks
You have 15 lines of imports?

From kent37 at tds.net  Mon Feb 12 01:15:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Feb 2007 19:15:23 -0500
Subject: [Tutor] MSI Installers for python
In-Reply-To: <45CE04A6.7000806@gmail.com>
References: <45CE04A6.7000806@gmail.com>
Message-ID: <45CFB19B.5030605@tds.net>

demonic.software at gmail.com wrote:
> Hello,
> 
> I was wondering if anyone can offer any examples, pointers, tutorials, 
> or howtos  on developing an MSI installer file for windows using Python. 
>   I found the msilib reference in the Python 2.5 documents, but I am not 
> familiar with this area and I am trying find any examples (code wise) 
> that implement the msilib.  I did check Google, but there did not seem 
> to be any good leads.  Thanks in advance,

Are you trying to create an MSI installer of a Python program or 
something else?

The docs for msilib indicate that it supports creation of MSI files for 
Python programs with the bdist_msi command in distutils. bdist_msi seems 
to be included with Python 2.5, it is in 
lib/distutils/command/bdist_msi, but it doesn't seem to be documented in 
the distutils docs. Here is a little bit about it:
http://www.dcl.hpi.uni-potsdam.de/home/loewis/bdist_msi/

General information about using distutils is here:
http://docs.python.org/dist/dist.html

I have never used distutils myself (other than to install stuff) so I 
probably can't give you much more help than this.

Kent



From carroll at tjc.com  Mon Feb 12 01:19:45 2007
From: carroll at tjc.com (Terry Carroll)
Date: Sun, 11 Feb 2007 16:19:45 -0800 (PST)
Subject: [Tutor] Geolocating objects
In-Reply-To: <634218.22046.qm@web55204.mail.re4.yahoo.com>
Message-ID: <Pine.LNX.4.44.0702111547490.9426-100000@violet.rahul.net>

On Sat, 10 Feb 2007, anil maran wrote:

> i m trying to use python to find the proximity of a person using lat
> long gps and zipcodes. 

A google search on "distance latitude longitude" will find you a number of 
pages with the math you need to determine distance, if you know latitude 
and longitude.

http://mathforum.org/library/drmath/sets/select/dm_lat_long.html has links 
to a few different pages explaining.  Another is at 
http://www.movable-type.co.uk/scripts/LatLong.html .

To go from zip codes to latitude and longitude: I vaguely remember that 
the U.S. Census Bureau had a humongous file with that data.  Ah, here you 
go: http://www.census.gov/geo/www/gazetteer/places2k.html

Good luck!


From demonic.software at gmail.com  Mon Feb 12 01:33:38 2007
From: demonic.software at gmail.com (demonic.software at gmail.com)
Date: Sun, 11 Feb 2007 18:33:38 -0600
Subject: [Tutor] MSI Installers for python
In-Reply-To: <45CFB19B.5030605@tds.net>
References: <45CE04A6.7000806@gmail.com> <45CFB19B.5030605@tds.net>
Message-ID: <45CFB5E2.1090108@gmail.com>

Thanks for your reply.

Yes. I am trying to build an MSI installer file using python.  Thank you 
for the pointers.  I'll see if I can glean any information from that and 
who know even post a short tutorial ;).  Thanks again.



Kent Johnson wrote:
> demonic.software at gmail.com wrote:
>> Hello,
>>
>> I was wondering if anyone can offer any examples, pointers, tutorials, 
>> or howtos  on developing an MSI installer file for windows using 
>> Python.   I found the msilib reference in the Python 2.5 documents, 
>> but I am not familiar with this area and I am trying find any examples 
>> (code wise) that implement the msilib.  I did check Google, but there 
>> did not seem to be any good leads.  Thanks in advance,
> 
> Are you trying to create an MSI installer of a Python program or 
> something else?
> 
> The docs for msilib indicate that it supports creation of MSI files for 
> Python programs with the bdist_msi command in distutils. bdist_msi seems 
> to be included with Python 2.5, it is in 
> lib/distutils/command/bdist_msi, but it doesn't seem to be documented in 
> the distutils docs. Here is a little bit about it:
> http://www.dcl.hpi.uni-potsdam.de/home/loewis/bdist_msi/
> 
> General information about using distutils is here:
> http://docs.python.org/dist/dist.html
> 
> I have never used distutils myself (other than to install stuff) so I 
> probably can't give you much more help than this.
> 
> Kent
> 
> 
> 

From alan.gauld at btinternet.com  Mon Feb 12 02:06:54 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Feb 2007 01:06:54 -0000
Subject: [Tutor] Follow-up Qs: Re: Identity operator (basic types)
References: <7a4620dc0702110559h130eb7bdifcd221554abd629a@mail.gmail.com>
Message-ID: <eqoejf$vg7$1@sea.gmane.org>

"Cecilia Alm" <ebbaalm at uiuc.edu> wrote

> When we copy any such data type (float, integer, string, char, bool) 
> into a
> function definition's local scope, does it always copy-by-value 
> then?

Kent has already answered this but no. we never copy by value
in Python, we create a new reference to the value.

>>>> def sum(k):
>    print k, id(k)
>    k += 1

This is actually k = k + 1
So k now refers to a new value which is one more than the
original value.

>>>> a = 1234
>>>> print a, id(a)
> 1234 12536936
>>>> sum(a)

This sets k to point to the same value as a: 1234

> 1234 12536936
> 1235 12536876

k now refers to the new value 1235. But a still refers to its
original value:

>>>> print a, id(a)
> 1234 12536936

As seen here.

As Kent said, you need to change your way of thinking
about variables and values. In Python variables are just
names. In fact they are dictionary keys. You can even
print the dictionary if you want, its called locals.

>>> x = 42
>>> print locals()
{'__builtins__': <module '__builtin__' (built-in)>,
'x': 42,
'__name__': '__main__',
'__doc__': None}

Notice that my x appears in the second line...

But its still just a reference to the real object. If I added a
new line y = 42 there would still only be a single 42 object
and both x and y dictionary entries would point at it.

HTH,

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



From kubota2550 at gmail.com  Mon Feb 12 12:28:44 2007
From: kubota2550 at gmail.com (kubota2550 at gmail.com)
Date: Mon, 12 Feb 2007 06:28:44 -0500
Subject: [Tutor] Random Number Randrange
Message-ID: <5900d730702120328l2f21b7dbl3468fd1a23fc53a8@mail.gmail.com>

When I  use the function random.randrange(x,y) I never get the upper limit y
in the list.  I've tried the range 1,3 and never get 3.  If I choose 1,4 I
get 3 but never 4.  Is the upperlimit actually <y instead of <=y?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070212/d37c4590/attachment.html 

From alan.gauld at btinternet.com  Mon Feb 12 15:04:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Feb 2007 14:04:05 -0000
Subject: [Tutor] Random Number Randrange
References: <5900d730702120328l2f21b7dbl3468fd1a23fc53a8@mail.gmail.com>
Message-ID: <eqps4n$svv$1@sea.gmane.org>


<kubota2550 at gmail.com> wrote

> When I  use the function random.randrange(x,y) I never get the upper 
> limit y
> in the list.  I've tried the range 1,3 and never get 3.  If I choose 
> 1,4 I
> get 3 but never 4.  Is the upperlimit actually <y instead of <=y?

The documentation says it returns a value in the *range* min,max.

A range in Python returns the values min....max-1:

>>> print range(1,3)
[1,2]

HTH,

Alan G. 



From les.hazlett at navteq.com  Mon Feb 12 19:49:22 2007
From: les.hazlett at navteq.com (Hazlett, Les)
Date: Mon, 12 Feb 2007 12:49:22 -0600
Subject: [Tutor] How to pass a large list to another object?
Message-ID: <B76F47F45A9B184781E0A41F711B516CADFFAC@NAEXC.ad.navteq.com>

Hello,

I just joined the list.  I have searched the archives unsuccessfully
trying to learn how to approach my problem.  So I have 2 questions - 

	1) How can I best pass a large list to another object?  

	2) How could I have found related discussion with a search of
the archives?

If I pass a large list via a parameter, there will be two copies of the
list.  Is there a way to avoid this additonal demand on RAM other than
having the lists global?  

Thanks for any help and advice on effectively using the tutor mailing
list.

Les



The information contained in this communication may be CONFIDENTIAL and is intended only for the use of the recipient(s) named above. If you are not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication, or any of its contents, is strictly prohibited. If you have received this communication in error, please notify the sender and delete/destroy the original message and any copy of it from your computer or paper files.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070212/f36aa836/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/gif
Size: 145 bytes
Desc: Blank Bkgrd.gif
Url : http://mail.python.org/pipermail/tutor/attachments/20070212/f36aa836/attachment.gif 

From kent37 at tds.net  Mon Feb 12 20:19:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Feb 2007 14:19:38 -0500
Subject: [Tutor] How to pass a large list to another object?
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CADFFAC@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CADFFAC@NAEXC.ad.navteq.com>
Message-ID: <45D0BDCA.7060504@tds.net>

Hazlett, Les wrote:
> Hello,
> 
> I just joined the list.  I have searched the archives unsuccessfully 
> trying to learn how to approach my problem.  So I have 2 questions -
> 
>     1) How can I best pass a large list to another object? 

Just pass it. Python does not pass parameters by value. The list will 
not be copied, rather the object receiving the list will get a reference 
to the same value. (One consequence of this is that changes in the list 
via the new reference will be seen at the old reference; they both refer 
to the same list.)
> 
>     2) How could I have found related discussion with a search of the
>     archives?

There is a searchable archive here:
http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor
but I'm not sure how you would have found an answer to this particular 
question.

> Thanks for any help and advice on effectively using the tutor mailing list.

We're pretty friendly here. Just subscribe to the list and ask your 
questions. If you can show us some code that you have tried or that you 
are confused about, that helps a lot - make your best effort, then ask 
for help. If you get an error message that you don't understand, post 
the entire error, including the traceback, copied verbatim from the console.

Welcome!
Kent


From rikard.bosnjakovic at gmail.com  Mon Feb 12 20:57:07 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 12 Feb 2007 20:57:07 +0100
Subject: [Tutor] How to pass a large list to another object?
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CADFFAC@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CADFFAC@NAEXC.ad.navteq.com>
Message-ID: <d9e88eaf0702121157l71a6ee05j9d535261485b2dc6@mail.gmail.com>

On 2/12/07, Hazlett, Les <les.hazlett at navteq.com> wrote:

> If I pass a large list via a parameter, there will be two copies of the
> list.

No. You pass a *reference* to the list, not the list itself.

>>> a = [1,2,3,4]
>>> b = a
>>> b is a
True
>>> id(b), id(a)
(1075562604, 1075562604)
>>> b = [1,2,3,4]
>>> b is a
False
>>> id(b), id(a)
(1075562796, 1075562604)


The "b = a" makes b reference a, that is a and b points to the same list.

The "b = [1,2,3,4]" destroys the reference-ship with a, and creates a
new list instead. The same goes for "b = a[:]", which is a copy of all
the elements in a.


-- 
- Rikard.

From challman at gmail.com  Mon Feb 12 21:00:49 2007
From: challman at gmail.com (Chris Hallman)
Date: Mon, 12 Feb 2007 15:00:49 -0500
Subject: [Tutor] telnet read_until problems
Message-ID: <9f68812f0702121200k22e1b6a2q269978ad773f492c@mail.gmail.com>

I've written a program that tests ISDN dial backup at 1,000 locations. I've
broken up the logic into server functions within a threading class (i.e.
logon, get interfaces, get dial string, etc.). At 999 locations, the
following code extract the first of three dial strings:

    def GetDialString(self):
        """ This function extracts the dial string."""
        self.tn.write("term len 0\n")
        self.tn.expect([self.host.upper() + "#"], 7)
        self.tn.write("sh dialer | i Default\n")
        self.data = self.tn.read_until(self.host.upper() + "#", 7)
        print self.data
        match = re.search("\d\d\d\d\d\d\d\d\d\d\d+", self.data)
        if match is not None:
            rc = match.group()
        else:
            rc = "missing"
        return rc

One location doesn't return it's dial string. In Idle, the output is:

>>> print data
sh dialer | i Default
17002111000              1          0    8w2d           successful   Default
17002111002              0          0    never                   -   Default
17002111001              1          0    never                   -   Default
J07MR3640#

The "print data" statement yields:

term len 0
J07MR3640#

I've run a packet capture and I see the data coming back every time. I don't
understand why it works fine for 999 out of 1,000 locations. Any
suggestions?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070212/b03049d6/attachment.html 

From alan.gauld at btinternet.com  Mon Feb 12 22:17:16 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Feb 2007 21:17:16 -0000
Subject: [Tutor] telnet read_until problems
References: <9f68812f0702121200k22e1b6a2q269978ad773f492c@mail.gmail.com>
Message-ID: <eqqlgu$emd$1@sea.gmane.org>


"Chris Hallman" <challman at gmail.com> wrote

> I've written a program that tests ISDN dial backup at 1,000 
> locations. I've
> broken up the logic into server functions within a threading class 
> (i.e.
> logon, get interfaces, get dial string, etc.). At 999 locations, the
> following code extract the first of three dial strings:
>
>    def GetDialString(self):

...

> I've run a packet capture and I see the data coming back every time. 
> I don't
> understand why it works fine for 999 out of 1,000 locations. Any
> suggestions?

The figure 999 is interesting. Python has a recursion limit of 1000
levels. Do you by any chance use recursion to call your function?

Otherwise I have no idea. Without seeing more of the code its pretty
hard to see where the breakage might be. I can't see anything obvious
in the function you posted.

HTH,


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



From carroll at tjc.com  Tue Feb 13 02:29:26 2007
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 12 Feb 2007 17:29:26 -0800 (PST)
Subject: [Tutor] Geolocating objects
Message-ID: <Pine.LNX.4.44.0702121725150.14960-100000@violet.rahul.net>

anil maran was asking about determining distances between two US zip 
codes.

I pointed him to a couple resources, but just for the fun of it, tried my 
hand at it.

As far as I know, this actually works:



from math import radians, sin, asin, cos, sqrt, atan2

class ZCTA:
    """
    class for each of the Zip Code Tabulation Areas (U.S. Census)
    """
    
    def __init__(self, line):
        """
        format from http://www.census.gov/geo/www/gazetteer/places2k.html:
        
        * Columns 1-2: United States Postal Service State Abbreviation
        * Columns 3-66: Name (e.g. 35004 5-Digit ZCTA - there are no
          post office names)
        * Columns 67-75: Total Population (2000)
        * Columns 76-84: Total Housing Units (2000)
        * Columns 85-98: Land Area (square meters) - Created for
          statistical purposes only.
        * Columns 99-112: Water Area (square meters) - Created for
          statistical purposes only.
        * Columns 113-124: Land Area (square miles) - Created for
          statistical purposes only.
        * Columns 125-136: Water Area (square miles) - Created for
          statistical purposes only.
        * Columns 137-146: Latitude (decimal degrees) First character
          is blank or "-" denoting North or South latitude respectively
        * Columns 147-157: Longitude (decimal degrees) First character
          is blank or "-" denoting East or West longitude respectively
        """

        import struct

        format = "2s64s9s9s14s14s12s12s10s11sc"
        assert len(line) == 158
        assert struct.calcsize(format) == 158
        # 157 chars as defined above, + one character for newline
        
        _tuple = struct.unpack(format, line)
        self.state = _tuple[0]
        self.ZCTA_name = _tuple[1]
        self.zipcode = self.ZCTA_name[0:5]
        self.pop = _tuple[2]
        self.housing_units = _tuple[3]
        self.land_area_metric = _tuple[4]
        self.water_area_metric = _tuple[5]
        self.land_area = _tuple[6]
        self.water_area = _tuple[7]
        self.latitude = float(_tuple[8])
        self.longitude = float(_tuple[9])
            
zfile = open("zcta5.txt","r")
ZCTAs = {}
for line in zfile:
    z = ZCTA(line)
    ZCTAs[z.zipcode] = z

R = 3956.08833 # circumference of the earth (miles)

while True:
    zipcode1 = raw_input("first zip code: ")
    if zipcode1 == "":
        break
    z1 = ZCTAs[zipcode1]
    print "starting: %s, lat: %s, long: %s" % \
          (z1.zipcode, z1.latitude, z1.longitude)
    zipcode2 = raw_input("second zip code: ")
    if zipcode2 == "":
        break
    z2 = ZCTAs[zipcode2]
    print "starting: %s, lat: %s, long: %s" % \
          (z2.zipcode, z2.latitude, z2.longitude)

    # Calculate the distance:
    # http://www.movable-type.co.uk/scripts/GIS-FAQ-5.1.html
    lon1 = radians(z1.longitude)
    lon2 = radians(z2.longitude)
    lat1 = radians(z1.latitude)
    lat2 = radians(z2.latitude)    
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin((dlat/2.0)**2) + cos(lat1) * cos(lat2) * sin((dlon/2.0)**2)
    # c = 2 * asin(min(1,sqrt(a)))    # alternate formula 
    c = 2 * atan2(sqrt(a), sqrt(1-a)) # distance in radians
    d_miles = R * c # distance in miles
    d_km = d_miles * 1.609344
    
    print "distance from %s to %s is %d miles (%d km)\n" % \
          (zipcode1, zipcode2, d_miles, d_km)



From jalilsan at gmail.com  Tue Feb 13 02:50:07 2007
From: jalilsan at gmail.com (Jalil)
Date: Mon, 12 Feb 2007 17:50:07 -0800
Subject: [Tutor] Accessing installed windows software from python
Message-ID: <5850ed90702121750v31f6f756l42ee14ecbab08087@mail.gmail.com>

I was wondering if its possible to go about writing a code to find out  all
the installed program on a windows machines.  Basically everything under Add
Remove Programs in the control panel.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070212/3e2de734/attachment.html 

From bgailer at alum.rpi.edu  Tue Feb 13 03:04:15 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 12 Feb 2007 18:04:15 -0800
Subject: [Tutor] telnet read_until problems
In-Reply-To: <9f68812f0702121200k22e1b6a2q269978ad773f492c@mail.gmail.com>
References: <9f68812f0702121200k22e1b6a2q269978ad773f492c@mail.gmail.com>
Message-ID: <45D11C9F.7090904@alum.rpi.edu>

Chris Hallman wrote:
>
> I've written a program that tests ISDN dial backup at 1,000 locations. 
> I've broken up the logic into server functions within a threading 
> class (i.e. logon, get interfaces, get dial string, etc.). At 999 
> locations, the following code extract the first of three dial strings:
>
>     def GetDialString(self):
>         """ This function extracts the dial string."""
>         self.tn.write("term len 0\n")
>         self.tn.expect([self.host.upper() + "#"], 7)
>         self.tn.write("sh dialer | i Default\n")
>         self.data = self.tn.read_until(self.host.upper() + "#", 7)
>         print self.data
>         match = re.search("\d\d\d\d\d\d\d\d\d\d\d+", self.data)
>         if match is not None:
>             rc = match.group()
>         else:
>             rc = "missing"
>         return rc
>
> One location doesn't return it's dial string. In Idle, the output is:
>
> >>> print data
> sh dialer | i Default
> 17002111000              1          0    8w2d           successful   
> Default
> 17002111002              0          0    never                   -   
> Default
> 17002111001              1          0    never                   -   
> Default
> J07MR3640#
>
> The "print data" statement yields:
>
> term len 0
> J07MR3640#
>
> I've run a packet capture and I see the data coming back every time. I 
> don't understand why it works fine for 999 out of 1,000 locations. Any 
> suggestions?
Sorry but I find the above confusing. The best guess I can make is that 
the 5 lines following >>> print data is the packet capture, and the 2 
lines following "yields:" is the subset of the packet capture that comes 
into self.data. Is this true? If so are you asking why 
self.tn.read_until(self.host.upper() + "#", 7) does not get all the packet?


-- 
Bob Gailer
510-978-4454


From shadabsayani at yahoo.com  Tue Feb 13 07:01:11 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Tue, 13 Feb 2007 06:01:11 +0000 (GMT)
Subject: [Tutor] Compiling a program ::Embedding Python in C
Message-ID: <20070213060111.71801.qmail@web38708.mail.mud.yahoo.com>

Hi,
I have a C program mm.c calling python function as
follows::
#include "Python.h"
#include <stdio.h>

int main(int argc, char* argv[])
{
        double answer = 0;
        PyObject *modname, *mod, *mdict, *func,
*stringarg, *args, *rslt;

        Py_Initialize();
    modname = PyString_FromString("Test");

    mod = PyImport_Import(modname);
        if (mod)
        {
                mdict = PyModule_GetDict(mod);
                func = PyDict_GetItemString(mdict,
"doit"); // borrowed reference
                if (func)
                {
                        if (PyCallable_Check(func))
                        {
                                stringarg =
PyString_FromString("5");//pay attention here
                                args = PyTuple_New(1);
                                PyTuple_SetItem(args,
0, stringarg);
                                rslt =
PyObject_CallObject(func, args);
                                if (rslt)
                                {
                                        answer =
PyFloat_AsDouble(rslt);
                                       
Py_XDECREF(rslt);
                                }
              Py_XDECREF(stringarg);
              Py_XDECREF(args);
                        }
                }

                Py_XDECREF(mod);
        }

        Py_XDECREF(modname);

        Py_Finalize();

        printf("%g",answer);

        return 0;
}

The python program -->(Test.py)
def doit(x1):
    try:
        x2 = eval(x1)
    except:
        print 'Error!'
        return 0

    else:
        return x2

COMPILING-->
I used this make file to compile the above program

OPT=-I/usr/local/include/python2.4/  -DHAVE_CONFIG_H
-D_THREAD_SAFE -pthread -pipe
mm: clean mm.o
        gcc $(OPT) -Wl.-E -o mm mm.o 
/usr/local/lib/python2.4/config/libpython2.4.a  -lm
mm.o: mm.c
        gcc $(OPT) -c mm.c
clean:
        rm -f *.o;rm -f *.so;rm -f *.core

But I got the following ERRORS-->
rm -f *.o;rm -f *.so;rm -f *.core
gcc -I/usr/local/include/python2.4/  -DHAVE_CONFIG_H
-D_THREAD_SAFE -pthread -pipe -c mm.c
gcc -I/usr/local/include/python2.4/  -DHAVE_CONFIG_H
-D_THREAD_SAFE -pthread -pipe -Wl.-E -o mm mm.o 
/usr/local/lib/python2.4/config/libpython2.4.a  -lm
/usr/local/lib/python2.4/config/libpython2.4.a(posixmodule.o)(.text+0x39a4):
In function `posix_tmpnam':
./Modules/posixmodule.c:6240: warning: the use of
`tmpnam_r' is dangerous, better use `mkstemp'
/usr/local/lib/python2.4/config/libpython2.4.a(posixmodule.o)(.text+0x3906):
In function `posix_tempnam':
./Modules/posixmodule.c:6195: warning: the use of
`tempnam' is dangerous, better use `mkstemp'
/usr/local/lib/python2.4/config/libpython2.4.a(dynload_shlib.o)(.text+0x15e):
In function `_PyImport_GetDynLoadFunc':
Python/dynload_shlib.c:130: undefined reference to
`dlopen'
/usr/local/lib/python2.4/config/libpython2.4.a(dynload_shlib.o)(.text+0x19f):Python/dynload_shlib.c:141:
undefined reference to `dlsym'
/usr/local/lib/python2.4/config/libpython2.4.a(dynload_shlib.o)(.text+0x1f6):Python/dynload_shlib.c:133:
undefined reference to `dlerror'
/usr/local/lib/python2.4/config/libpython2.4.a(posixmodule.o)(.text+0x1b49):
In function `posix_openpty':
: undefined reference to `openpty'
/usr/local/lib/python2.4/config/libpython2.4.a(posixmodule.o)(.text+0x1b93):
In function `posix_forkpty':
: undefined reference to `forkpty'
collect2: ld returned 1 exit status
make: *** [mm] Error 1

HOW TO FIX THESE and get a executable so that I can
directly run it?

Thanks and Regards,
Shadab.

Send instant messages to your online friends http://uk.messenger.yahoo.com 

From rikard.bosnjakovic at gmail.com  Tue Feb 13 09:00:40 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 13 Feb 2007 09:00:40 +0100
Subject: [Tutor] Accessing installed windows software from python
In-Reply-To: <5850ed90702121750v31f6f756l42ee14ecbab08087@mail.gmail.com>
References: <5850ed90702121750v31f6f756l42ee14ecbab08087@mail.gmail.com>
Message-ID: <d9e88eaf0702130000h248aa752x336d9ce0ba17c4c5@mail.gmail.com>

On 2/13/07, Jalil <jalilsan at gmail.com> wrote:

> I was wondering if its possible to go about writing a code to find out  all
> the installed program on a windows machines.  Basically everything under Add
> Remove Programs in the control panel.

There is no support for this in the standard Python-distribution.
However, Mark Hammond has developed a fullblown set of Win32-API
support in his win32-modules. You might want to take a peek there:

        http://sourceforge.net/projects/pywin32/

You might also want to join the python-win32 mailing list:

        http://mail.python.org/mailman/listinfo/python-win32


-- 
- Rikard.

From rikard.bosnjakovic at gmail.com  Tue Feb 13 09:05:09 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 13 Feb 2007 09:05:09 +0100
Subject: [Tutor] Compiling a program ::Embedding Python in C
In-Reply-To: <20070213060111.71801.qmail@web38708.mail.mud.yahoo.com>
References: <20070213060111.71801.qmail@web38708.mail.mud.yahoo.com>
Message-ID: <d9e88eaf0702130005s64868e2fw1198d11eb72d0e9b@mail.gmail.com>

On 2/13/07, Shadab Sayani <shadabsayani at yahoo.com> wrote:

[...]
> /usr/local/lib/python2.4/config/libpython2.4.a(dynload_shlib.o)(.text+0x1f6):Python/dynload_shlib.c:133:
> undefined reference to `dlerror'
[...]

You have not provided enough information for us to help you. What
system do you use?

It looks like a Unix-flavorish. Try issuing this: "nm
/usr/local/lib/python2.4/config/libpython2.4.a | grep dlerror". Most
likely you will get a line similiar to "U dlerror", which means that
function / symbol is undefined on your system.

But like I said, you need to provide more info for us.

-- 
- Rikard.

From alan.gauld at btinternet.com  Tue Feb 13 09:37:15 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Feb 2007 08:37:15 -0000
Subject: [Tutor] Accessing installed windows software from python
References: <5850ed90702121750v31f6f756l42ee14ecbab08087@mail.gmail.com>
Message-ID: <eqrtbt$uo7$1@sea.gmane.org>


"Jalil" <jalilsan at gmail.com> wrote

>I was wondering if its possible to go about writing a code to find 
>out  all
> the installed program on a windows machines.  Basically everything 
> under Add
> Remove Programs in the control panel.

I believe thats done by searching the Windows registry.
You can use the Win32 API or the WSH API to do that,
but I don't know which keys you should look under.
Try MSDN...

To access the Win32/WSH API you can use ctypes (now part of the
standard library in 2.5 I think) or Mark Hammond's winall package.

HTH,


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



From shadabsayani at yahoo.com  Tue Feb 13 09:38:00 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Tue, 13 Feb 2007 08:38:00 +0000 (GMT)
Subject: [Tutor] Compiling a program ::Embedding Python in C
In-Reply-To: <d9e88eaf0702130005s64868e2fw1198d11eb72d0e9b@mail.gmail.com>
Message-ID: <20070213083800.44045.qmail@web38704.mail.mud.yahoo.com>

Hi,
I am using FC3.
On issuing the command given by you I got the same
response.So how can I fix it?
My main line of execution is C.My intention is to use
python in C to do some operations.I have a main
function in C code.I want to compile it get its
executable and execute it to get the output which is
actually processed in python module.
Thanks,
Shadab.

--- Rikard Bosnjakovic <rikard.bosnjakovic at gmail.com>
wrote:

> On 2/13/07, Shadab Sayani <shadabsayani at yahoo.com>
> wrote:
> 
> [...]
> >
>
/usr/local/lib/python2.4/config/libpython2.4.a(dynload_shlib.o)(.text+0x1f6):Python/dynload_shlib.c:133:
> > undefined reference to `dlerror'
> [...]
> 
> You have not provided enough information for us to
> help you. What
> system do you use?
> 
> It looks like a Unix-flavorish. Try issuing this:
> "nm
> /usr/local/lib/python2.4/config/libpython2.4.a |
> grep dlerror". Most
> likely you will get a line similiar to "U dlerror",
> which means that
> function / symbol is undefined on your system.
> 
> But like I said, you need to provide more info for
> us.
> 
> -- 
> - Rikard.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


Send instant messages to your online friends http://uk.messenger.yahoo.com 

From alan.gauld at btinternet.com  Tue Feb 13 09:44:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Feb 2007 08:44:29 -0000
Subject: [Tutor] Compiling a program ::Embedding Python in C
References: <20070213060111.71801.qmail@web38708.mail.mud.yahoo.com>
Message-ID: <eqrtpf$vuu$1@sea.gmane.org>

"Shadab Sayani" <shadabsayani at yahoo.com> wrote 

I can't help with the compile issues but a couple of quick points...

> I have a C program mm.c calling python function as
> follows::
> #include "Python.h"
> #include <stdio.h>
> 
> int main(int argc, char* argv[])
> {
>        double answer = 0;
>        PyObject *modname, *mod, *mdict, *func,
> *stringarg, *args, *rslt;

Please, initialise your variables! 
The single most common cause of 'random' bugs in C code is 
uninitialised pointers. Even though you use them safely below 
it's oh so easy to make a change later that tests a pointer 
value before its been set. Much better to *always* initialise 
pointers to NULL.

Alan G.
(3 years a C maintenance team lead ;-( )




From eike.welk at gmx.net  Tue Feb 13 13:46:22 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Tue, 13 Feb 2007 13:46:22 +0100
Subject: [Tutor] telnet read_until problems
In-Reply-To: <eqqlgu$emd$1@sea.gmane.org>
References: <9f68812f0702121200k22e1b6a2q269978ad773f492c@mail.gmail.com>
	<eqqlgu$emd$1@sea.gmane.org>
Message-ID: <200702131346.22594.eike.welk@gmx.net>

Hello Allan!

On Monday 12 February 2007 22:17, Alan Gauld wrote:
> The figure 999 is interesting. Python has a recursion limit of 1000
> levels. Do you by any chance use recursion to call your function?

Is the recursion limit hard coded, or can it be changed?

Regards,
Eike.


From kent37 at tds.net  Tue Feb 13 14:10:26 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Feb 2007 08:10:26 -0500
Subject: [Tutor] Recursion limit
In-Reply-To: <200702131346.22594.eike.welk@gmx.net>
References: <9f68812f0702121200k22e1b6a2q269978ad773f492c@mail.gmail.com>	<eqqlgu$emd$1@sea.gmane.org>
	<200702131346.22594.eike.welk@gmx.net>
Message-ID: <45D1B8C2.4090507@tds.net>

Eike Welk wrote:
> Hello Allan!
> 
> On Monday 12 February 2007 22:17, Alan Gauld wrote:
>> The figure 999 is interesting. Python has a recursion limit of 1000
>> levels. Do you by any chance use recursion to call your function?
> 
> Is the recursion limit hard coded, or can it be changed?

It is settable with sys.setrecursionlimit(). I'm sure there are some 
valid reasons to change this but I would look for a different way to 
solve my problem first. From the docs:

setrecursionlimit(  	limit)
     Set the maximum depth of the Python interpreter stack to limit. 
This limit prevents infinite recursion from causing an overflow of the C 
stack and crashing Python.

     The highest possible limit is platform-dependent. A user may need 
to set the limit higher when she has a program that requires deep 
recursion and a platform that supports a higher limit. This should be 
done with care, because a too-high limit can lead to a crash.


Kent


From sanelson at gmail.com  Tue Feb 13 16:15:54 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Tue, 13 Feb 2007 15:15:54 +0000
Subject: [Tutor] Python for Sysadmins
Message-ID: <b6131fdc0702130715x678bb871s69635f5177993223@mail.gmail.com>

Hello chaps,

So further to the MapReduce question, it helped greatly, and I got the
job, so I'll now be programming Ruby for a living...

Before I leave my present job, I've been asked to put together a day's
course on Python for Sysadmins.  This is mainly to enable them to
maintain my code, and give them a flavour for what Python is, how it
works, and give them somewhere to begin going on to learn.

I'd like some suggestions for a course outline - bear in mind I'll
only have a day for the course.  The attendees are all sysadmins with
a UNIX background, and are reasonably comfortable with shell, but
nothing else.

Any ideas?

S.

From chris.arndt at web.de  Tue Feb 13 16:38:47 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Tue, 13 Feb 2007 16:38:47 +0100
Subject: [Tutor] Python for Sysadmins
In-Reply-To: <b6131fdc0702130715x678bb871s69635f5177993223@mail.gmail.com>
References: <b6131fdc0702130715x678bb871s69635f5177993223@mail.gmail.com>
Message-ID: <45D1DB87.7050705@web.de>

Steve Nelson schrieb:
> I'd like some suggestions for a course outline - bear in mind I'll
> only have a day for the course.  The attendees are all sysadmins with
> a UNIX background, and are reasonably comfortable with shell, but
> nothing else.

Must topics (apart from the basic Python stuff):

- functions in the os and os.path module
- the subprocess module
- recipe for option parsing with optparse
- recipe for basic logging with the logging module
- file globbing with glob
- walking a directory hierarchy with os.walk
- the re module
- the urllib module

Maybe:

- Python modules and packages
- distutils and easy_install (if they have to install third-party packages)

Since you only have a day this can be only very basic introductions resp. recipes.

Chris

From eike.welk at gmx.net  Tue Feb 13 17:04:15 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Tue, 13 Feb 2007 17:04:15 +0100
Subject: [Tutor] Recursion limit
In-Reply-To: <45D1B8C2.4090507@tds.net>
References: <9f68812f0702121200k22e1b6a2q269978ad773f492c@mail.gmail.com>
	<200702131346.22594.eike.welk@gmx.net> <45D1B8C2.4090507@tds.net>
Message-ID: <200702131704.16305.eike.welk@gmx.net>

Thank you!
I have a program myself that does a lot of recursion.

Regards,
Eike. 


From hmm at woolgathering.cx  Tue Feb 13 17:32:31 2007
From: hmm at woolgathering.cx (William O'Higgins Witteman)
Date: Tue, 13 Feb 2007 11:32:31 -0500
Subject: [Tutor] Python for Sysadmins
In-Reply-To: <45D1DB87.7050705@web.de>
References: <b6131fdc0702130715x678bb871s69635f5177993223@mail.gmail.com>
	<45D1DB87.7050705@web.de>
Message-ID: <20070213163231.GH632@sillyrabbi.dyndns.org>

On Tue, Feb 13, 2007 at 04:38:47PM +0100, Christopher Arndt wrote:
>Steve Nelson schrieb:
>> I'd like some suggestions for a course outline - bear in mind I'll
>> only have a day for the course.  The attendees are all sysadmins with
>> a UNIX background, and are reasonably comfortable with shell, but
>> nothing else.
>
>Must topics (apart from the basic Python stuff):
>
>- functions in the os and os.path module
>- the subprocess module
>- recipe for option parsing with optparse
>- recipe for basic logging with the logging module
>- file globbing with glob
>- walking a directory hierarchy with os.walk
>- the re module
>- the urllib module
>
>Maybe:
>
>- Python modules and packages
>- distutils and easy_install (if they have to install third-party packages)
>
>Since you only have a day this can be only very basic introductions resp. recipes.

These are good suggestions; two more are python.org and the tutor list!
If they get stuck they can fall back on the community - the strength of
a language isn't syntax or structure or ease of use, but the core
documentation and community around it.
-- 

yours,

William

From dkuhlman at rexx.com  Tue Feb 13 17:45:29 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 13 Feb 2007 08:45:29 -0800
Subject: [Tutor] Python for Sysadmins
In-Reply-To: <b6131fdc0702130715x678bb871s69635f5177993223@mail.gmail.com>
References: <b6131fdc0702130715x678bb871s69635f5177993223@mail.gmail.com>
Message-ID: <20070213164529.GA62371@cutter.rexx.com>

On Tue, Feb 13, 2007 at 03:15:54PM +0000, Steve Nelson wrote:

> I'd like some suggestions for a course outline - bear in mind I'll
> only have a day for the course.  The attendees are all sysadmins with
> a UNIX background, and are reasonably comfortable with shell, but
> nothing else.

You might want to look at the following:

    http://www.rexx.com/~dkuhlman/jython_course_01.html
    http://www.rexx.com/~dkuhlman/python_course_01.html

These are intended for a 3 to 5 day course.  So they are likely to
be too detailed for your needs.  But, you still might want to look
at the table of contents.

Also, it might be of help just to review the table of contents and
the first paragraph of each chapter of a beginner's Python book. 
Alan's book, "Learn to program using Python" or "Learning Python"
by Lutz would give you the topics you need to cover and help with
covering them, too.

Dave


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

From kent37 at tds.net  Tue Feb 13 17:46:32 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Feb 2007 11:46:32 -0500
Subject: [Tutor] Python for Sysadmins
In-Reply-To: <45D1DB87.7050705@web.de>
References: <b6131fdc0702130715x678bb871s69635f5177993223@mail.gmail.com>
	<45D1DB87.7050705@web.de>
Message-ID: <45D1EB68.5070501@tds.net>

Christopher Arndt wrote:
> Steve Nelson schrieb:
>> I'd like some suggestions for a course outline - bear in mind I'll
>> only have a day for the course.  The attendees are all sysadmins with
>> a UNIX background, and are reasonably comfortable with shell, but
>> nothing else.

You might get some ideas here:
http://www.swc.scipy.org/

Kent


From chris.lasher at gmail.com  Tue Feb 13 20:16:19 2007
From: chris.lasher at gmail.com (Chris Lasher)
Date: Tue, 13 Feb 2007 14:16:19 -0500
Subject: [Tutor] Accessing class attributes: use methods only?
Message-ID: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>

Is it general good practice to access and set class attributes via
methods only, or is it okay practice to directly interact with class
attributes? The professor in a class on Perl that I'm taking suggested
that directly accessing and setting class attributes was a bad idea.
Just wondering what the current preference in Python is.

Many thanks,
Chris

From rabidpoobear at gmail.com  Tue Feb 13 20:49:24 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 13 Feb 2007 13:49:24 -0600
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
Message-ID: <45D21644.6040301@gmail.com>

Chris Lasher wrote:
> Is it general good practice to access and set class attributes via
> methods only, or is it okay practice to directly interact with class
> attributes? The professor in a class on Perl that I'm taking suggested
> that directly accessing and setting class attributes was a bad idea.
> Just wondering what the current preference in Python is.
>   
Python goes by the premise that you won't go and muck around in the 
class if you don't know what you're doing / need to,
but if you do need to, the programming language shouldn't restrict you 
from doing so.
That's why there's no such thing as private.
Usually if the method has underlines before its name, the programmer is 
trying to tell you you shouldn't access it unless you need to.
Otherwise, I see no problem accessing data members outside of the class.
The  main problem (that I see) lies in setting the attributes:  F.E. if 
you had an array class that had an attribute called 'used' that stored 
the # of in-use items
in most cases you wouldn't want to change this value, but let the class 
handle changing it.
I hear in my CS classes that it's bad, but I think that's partially the 
C++ mindset.
I don't see anything wrong with it.
It just may not be the easiest way to do it for certain attributes.
But if you have csomeClassInstance.objidentifier = "Some New String"
I think that makes more sense than wrapping that functionality in a method.
You probably want to wait for someone else to answer, because they'll be 
able to give you more information on whether or not it's bad.
-Luke

From les.hazlett at navteq.com  Tue Feb 13 21:48:43 2007
From: les.hazlett at navteq.com (Hazlett, Les)
Date: Tue, 13 Feb 2007 14:48:43 -0600
Subject: [Tutor] Multiple Tk frames
Message-ID: <B76F47F45A9B184781E0A41F711B516CB7B593@NAEXC.ad.navteq.com>

Hi,

I have found many simple examples of using Tk with one frame.  I found
self.quit to close the open frame object.  I see that control goes to
the end of main, but I don't know how to then create and use another
frame.  

Below is a "cut-down" version of what I have tried.

Thanks for any help,

Les Hazlett

=====================

# Test using TK

from Tkinter import *

class Window1(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
     # create a quit button
        Button(self,
               text = "Quit",
               command = self.quit
               ).grid(row = 10, column = 1)

# main
root = Tk()
root.title("Portable Disk Upload")
app = Window1(root)
root.mainloop()

print '\nWanted to stop here and do it again.'

root = Tk()
root.title("Select Source Directory")
app = Window1(root)
root.mainloop



The information contained in this communication may be CONFIDENTIAL and is intended only for the use of the recipient(s) named above. If you are not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication, or any of its contents, is strictly prohibited. If you have received this communication in error, please notify the sender and delete/destroy the original message and any copy of it from your computer or paper files.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070213/7c0a4435/attachment.html 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/gif
Size: 145 bytes
Desc: Blank Bkgrd.gif
Url : http://mail.python.org/pipermail/tutor/attachments/20070213/7c0a4435/attachment-0001.gif 

From kent37 at tds.net  Tue Feb 13 22:03:03 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Feb 2007 16:03:03 -0500
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
Message-ID: <45D22787.1070503@tds.net>

Chris Lasher wrote:
> Is it general good practice to access and set class attributes via
> methods only, or is it okay practice to directly interact with class
> attributes? The professor in a class on Perl that I'm taking suggested
> that directly accessing and setting class attributes was a bad idea.
> Just wondering what the current preference in Python is.

Assuming you actually mean instance attributes, not class attributes; 
i.e. an attribute that has a value for each instance of a class, not an 
attribute that is shared by all instances...

Python practice is to use direct attribute access. If you need to do 
something special when an attribute is read or set, you can create a 
property. This allows you to define methods to be called when the 
attribute is accessed, without having to change the client code.

The use of getters and setters is popular in C++ and Java where it is 
painful to change client code from direct attribute access to indirect 
access through setters and getters. In Python there is no need for this 
as the change only affects the class itself.

Properties are a somewhat advanced feature; here is some more information:
http://www.python.org/download/releases/2.2/descrintro/#property

Kent


From bgailer at alum.rpi.edu  Tue Feb 13 22:03:17 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 13 Feb 2007 13:03:17 -0800
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
Message-ID: <45D22795.7030607@alum.rpi.edu>

Chris Lasher wrote:
> Is it general good practice to access and set class attributes via
> methods only, or is it okay practice to directly interact with class
> attributes? The professor in a class on Perl that I'm taking suggested
> that directly accessing and setting class attributes was a bad idea.
> Just wondering what the current preference in Python is.
>   
I really like the simplicity of a.b = 3. I groan when put in other 
environments where a method call is required.

And Python has the magic method __setattr__ to intercept attribute 
assignment for the times where some inspection / protection / 
side-effect action is desired.

-- 
Bob Gailer
510-978-4454


From john at fouhy.net  Tue Feb 13 22:09:44 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 14 Feb 2007 10:09:44 +1300
Subject: [Tutor] Multiple Tk frames
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CB7B593@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CB7B593@NAEXC.ad.navteq.com>
Message-ID: <5e58f2e40702131309y38799f03m7bc6025a504564f3@mail.gmail.com>

On 14/02/07, Hazlett, Les <les.hazlett at navteq.com> wrote:
> I have found many simple examples of using Tk with one frame.  I found
> self.quit to close the open frame object.  I see that control goes to the
> end of main, but I don't know how to then create and use another frame.

Hi Les,

In Tkinter parlance, a "Frame" is a container that you use to build up
a window.  Is that what you're after, or do you want to make multiple
windows?

When you call Tk(), it does two things:
 1. it creates a top level window that you can put things into
 2. it creates and initialises the Tk engine.

You only need to do (2) once, so you only need to call Tk() once.  If
you want more than one top level window, you need to use Toplevel().

eg:

from Tkinter import *

root = Tk()
root.title("Main window")
lab1 = Label(root, text="This is the main window")
lab1.pack()

otherWindow = Toplevel()
otherWindow.title("Other window")
lab2 = Label(otherWindow, text="This is the other window")
lab2.pack()

root.mainloop()

-- 
John.

From alan.gauld at freenet.co.uk  Tue Feb 13 22:12:10 2007
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 13 Feb 2007 21:12:10 -0000
Subject: [Tutor] New Tutor topic(almost)
Message-ID: <000501c74fb3$a0b7f860$6601a8c0@xp>

Hi gang,

After a very long delay I finally got some work done on 
my networking with sockets topic in my tutorial. There is 
still a section to complete but the introductory explanations 
and examples are now on the site.

http://www.freenetpages.co.uk/hp/alan.gauld/tutsocket.htm

If anyone has any feedback I'd love to hear it.

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

From alan.gauld at btinternet.com  Tue Feb 13 22:41:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Feb 2007 21:41:40 -0000
Subject: [Tutor] Accessing class attributes: use methods only?
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
Message-ID: <eqtban$ick$1@sea.gmane.org>

"Chris Lasher" <chris.lasher at gmail.com> wrote

> Is it general good practice to access and set class attributes via
> methods only, or is it okay practice to directly interact with class
> attributes?

Its generally good OOP practice to interact with object via messages.
Its also good practice NOT to access an objects attributes directly
(and that includes via get/set methods) A class should publish a
set of operations. The attributes should be there to support
those operations.

If you extract a value from a class, mess with it and write it back
again thats *very bad* OO programming, don't do it. Its so important
it even has a law named after it - the Law of Demeter...

That having been said, some objects responsibilities include
exposing some data, but usually in those cases you want a set
of data and it can be returned in a single method via a tuple.
Similarly you can modify the data via a single call.
An example might be a Location class where rather than
having access to each field of the address you simply create
an address by passing a tuple of values, read an address
by retrieving a tuple and modify an address by using the
full tuple. (This also ensures that validation of fields - like
checking the post code still matches - can be done) But
you might also have other operations such as formatting
addresses. caculating distances between addressed (cue
the recent geo thread!) etc.

If you really must expose an attribute you should ideally
make it a property rather than a normal attribute.

> The professor in a class on Perl that I'm taking suggested
> that directly accessing and setting class attributes was a bad idea.

This is true in any OOP environment and the principles of
information hiding apply to classses as much as to modules.
But the really important issue is that classes should express
an operationally focused interface not a data focusssed one.
Most of the time you shouldn't know, nor care, what the dfata
attributes of a class are. You send messages to get things
done, not to extract/insert data.

Polymorphism only works on methods, not data access.

However, one of Pythons core principles is it doesn't get in your way.
If you really must access a bit of object state directly Python lets
you and its not any more wrong than doing it by calling a
getX/setX method. get/set abuses information hiding almost as
much as direct access.


PS. If you really want to find out why access to data is bad
read Parnas' original paper on Information Hiding
(On the Criteria to Be Used in Decomposing Systems Into
Modules). Its probably on the web somewhere I'm sure.
Its from 1972, this isn't anything new... Wikipedia is also
a good source.

HTH,

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



From alan.gauld at btinternet.com  Tue Feb 13 22:49:16 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Feb 2007 21:49:16 -0000
Subject: [Tutor] Multiple Tk frames
References: <B76F47F45A9B184781E0A41F711B516CB7B593@NAEXC.ad.navteq.com>
Message-ID: <eqtbou$kok$1@sea.gmane.org>

"Hazlett, Les" <les.hazlett at navteq.com> wrote

> I have found many simple examples of using Tk with one frame.
> I found self.quit to close the open frame object.
> I see that control goes to the end of main, but I don't know
> how to then create and use another frame.

You first need to get your terminology straight. A Frame
is a container widget in Tk and as such you normally have
many, many frames - even inside a single window!

>From looking at your code below you want to close a
window then open another one. Without the user doing
anything - thats a very unusual GUI! Are you sure you
want the second window to open after you close the first?
Are you sure you don;t want the second window (a dialog
maybe?) to open as the first closes - that would be
more common. (In which case look at the TopLevel widget.

But GUI programs are event driven, they rely on a single
event loop dispatching messages(events) to the application.
You need to structure your code around that concept. Which
object will receive the messages? Which object creates
windows/dialogs etc?

Actually from your code it looks like you may be searching
for the tk file dialogs that do the usual file open, file saveas
fuinctions. If that is the case ask us again in terms of what
you are really trying to do. ;-)

HTH,

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


=====================

# Test using TK

from Tkinter import *

class Window1(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
     # create a quit button
        Button(self,
               text = "Quit",
               command = self.quit
               ).grid(row = 10, column = 1)

# main
root = Tk()
root.title("Portable Disk Upload")
app = Window1(root)
root.mainloop()

print '\nWanted to stop here and do it again.'

root = Tk()
root.title("Select Source Directory")
app = Window1(root)
root.mainloop



The information contained in this communication may be CONFIDENTIAL 
and is intended only for the use of the recipient(s) named above. If 
you are not the intended recipient, you are hereby notified that any 
dissemination, distribution, or copying of this communication, or any 
of its contents, is strictly prohibited. If you have received this 
communication in error, please notify the sender and delete/destroy 
the original message and any copy of it from your computer or paper 
files.



--------------------------------------------------------------------------------


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



From falcon3166 at hotmail.com  Wed Feb 14 00:11:20 2007
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Tue, 13 Feb 2007 16:11:20 -0700
Subject: [Tutor] Why doesn't it choose a new number each time?
Message-ID: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>


Hey all,
 
I wrote a rock, paper, scissors game and every time you play without exiting, it chooses the same number. How can I fix this problem? The relative code is below:
 
[code]
# -*- coding: cp1252 -*-from random import *
print "Welcome to Rock, Paper, or Scissors!"print "by Nathan Pinno"print "? 2007. All rights reserved."printwhile 1:    answer = int(raw_input("Would you like to play a game? 1 for yes and 2 for no. "))    if answer == 1:        compchoice = choice(range(3))        humanchoice = int(raw_input("Enter 1 for rock, 2 for paper, and 3 for scissors. "))        if compchoice == 1:            print "AI chose rock."            if humanchoice == 1:                print "You chose rock. Tie game."            elif humanchoice == 2:                print "You chose paper. You win!"            elif humanchoice == 3:                print "You chose scissors. You lost!"            else:                print "That's not an option. Choose again."        elif compchoice == 2:            print "AI chose paper."            if humanchoice == 1:                print "You chose rock. You lost!"            elif humanchoice == 2:                print "You chose paper. Tie game."            elif humanchoice == 3:                print "You chose scissors. You win!"            else:                print "That's not an option. Choose again."        else:            print "AI chose scissors."            if humanchoice == 1:                print "You chose rock. You win!"            elif humanchoice == 2:                print "You chose paper. You lost!"            elif humanchoice == 3:                print "You chose scissors. Tie game."            else:                print "That's not an option. Choose again."    elif answer == 2:        break    else:        print "That's not an option."print "Goodbye."[/code]
 
Thanks,
Nathan Pinno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070213/acd5f7f5/attachment-0001.htm 

From alan.gauld at btinternet.com  Wed Feb 14 01:07:06 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Feb 2007 00:07:06 -0000
Subject: [Tutor] Why doesn't it choose a new number each time?
References: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>
Message-ID: <eqtjrc$ohl$1@sea.gmane.org>


"Nathan Pinno" <falcon3166 at hotmail.com> wrote

> I wrote a rock, paper, scissors game and every time you play
> without exiting, it chooses the same number. How can I fix this
> problem? The relative code is below:

I can't see anything obvious, can you be more specific. Which
number does it always choose(I assume you mean the choice()
call?) or does it choose a different number to stick on each time?
And have you tried putting a debug print statement after the call
to choice, just to see what you get out?

Just some thoughts,

Alan G.


[code]
# -*- coding: cp1252 -*-from random import *
print "Welcome to Rock, Paper, or Scissors!"print "by Nathan 
Pinno"print "? 2007. All rights reserved."printwhile 1:    answer = 
int(raw_input("Would you like to play a game? 1 for yes and 2 for no. 
"))    if answer == 1:        compchoice = choice(range(3)) 
humanchoice = int(raw_input("Enter 1 for rock, 2 for paper, and 3 for 
scissors. "))        if compchoice == 1:            print "AI chose 
rock."            if humanchoice == 1:                print "You chose 
rock. Tie game."            elif humanchoice == 2: 
print "You chose paper. You win!"            elif humanchoice == 3: 
print "You chose scissors. You lost!"            else: 
print "That's not an option. Choose again."        elif compchoice == 
2:            print "AI chose paper."            if humanchoice == 1: 
print "You chose rock. You lost!"            elif humanchoice == 2: 
print "You chose paper. Tie game."            elif humanchoice == 3: 
print "You chose scissors. You win!"            else: 
print "That's not an option. Choose again."        else: 
print "AI chose scissors."            if humanchoice == 1: 
print "You chose rock. You win!"            elif humanchoice == 2: 
print "You chose paper. You lost!"            elif humanchoice == 3: 
print "You chose scissors. Tie game."            else: 
print "That's not an option. Choose again."    elif answer == 2: 
break    else:        print "That's not an option."print 
"Goodbye."[/code]

Thanks,
Nathan Pinno


--------------------------------------------------------------------------------


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



From wescpy at gmail.com  Wed Feb 14 01:12:48 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 13 Feb 2007 16:12:48 -0800
Subject: [Tutor] Why doesn't it choose a new number each time?
In-Reply-To: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>
References: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>
Message-ID: <78b3a9580702131612r272ac67dmc5033b0950dc0c2e@mail.gmail.com>

>  I wrote a rock, paper, scissors game and every time you play without
> exiting, it chooses the same number. How can I fix this problem? The
> relative code is below:
>        :
>         compchoice = choice(range(3))


hey nathan,

neat program... that's one of the homework assignments in my book!  i
love to give this exercise to my students.  while i don't have enough
time to scan your entire program to tell you what the problem is with
your solution, i *can* tell you that the line of code you have there
will let the computer only choose 0, 1, or 2, not 1, 2, or 3.  you
have to use range(1,4) for that, or do the same thing but add 1 to it,
e.g., choice()+1.

as far as how to improve your code, if you study your program
carefully, you should be able to reduce the overall number of print
statements, and then later, when you really become an expert, to
reduce the number of if statements.  in the end, you can refactor your
solution down to, say, 10 lines or less.

good luck!
-- 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 kent37 at tds.net  Wed Feb 14 05:35:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Feb 2007 23:35:47 -0500
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <45D22795.7030607@alum.rpi.edu>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
	<45D22795.7030607@alum.rpi.edu>
Message-ID: <45D291A3.4070207@tds.net>

Bob Gailer wrote:
> I really like the simplicity of a.b = 3. I groan when put in other 
> environments where a method call is required.
> 
> And Python has the magic method __setattr__ to intercept attribute 
> assignment for the times where some inspection / protection / 
> side-effect action is desired.

The modern way to do this (since Python 2.2 I think) is to use 
properties. __setattr__ has other uses (for example for delegation) but 
it is too big a hammer for changing the behaviour of a single attribute.

Kent


From cspears2002 at yahoo.com  Wed Feb 14 06:46:45 2007
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Tue, 13 Feb 2007 21:46:45 -0800 (PST)
Subject: [Tutor] critique my script: add columns in a file
Message-ID: <20070214054645.17199.qmail@web51608.mail.yahoo.com>

I created a file called table.txt.  Here is the file's
contents:

1       5       10      2       1.0
2       10      20      4       2.0     3
3       15      30      8       3       2       1
4       20      40      16      4.0

I modified a script I found in "Programming Python"
and created script called summer_v03.py that added the
columns together succesfully and outputted the results
in a list:

io at io-station-1 ./text_proc 158> ./summer_v03.py
table.txt
[10.0, 50.0, 100.0, 30.0, 10.0, 5.0, 1.0]

Here is the code:

#!/usr/bin/python
import string

def find_longest_line(fileName):
	longest_col = []
	for lines_in_file in open(fileName, 'r').readlines():
		cols_in_file = string.split(lines_in_file)
		#print cols_in_file
		numCols = len(cols_in_file)
		if numCols > len(longest_col):
			longest_col = cols_in_file
	return len(longest_col)
		

def summer(fileName):
	length_longest_col = find_longest_line(fileName)
	sums = [0] * length_longest_col
	for lines_in_file in open(fileName, 'r').readlines():
		cols = string.split(lines_in_file)
		for i in range(len(cols)):
			sums[i] = sums[i] + float(cols[i])
	return sums
			
if __name__ == '__main__':
	import sys
	print summer(sys.argv[1])

What do you think?


"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 rikard.bosnjakovic at gmail.com  Wed Feb 14 08:44:34 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 14 Feb 2007 08:44:34 +0100
Subject: [Tutor] Why doesn't it choose a new number each time?
In-Reply-To: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>
References: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>
Message-ID: <d9e88eaf0702132344p73de48d8ycf09d5849232d077@mail.gmail.com>

On 2/14/07, Nathan Pinno <falcon3166 at hotmail.com> wrote:

>  I wrote a rock, paper, scissors game and every time you play without
> exiting, it chooses the same number. How can I fix this problem? The
> relative code is below:
[...]
>         compchoice = choice(range(3))
[...]

>>> range(3)
[0, 1, 2]

You either have to change your if-case ranges from 1-3 to 0-2, or
simply add one to the "compchoice" variable.


-- 
- Rikard.

From alan.gauld at btinternet.com  Wed Feb 14 09:48:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Feb 2007 08:48:34 -0000
Subject: [Tutor] Why doesn't it choose a new number each time?
References: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>
	<d9e88eaf0702132344p73de48d8ycf09d5849232d077@mail.gmail.com>
Message-ID: <equid5$p3b$1@sea.gmane.org>


"Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote
> On 2/14/07, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
>>  I wrote a rock, paper, scissors game and every time you play 
>> without
>> exiting, it chooses the same number. How can I fix this problem? 
>> The
>> relative code is below:
> [...]
>>         compchoice = choice(range(3))
> [...]
>
>>>> range(3)
> [0, 1, 2]
>
> You either have to change your if-case ranges from 1-3 to 0-2, or
> simply add one to the "compchoice" variable.

I don't think that's a problem. The fact that the computers numbers
don't correspond with the users numbers shouldn't matter provided
the 'if' tests align with the choice result, which they do.

I've now tried running it on my PC and get:

=================
>>> Welcome to Rock, Paper, or Scissors!
by Nathan Pinno
? 2007. All rights reserved.

AI chose scissors.
You chose rock. You win!
AI chose rock.
You chose paper. You win!
AI chose scissors.
You chose scissors. Tie game.
Goodbye.
==================
Which all looks fine.

What exactly was the problem you found Nathan?

Alan G. 



From alan.gauld at btinternet.com  Wed Feb 14 10:03:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Feb 2007 09:03:49 -0000
Subject: [Tutor] critique my script: add columns in a file
References: <20070214054645.17199.qmail@web51608.mail.yahoo.com>
Message-ID: <equj9o$s0k$1@sea.gmane.org>

"Christopher Spears" <cspears2002 at yahoo.com> wrote

> I modified a script I found in "Programming Python"

I assume it was the first edition of Programming Python?

> #!/usr/bin/python
> import string
>
> def find_longest_line(fileName):
> longest_col = []
> for lines_in_file in open(fileName, 'r').readlines():

for line in open(fileName):      # no need for readlines now and 'r' 
is default

> cols_in_file = string.split(lines_in_file)

    cols = line.split()  # string module deprecated, use string 
methods

> numCols = len(cols_in_file)
> if numCols > len(longest_col):
> longest_col = cols_in_file

longest = max(longest,len(cols))

> return len(longest_col)

return longest   # save calculating length twice

> def summer(fileName):
> length_longest_col = find_longest_line(fileName)
> sums = [0] * length_longest_col
> for lines_in_file in open(fileName, 'r').readlines():

for line in open(fileName):   # as above

> cols = string.split(lines_in_file)

cols = line.split() # as above

> for i in range(len(cols)):
> sums[i] = sums[i] + float(cols[i])

sums[i] =+ float(cols[i])   # new += operator added

> return sums
>
> if __name__ == '__main__':
> import sys
> print summer(sys.argv[1])
>
> What do you think?

Apart from the use of old idioms its OK. Try it with the
changes above, it should be a lot shorter. Also to avoid
iterating over the file twice you could consider capturing
the data into a table and passing that back as well as
the longest line length. You could even return the length
of each line as the first element to avoiud finding it twice.

Just some ideas.


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



From kent37 at tds.net  Wed Feb 14 13:53:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Feb 2007 07:53:54 -0500
Subject: [Tutor] critique my script: add columns in a file
In-Reply-To: <20070214054645.17199.qmail@web51608.mail.yahoo.com>
References: <20070214054645.17199.qmail@web51608.mail.yahoo.com>
Message-ID: <45D30662.5020203@tds.net>

Christopher Spears wrote:
> I created a file called table.txt.  Here is the file's
> contents:
> 
> 1       5       10      2       1.0
> 2       10      20      4       2.0     3
> 3       15      30      8       3       2       1
> 4       20      40      16      4.0
> 
> I modified a script I found in "Programming Python"
> and created script called summer_v03.py that added the
> columns together succesfully and outputted the results
> in a list:
> 
> io at io-station-1 ./text_proc 158> ./summer_v03.py
> table.txt
> [10.0, 50.0, 100.0, 30.0, 10.0, 5.0, 1.0]
> 
> Here is the code:

It is very wordy. There is no need to read and split the file twice. I 
would just make a list of the (split) lines in the file and keep it 
around. The loops in find_longest_line can easily be replaced with list 
comprehensions.

Some of your names are a little off. lines_in_file is actually a single 
line; cols_in_file is the cols of a single line.

Reading the file into a list of split columns and finding the length of 
the longest line is as  simple as
data = [ line.split() for line in open(fileName) ]
numCols = max(len(cols) for cols in data)

Then your summing loop pretty much stands, though you might want to use 
enumerate() instead of range(len(cols)):
sums = [0] * numCols
for cols in data:
   for i, col in enumerate(cols):
     sums[i] += col

Kent
> 
> #!/usr/bin/python
> import string
> 
> def find_longest_line(fileName):
> 	longest_col = []
> 	for lines_in_file in open(fileName, 'r').readlines():
> 		cols_in_file = string.split(lines_in_file)
> 		#print cols_in_file
> 		numCols = len(cols_in_file)
> 		if numCols > len(longest_col):
> 			longest_col = cols_in_file
> 	return len(longest_col)
> 		
> 
> def summer(fileName):
> 	length_longest_col = find_longest_line(fileName)
> 	sums = [0] * length_longest_col
> 	for lines_in_file in open(fileName, 'r').readlines():
> 		cols = string.split(lines_in_file)
> 		for i in range(len(cols)):
> 			sums[i] = sums[i] + float(cols[i])
> 	return sums
> 			
> if __name__ == '__main__':
> 	import sys
> 	print summer(sys.argv[1])
> 
> What do you think?
> 
> 
> "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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From les.hazlett at navteq.com  Wed Feb 14 15:33:27 2007
From: les.hazlett at navteq.com (Hazlett, Les)
Date: Wed, 14 Feb 2007 08:33:27 -0600
Subject: [Tutor] Mulltiple TK frames
Message-ID: <B76F47F45A9B184781E0A41F711B516CB7B914@NAEXC.ad.navteq.com>

Thank you Alan and John,

No doubt the widow vs. frame terminology is simpe "once you understand
it".  But I am still confused.  John used the labels "Main Window" and
"Other Window" and Alan said you normally have many frames inside a
single window.  

Knowing that I am still confused by the window vs. frame terminology,
let me use the term "userform" to express what I want the user to will
see.

What I want is, no doubt, ordinary.  I want to display a "userform"
asking the user to enter a folder path.  When the user clicks the
"Continue" button, I want to get the directory of what is inside tthe
selected folder and show a different "userform" with check buttons for
subordinate folders.  When the user clicks the "Continue" button in the
second "userform", I want to do some (no need to explain) things to the
selected folders and then show a third "userform" with summary
information about folder/file sizes and run time.  

I would love to see a simple sample that uses multiple "userforms".

I will keep reading about Tk.  What reference would you recommend.  I
have the Wesley Chun Core Python Programming book.



The information contained in this communication may be CONFIDENTIAL and is intended only for the use of the recipient(s) named above. If you are not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication, or any of its contents, is strictly prohibited. If you have received this communication in error, please notify the sender and delete/destroy the original message and any copy of it from your computer or paper files.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070214/4868e2ee/attachment.html 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/gif
Size: 145 bytes
Desc: Blank Bkgrd.gif
Url : http://mail.python.org/pipermail/tutor/attachments/20070214/4868e2ee/attachment.gif 

From kent37 at tds.net  Wed Feb 14 15:50:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Feb 2007 09:50:52 -0500
Subject: [Tutor] Mulltiple TK frames
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CB7B914@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CB7B914@NAEXC.ad.navteq.com>
Message-ID: <45D321CC.20406@tds.net>

Hazlett, Les wrote:

> I would love to see a simple sample that uses multiple "userforms".

You might want to look at EasyGui. I don't think it will do exactly what 
you want but it has many examples of how to put up simple dialogs.
http://www.ferg.org/easygui/

Kent


From rikard.bosnjakovic at gmail.com  Wed Feb 14 17:17:57 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 14 Feb 2007 17:17:57 +0100
Subject: [Tutor] Why doesn't it choose a new number each time?
In-Reply-To: <equid5$p3b$1@sea.gmane.org>
References: <BAY123-W6C3624BC3EED9AA4EAE96C4900@phx.gbl>
	<d9e88eaf0702132344p73de48d8ycf09d5849232d077@mail.gmail.com>
	<equid5$p3b$1@sea.gmane.org>
Message-ID: <d9e88eaf0702140817s7e7ab8a0n44c8cd2e0e56d281@mail.gmail.com>

On 2/14/07, Alan Gauld <alan.gauld at btinternet.com> wrote:

> I don't think that's a problem. The fact that the computers numbers
> don't correspond with the users numbers shouldn't matter provided
> the 'if' tests align with the choice result, which they do.

Alan,

You're right, ofcourse. I approached the problem entirely
pragmatically and somehow disregarded the original problem.

Nathan, you need to provide us more details. For example, what really
happens (which you consider being a problem), and what do you want to
happen instead?


--
- Rikard.

From rikard.bosnjakovic at gmail.com  Wed Feb 14 17:20:44 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 14 Feb 2007 17:20:44 +0100
Subject: [Tutor] Replying to the tutor-list
Message-ID: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>

All texts that I reply to this list are automatically sent to the
author, or - by selecting "Reply all" in my mail client - the
tutorlist gets a CC.

Why is there no reply-to-tag in all the posts, making the list
recipient at all times?


-- 
- Rikard.

From Mike.Hansen at atmel.com  Wed Feb 14 17:46:07 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 14 Feb 2007 09:46:07 -0700
Subject: [Tutor] Replying to the tutor-list
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
Message-ID: <57B026980605A64F9B23484C5659E32E5B20EF@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Rikard Bosnjakovic
> Sent: Wednesday, February 14, 2007 9:21 AM
> To: tutor at python.org
> Subject: [Tutor] Replying to the tutor-list
> 
> All texts that I reply to this list are automatically sent to the
> author, or - by selecting "Reply all" in my mail client - the
> tutorlist gets a CC.
> 
> Why is there no reply-to-tag in all the posts, making the list
> recipient at all times?
> 
> 
> -- 
> - Rikard.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

The following tutor faq has an explanation:

http://www.python.org/infogami-faq/tutor/tutor-why-do-my-replies-go-to-t
he-person-who-sent-the-message-and-not-to-the-list/

Or 

http://tinyurl.com/uns5q

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From dkuhlman at rexx.com  Wed Feb 14 18:08:38 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 14 Feb 2007 09:08:38 -0800
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
Message-ID: <20070214170838.GA83451@cutter.rexx.com>

On Wed, Feb 14, 2007 at 05:20:44PM +0100, Rikard Bosnjakovic wrote:

> Why is there no reply-to-tag in all the posts, making the list
> recipient at all times?

Believe it or not -- The email reader that I use (mutt on a FreeBSD
machine that I telnet/ssh into) has a reply-to-list operation. 
That's what I've used to post this message.  So, you can tell me if
it is doing the right thing.

You might look for a similar feature in your email reader.

In the mutt email reader, I've actually had to do a little
configuration to tell mutt which lists I want to use this feature
on.

I just checked.  It looks like when I use the reply-to-list
operation in mutt, the only recipient is tutor at python.org.

Dave


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

From hgfernan at lsi.usp.br  Wed Feb 14 18:21:10 2007
From: hgfernan at lsi.usp.br (Hilton Garcia Fernandes)
Date: Wed, 14 Feb 2007 15:21:10 -0200
Subject: [Tutor] How to make epydoc behave like doxygen
Message-ID: <200702141521.11775.hgfernan@lsi.usp.br>

Dear all,

unfortunately, i could not make epydoc 2.1 (stable) behave like doxygen, in 
the sense that it could not make it generate function (or method) callgraphs.

The only diagrams i could make it creat e were class inheritance ones. Besides 
that, it transcribed the user-provided documentation available in the source 
code as docstrings. 

An interesting point was that it demanded the Python code to be the 
implementation of a module.

Does anyone know if the alpha version is more doxygen-like? 

All the best,
hilton 

-- 
Hilton Garcia Fernandes
Nucleo de Tecnologias sem Fio (NTSF) -- Wireless Technologies Team
Lab de Sistemas Integraveis Tecnologico (LSI) -- Integrable Systems Lab
Escola Politecnica (Poli) -- Engineering School
Univ S Paulo (USP)
Tel: (5511)3091-5676 (work)
    (5511)8131-5213 (mobile)
Av. Prof. Luciano Gualberto,158 trav.3 CEP 05508-900
S. Paulo -- SP -- Brazil
Pagina inicial: http://www.lsi.usp.br/~hgfernan

From dkuhlman at rexx.com  Wed Feb 14 18:27:45 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 14 Feb 2007 09:27:45 -0800
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <45D291A3.4070207@tds.net>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
	<45D22795.7030607@alum.rpi.edu> <45D291A3.4070207@tds.net>
Message-ID: <20070214172745.GB83451@cutter.rexx.com>

On Tue, Feb 13, 2007 at 11:35:47PM -0500, Kent Johnson wrote:
> Bob Gailer wrote:
> > I really like the simplicity of a.b = 3. I groan when put in other 
> > environments where a method call is required.
> > 
> > And Python has the magic method __setattr__ to intercept attribute 
> > assignment for the times where some inspection / protection / 
> > side-effect action is desired.
> 
> The modern way to do this (since Python 2.2 I think) is to use 
> properties. __setattr__ has other uses (for example for delegation) but 
> it is too big a hammer for changing the behaviour of a single attribute.

NTSAAB (Not to start an argument but) ...

Some of us old school types feel that properties are non-Pythonic. 
They are a way to write code that does something that it does not
look like that code is doing.  It hides your intend.  So, it is not
explicit.

    "Explicit is better than implicit."
                   - Tim Peters
                     (see http://www.python.org/dev/peps/pep-0020/)

In other words, properties are a way of writing code that appears
harmless, for example:

    temp = weather.temperature

and:

    weather.temperature = temp

but making it do arbitrary, sneaky, gratuitous, and egregious things.
See the documentation on the *property* function at
http://www.python.org/dev/peps/pep-0020/.

However, some of you are probably saying to yourselves: "Well, of
course (we're sneaky; we're devious; ...).  I mean we are
programmers, after all."

OK. OK. Maybe I had too much coffee this morning.

Dave

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

From kalzimin at yahoo.fr  Wed Feb 14 18:27:40 2007
From: kalzimin at yahoo.fr (Konan Zimin Albert-Eric)
Date: Wed, 14 Feb 2007 18:27:40 +0100 (CET)
Subject: [Tutor] information
Message-ID: <20070214172740.73693.qmail@web27705.mail.ukl.yahoo.com>

Hi,i just subscribed to the python mailist. i know nothing about programming. i downloaded the python software but i need help to know what i'm able to do with it, to understand programming in general, and python in particular. So, i will deadly be waiting for an answer.
   
   
                                                                                        Thanks

 		
---------------------------------
 Nouveau : t?l?phonez moins cher avec Yahoo! Messenger ! D?couvez les tarifs exceptionnels pour appeler la France et l'international.T?l?chargez la version beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070214/21edcb8e/attachment.html 

From monashee88 at shaw.ca  Wed Feb 14 18:54:17 2007
From: monashee88 at shaw.ca (J or M Montgomery)
Date: Wed, 14 Feb 2007 09:54:17 -0800
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <20070214170838.GA83451@cutter.rexx.com>
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
	<20070214170838.GA83451@cutter.rexx.com>
Message-ID: <20070214095417.70981163.monashee88@shaw.ca>

On Wed, 14 Feb 2007 09:08:38 -0800
Dave Kuhlman <dkuhlman at rexx.com> wrote:

> On Wed, Feb 14, 2007 at 05:20:44PM +0100, Rikard Bosnjakovic wrote:
> 
> > Why is there no reply-to-tag in all the posts, making the list
> > recipient at all times?
>
I use Sylpheed 2.2.7 in a Linux box. There are 'Reply' and 'Reply all' options. when I send a message using 'Reply" it goes only to the Tutor List. Using the 'Reply all" choice it goes to the prior poster with a copy to the list.

John Montgomery

From kent37 at tds.net  Wed Feb 14 19:01:14 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Feb 2007 13:01:14 -0500
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <20070214172745.GB83451@cutter.rexx.com>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>	<45D22795.7030607@alum.rpi.edu>
	<45D291A3.4070207@tds.net> <20070214172745.GB83451@cutter.rexx.com>
Message-ID: <45D34E6A.3030707@tds.net>

Dave Kuhlman wrote:

> Some of us old school types feel that properties are non-Pythonic. 
> They are a way to write code that does something that it does not
> look like that code is doing.  It hides your intend.  So, it is not
> explicit.
> 
>     "Explicit is better than implicit."
>                    - Tim Peters
>                      (see http://www.python.org/dev/peps/pep-0020/)
> 
> In other words, properties are a way of writing code that appears
> harmless, for example:
> 
>     temp = weather.temperature
> 
> and:
> 
>     weather.temperature = temp
> 
> but making it do arbitrary, sneaky, gratuitous, and egregious things.

And this is different how from what is available without properties? 
__setattr__ and __getattr__ hooks have been available at least since 
Python 1.4. New-style classes add __getattribute__. All of these exist 
so you can make attribute access do useful things, or if you want, 
arbitrary, sneaky, gratuitous, and egregious things.

Functions *are* descriptors (the underlying mechanism behind properties) 
since Python 2.2. The magic that makes bound and unbound methods is in 
the __get__() method of the function. When you invoke 
weather.getTemperature() you are essentially invoking a property to get 
the getTemperature() method. Which is pretty sneaky ;-)

Of course you can also change the meaning of a + b, c[1], etc if you like.

Because it is highly dynamic and exposes much of its internal 
mechanisms, Python gives the programmer great latitude to do stupid 
things in a wide variety of ways. This is generally considered a feature.

Kent


From richard.caicedo at navy.mil  Wed Feb 14 17:24:32 2007
From: richard.caicedo at navy.mil (Caicedo, Richard IT2 NSWC)
Date: Wed, 14 Feb 2007 11:24:32 -0500
Subject: [Tutor] question
Message-ID: <10E78A1830778548A5DA8D112686872C0999E748@NAEALKHREX05VA.nadsusea.nads.navy.mil>

I am trying to get the $ python promt I can't seem to get it.  I can get
the python shell but when I press enter I don't get the $ python? 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070214/e14d82df/attachment.html 

From kent37 at tds.net  Wed Feb 14 19:08:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Feb 2007 13:08:52 -0500
Subject: [Tutor] How to make epydoc behave like doxygen
In-Reply-To: <200702141521.11775.hgfernan@lsi.usp.br>
References: <200702141521.11775.hgfernan@lsi.usp.br>
Message-ID: <45D35034.8010404@tds.net>

Hilton Garcia Fernandes wrote:
> Dear all,
> 
> unfortunately, i could not make epydoc 2.1 (stable) behave like doxygen, in 
> the sense that it could not make it generate function (or method) callgraphs.

I don't know about epydoc but you might be interested in pycallgraph:
http://pycallgraph.slowchop.com/

Perhaps you could extend epydoc to include callgraphs with this module.

Kent


From kent37 at tds.net  Wed Feb 14 19:10:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Feb 2007 13:10:04 -0500
Subject: [Tutor] information
In-Reply-To: <20070214172740.73693.qmail@web27705.mail.ukl.yahoo.com>
References: <20070214172740.73693.qmail@web27705.mail.ukl.yahoo.com>
Message-ID: <45D3507C.3040505@tds.net>

Konan Zimin Albert-Eric wrote:
> Hi,i just subscribed to the python mailist. i know nothing about 
> programming. i downloaded the python software but i need help to know 
> what i'm able to do with it, to understand programming in general, and 
> python in particular. So, i will deadly be waiting for an answer.

Try reading one of the tutorials listed here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Kent


From rabidpoobear at gmail.com  Wed Feb 14 19:14:01 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 14 Feb 2007 12:14:01 -0600
Subject: [Tutor] question
In-Reply-To: <eign0r$aiv$1@sea.gmane.org>
References: <454BD879.7030209@nc.rr.com> <eign0r$aiv$1@sea.gmane.org>
Message-ID: <45D35169.4070907@gmail.com>

Alan Gauld wrote:
> "Doug Potter" <dpotter at nc.rr.com> wrote
>   
>> I don't get  the output I would expect from the following.
>>     
>
>   
>>>>> a = open('arp.txt')
>>>>> file = a.read()
>>>>> file = file.split('\n')
>>>>>           
>
> Easier to do
>
> file = open('arp.txt').readlines()
>
> But file is a bad name since its an alias for open...
>
>   
>>>>> b = open('arplist.txt','w')
>>>>>           
>
> Not sure why you do this
>
>   
>>>>> clean1 = []
>>>>>
>>>>>           
>
> clean is an empty list
>
>   
>>>>> for i in file:
>>>>>           
>> ...         clean1 = i[26:40]
>>     
>
> clean is now overwritten by a string until you reach the 
> end of the file upon which clean1 will be an empty string
>
>   
>>>>> clean1
>>>>>           
>> ''
>>     
>
> Which it is...
>
> I think you may have meant to use the append method
>
> for i in file:
>     clean1.append(i[26:40])
>
> And since you can iterate over a file the whole thing shrinks to:
>
> clean1 = []
> for i in open('arp.txt'):
>     clean1.append(i[26:40])
> print clean1
>
> Or even more succinctly:
>
> clean1 = [i[26:40] for i in open('arp.txt')]
>   
Would this file stay open until the scope changes or is it immediately 
garbage collected, or does something else happen?
Is it unnecessary to use the close methods of files if there are no 
references to the object anymore?
If you had a variable assigned to an open file, and then assigned it to 
something else,
the file would be automatically closed?
Are there any caveats here or is this as safe as closing the file in a 
separate statement?
I've always assumed that you had to explicitly close files.

If you did
file('something.out', 'w').writelines(['testitem1\n','testitem2\n'])
the file would be closed immediately after this was done executing, right?
is there a special func like __init__ that is called when files need to 
be deleted? perhaps __del__?

Feel free to refer me to a tutorial/reference that explains python 
garbage collecting or something.
I would google it myself but I have a huge gigantic test tomorrow.
If no one feels like answering I'll look into it this weekend.
Thanks.


From rabidpoobear at gmail.com  Wed Feb 14 19:15:30 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 14 Feb 2007 12:15:30 -0600
Subject: [Tutor] question
In-Reply-To: <10E78A1830778548A5DA8D112686872C0999E748@NAEALKHREX05VA.nadsusea.nads.navy.mil>
References: <10E78A1830778548A5DA8D112686872C0999E748@NAEALKHREX05VA.nadsusea.nads.navy.mil>
Message-ID: <45D351C2.2020905@gmail.com>

Caicedo, Richard IT2 NSWC wrote:
>
> I am trying to get the $ python promt I can't seem to get it.  I can 
> get the python shell but when I press enter I don't get the $ python?
>
I don't understand what you're asking.
What is the $ prompt?
If you have a python shell you mean you have a python interpreter you 
can type statements into, right?
the default prompt for the interpreter is >>>.
HTH,
-Luke
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From carroll at tjc.com  Wed Feb 14 20:10:58 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 14 Feb 2007 11:10:58 -0800 (PST)
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <20070214172745.GB83451@cutter.rexx.com>
Message-ID: <Pine.LNX.4.44.0702141109030.891-100000@violet.rahul.net>

On Wed, 14 Feb 2007, Dave Kuhlman wrote:

> On Tue, Feb 13, 2007 at 11:35:47PM -0500, Kent Johnson wrote:
> > Bob Gailer wrote:
> > > I really like the simplicity of a.b = 3. I groan when put in other 
> > > environments where a method call is required.
> > > 
> > > And Python has the magic method __setattr__ to intercept attribute 
> > > assignment for the times where some inspection / protection / 
> > > side-effect action is desired.
> > 
> > The modern way to do this (since Python 2.2 I think) is to use 
> > properties. __setattr__ has other uses (for example for delegation) but 
> > it is too big a hammer for changing the behaviour of a single attribute.
> 
> Some of us old school types feel that properties are non-Pythonic. 
> They are a way to write code that does something that it does not
> look like that code is doing.  It hides your intend.  So, it is not
> explicit.

Using __setattr__ is at least as sneaky, though.

If the sneakiness bothers you, use a setter/getter method and lose that 
simplicity Bob refers to.


From alan.gauld at btinternet.com  Wed Feb 14 20:37:48 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Feb 2007 19:37:48 -0000
Subject: [Tutor] Mulltiple TK frames
References: <B76F47F45A9B184781E0A41F711B516CB7B914@NAEXC.ad.navteq.com>
Message-ID: <eqvoef$s30$1@sea.gmane.org>

"Hazlett, Les" <les.hazlett at navteq.com> wrote

> No doubt the widow vs. frame terminology is simpe

A Window is a GUI concept, it is the thing with the
iconify/delete buttons and title bar. A Frame is literally
a container for other widgets. Its conventional to create
your Windows with a Frame as the top widget that
contains all others.

For a simple example look at the Grammer checkerr
GUI in my tutorial Case Study. It has 3 frames in a
single window.

> Knowing that I am still confused by the window vs.
> frame terminology, let me use the term "userform"

Form is common terminology in Visual Basic and
Delphi so thats not a bad term to use for a window
within an application. It encompasses both application
level windows and dialog boxes etc.

> What I want is, no doubt, ordinary.  I want to display
> a "userform" asking the user to enter a folder path.

OK, That would normally be done using the standard
folder dialog. It uses the usual OS Windows style dialog
with a tree widget and returns the folder name the user
selects.

Look here for more on the common dialogs:

http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/TkIntro/introduction/intro08.htm

I'm amazed nobody has documented these in the standard library
yet. They seem to be something of a secret in the Tkinter community!
They andle the normal File-Open, File-SaveAs, Choose Folder type
tasks needed in most GUI apps.

> "Continue" button, I want to get the directory of what is inside
> tthe selected folder and show a different "userform" with check
> buttons for subordinate folders.

Couldn't you use the normal Ctrl-Click/Shift click methods of
selecting multiple folders using the standard dialogs? They can
return a list of names if you ask them to...

> second "userform", I want to do some (no need to explain) things to 
> the
> selected folders and then show a third "userform" with summary
> information about folder/file sizes and run time.

Can I suggest a different scheme?

One Form on startup, with a button, or menu option (or both) that
opens a standard chooser dialog which returns a list of folders.
That same form also has a display widget (Text maybe?) that
gets filled with the result of your processing.

This is the conventional style of GUI application and should
seem normal to your users.

> I would love to see a simple sample that uses multiple
> "userforms".

Try the IDLE editor. It has several popup dialogs etc.
It is written in Tkinter.

> I will keep reading about Tk.  What reference would
> you recommend.  I have the Wesley Chun Core Python
> Programming book.

The best references are:

Fred Lundh's tutorial and reference (but doesn't cover standard 
dialogs!)
- linked from the Tkinter section on the Python web site.
The link I posted above
Grayson's book "Python & Tkinter Programming"

For generic info about building GUIs you could skim my GUI topic too,
its very thin but does cover the basics.

HTH,

-- 
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 Feb 14 20:54:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Feb 2007 19:54:00 -0000
Subject: [Tutor] Mulltiple TK frames
References: <B76F47F45A9B184781E0A41F711B516CB7B914@NAEXC.ad.navteq.com>
Message-ID: <eqvpcr$22o$1@sea.gmane.org>

Here is another reference to the standard dialogs:

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

And to correct my previous comment, the link I posted was 
by Fred Lundh and opening the tkFileDioalog moduler we 
discover that he was in fact the author of the code! 
So he does document these but not in his standard 
Tkinter tutorial and not in the standard module documentation 
either......

Alan G.


From alan.gauld at btinternet.com  Wed Feb 14 20:59:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Feb 2007 19:59:14 -0000
Subject: [Tutor] Replying to the tutor-list
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
Message-ID: <eqvpml$3v8$1@sea.gmane.org>

"Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote 

> All texts that I reply to this list are automatically sent to the
> author, or - by selecting "Reply all" in my mail client - the
> tutorlist gets a CC.

Yep, that makes sense. It's how mail tools work in a sane world.
You Reply and it goes to the sender.
You ReplyAll and it goes to everyone who received the message, 
including the list.

Normal email behaviour.

> Why is there no reply-to-tag in all the posts, making the list
> recipient at all times?

Because hitting Reply and sending to a list would only be 
consistent if the list was the originator of the message.
Some mailing lists do implement this bizarre and 
non-standard email behaviour but thankfully the Python 
community doesn't! This behaviour has been standard 
in email tools for over 25 years, let's not try to change 
it now!

IMHO of course :-)

Alan G.


From kent37 at tds.net  Wed Feb 14 21:12:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Feb 2007 15:12:27 -0500
Subject: [Tutor] Mulltiple TK frames
In-Reply-To: <eqvpcr$22o$1@sea.gmane.org>
References: <B76F47F45A9B184781E0A41F711B516CB7B914@NAEXC.ad.navteq.com>
	<eqvpcr$22o$1@sea.gmane.org>
Message-ID: <45D36D2B.2080207@tds.net>

Alan Gauld wrote:
> Here is another reference to the standard dialogs:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438123
> 
> And to correct my previous comment, the link I posted was 
> by Fred Lundh and opening the tkFileDioalog moduler we 
> discover that he was in fact the author of the code! 
> So he does document these but not in his standard 
> Tkinter tutorial and not in the standard module documentation 
> either......

It is in Fredrik Lundh's Introduction to Tkinter:
http://www.pythonware.com/library/tkinter/introduction/standard-dialogs.htm

This page and the following ones seem to be the same material as your 
original link.

Kent


From carroll at tjc.com  Wed Feb 14 21:36:02 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 14 Feb 2007 12:36:02 -0800 (PST)
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0702141232460.891-100000@violet.rahul.net>

On Wed, 14 Feb 2007, Rikard Bosnjakovic wrote:

> All texts that I reply to this list are automatically sent to the
> author, or - by selecting "Reply all" in my mail client - the
> tutorlist gets a CC.
> 
> Why is there no reply-to-tag in all the posts, making the list
> recipient at all times?

I also prefer that, but it's a matter of taste, and this lists tastes 
don't run that way.

I use procmail to add a Reply-To: header, and then dump the email into my 
separate Python in-box:

# Python tutor list
:0:
* ^Sender.*tutor.*@python.org
{
        :0hf
        | $FORMAIL -A "Reply-To: tutor at python.org"

        :0:
        inbox.python

}


(I've got a FORMAIL=/usr/bin/formail earlier in my .procmailrc)


From kubota2550 at gmail.com  Wed Feb 14 22:05:38 2007
From: kubota2550 at gmail.com (kubota2550 at gmail.com)
Date: Wed, 14 Feb 2007 16:05:38 -0500
Subject: [Tutor] User Input List and Sort
Message-ID: <5900d730702141305x43096e21w427e8c2bd9c8c882@mail.gmail.com>

Every example of a list that I've seen involves working with, sorting, etc
pre-populated list.  How can I create a list where the user inputs a string
of numbers and then sorts it?

I've tried:

print "Input list separated by commas"
lst=[raw_input()]
print lst
print len(lst)
lst.sort()
print lst

It appears to accept the input and will print the list but the length of the
list is wrong and it doesn't sort, leading me to believe that it is seeing
the input as 1 large input instead of separate numbers.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070214/830ca889/attachment.html 

From rikard.bosnjakovic at gmail.com  Wed Feb 14 22:23:17 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 14 Feb 2007 22:23:17 +0100
Subject: [Tutor] User Input List and Sort
In-Reply-To: <5900d730702141305x43096e21w427e8c2bd9c8c882@mail.gmail.com>
References: <5900d730702141305x43096e21w427e8c2bd9c8c882@mail.gmail.com>
Message-ID: <d9e88eaf0702141323g1dfd66b9j48d98bb58f1e4b85@mail.gmail.com>

On 2/14/07, kubota2550 at gmail.com <kubota2550 at gmail.com> wrote:

> Every example of a list that I've seen involves working with, sorting, etc
> pre-populated list.  How can I create a list where the user inputs a string
> of numbers and then sorts it?

The code of yours gets a commaseparated _string_, which you are
putting into a list. The list contains one element only; the string
you entered.

What you want to do is this:

print "Input list separated by commas"
foo = raw_input()
lst = foo.split(",")
print lst
print len(lst)
lst.sort()
print lst

> leading me to believe that it is seeing
> the input as 1 large input instead of separate numbers.

Correct.

raw_input() is not smart enough to split the elements for you, so you
need to do the dirty work. The string-method "split" does this. Type
help("".split) for more info.


-- 
- Rikard.

From alan.gauld at btinternet.com  Wed Feb 14 22:09:57 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Wed, 14 Feb 2007 21:09:57 +0000 (GMT)
Subject: [Tutor] Mulltiple TK frames
Message-ID: <20070214210957.20533.qmail@web86107.mail.ird.yahoo.com>

> > So he does document these but not in his standard 
> > Tkinter tutorial and not in the standard module documentation 
>
> It is in Fredrik Lundh's Introduction to Tkinter:
> http://www.pythonware.com/library/tkinter/introduction/standard-dialogs.htm

I thought it should be, but couldn't see them. Thanks Kent.
However the page only mentions a couple of the convenience 
functions there are more if you check the module itself.

Thanks again,

Alan G.





		
___________________________________________________________ 
What kind of emailer are you? Find out today - get a free analysis of your email personality. Take the quiz at the Yahoo! Mail Championship. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From allison.william at comcast.net  Thu Feb 15 04:12:57 2007
From: allison.william at comcast.net (William Allison)
Date: Wed, 14 Feb 2007 22:12:57 -0500
Subject: [Tutor] question
In-Reply-To: <10E78A1830778548A5DA8D112686872C0999E748@NAEALKHREX05VA.nadsusea.nads.navy.mil>
References: <10E78A1830778548A5DA8D112686872C0999E748@NAEALKHREX05VA.nadsusea.nads.navy.mil>
Message-ID: <45D3CFB9.2020903@comcast.net>

Caicedo, Richard IT2 NSWC wrote:
>
> I am trying to get the $ python promt I can't seem to get it.  I can 
> get the python shell but when I press enter I don't get the $ python?
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   
The $ is probably referring to the BASH prompt at which you would type 
the command
python to bring up the interactive interpreter.
Will

From falcon3166 at hotmail.com  Thu Feb 15 09:42:06 2007
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Thu, 15 Feb 2007 01:42:06 -0700
Subject: [Tutor] [Tutor} Why doesn't it choose a new number each time?
Message-ID: <BAY123-W9CB5490DC6D1445A6EF6FC4960@phx.gbl>


Hey all,
 
I edited my code, and it seems to choose a new number each time. Maybe I didn't run my test long enough the first time?
 
I should have spotted the problem of
 
choice(range(3))
 
a mile away. I edited that bit, and now I think it's running right. (25 rounds of Rock, Paper, Scissors should be good enough testing, right? LOL) The new code is
 
choice(range(1,4))and that was a suggestion. (Thanks!) But can anyone explain why I can shorten the code? I looked at it a long while yesterday, and came up with nothing. The only thing I decided was to try to get it to the GUI stage.
 
Thanks,
Nathan
> Date: Wed, 14 Feb 2007 17:17:57 +0100> From: "Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com>> Subject: Re: [Tutor] Why doesn't it choose a new number each time?> To: tutor at python.org> Message-ID:> <d9e88eaf0702140817s7e7ab8a0n44c8cd2e0e56d281 at mail.gmail.com>> Content-Type: text/plain; charset=ISO-8859-1; format=flowed> > On 2/14/07, Alan Gauld <alan.gauld at btinternet.com> wrote:> > > I don't think that's a problem. The fact that the computers numbers> > don't correspond with the users numbers shouldn't matter provided> > the 'if' tests align with the choice result, which they do.> > Alan,> > You're right, ofcourse. I approached the problem entirely> pragmatically and somehow disregarded the original problem.> > Nathan, you need to provide us more details. For example, what really> happens (which you consider being a problem), and what do you want to> happen instead?> > > --> - Rikard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070215/6a6169d7/attachment.html 

From alan.gauld at btinternet.com  Thu Feb 15 10:05:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Feb 2007 09:05:27 -0000
Subject: [Tutor] [Tutor} Why doesn't it choose a new number each time?
References: <BAY123-W9CB5490DC6D1445A6EF6FC4960@phx.gbl>
Message-ID: <er17or$8ca$1@sea.gmane.org>

"Nathan Pinno" <falcon3166 at hotmail.com> wrote

> But can anyone explain why I can shorten the code?

There are a few things you could do but one very powerful
trick is to use a table driven approach. Thus:

rps = {0:'rock',1:'paper',2:'scissors'}  # use zero to match list 
index

results = [
                # zeroth item AI chose rock
                 ['You chose Rock : Tied Game',
                  'You chose Paper: You win!',
                  'You chose scissors, AI Wins!'],
                # index one is AI chose paper
                 ['You chose Rock, AI Wins!'
                  ...etc....],
                # index 3 AI chose scissors
                 ['You chose Rock, You win!', ....etc]
]

Now all your if/else logic becomes:

tool = choice(range3))
user = int(raw_input(....)
print 'AI chose ', rps[tool], results[tool][user]

And you can reduce that further by using multiple tables
of strings and the results table simply becomes a collection
of indexes into those tables. This is starting to get into a
database topic called normal forms which is probably a
tad advanced for this case!

HTH,

Alan G.



From rikard.bosnjakovic at gmail.com  Thu Feb 15 10:06:40 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 15 Feb 2007 10:06:40 +0100
Subject: [Tutor] [Tutor} Why doesn't it choose a new number each time?
In-Reply-To: <BAY123-W9CB5490DC6D1445A6EF6FC4960@phx.gbl>
References: <BAY123-W9CB5490DC6D1445A6EF6FC4960@phx.gbl>
Message-ID: <d9e88eaf0702150106h146f0e80u51220392524b0037@mail.gmail.com>

On 2/15/07, Nathan Pinno <falcon3166 at hotmail.com> wrote:

> and that was a suggestion. (Thanks!) But can anyone explain why I can
> shorten the code? I looked at it a long while yesterday, and came up with
> nothing. The only thing I decided was to try to get it to the GUI stage.

If you take a look at your if-cases, you see that a lot of strings in
there are the same. The code is therefore redundant, and this is what
can be trimmed down.

Consider this code:

if var1 = 1 and var2 = 0:
  print "Var1 is 1, var2 is 0"
if var1 = 0 and var2 = 0:
  print "Var1 is 0, var2 is 0"
if var1 = 1 and var2 = 1:
  print "Var1 is 1, var2 is 1"
if var1 = 0 and var2 = 1:
  print "Var1 is 0, var2 is 1"

This scope is redundant in a lot of ways and can be trimmed down to
one if and one print:

if (var1 in [0,1]) and (var2 in [0,1]):
  print "Var1 is %d, var2 is %d" % (var1, var2)

Your code is similiar to the above. It takes time to learn how to trim
down redundant code. Vast knowledge of a language itself is not
required, but a pretty solid knowledge about the basics is probably
required. If you are entirely new to programming, it might be
cumbersome though.

Give it a try, and don't hesitate to ask again.

-- 
- Rikard.

From rabidpoobear at gmail.com  Thu Feb 15 11:30:57 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 15 Feb 2007 04:30:57 -0600
Subject: [Tutor] [Tutor} Why doesn't it choose a new number each time?
In-Reply-To: <d9e88eaf0702150106h146f0e80u51220392524b0037@mail.gmail.com>
References: <BAY123-W9CB5490DC6D1445A6EF6FC4960@phx.gbl>
	<d9e88eaf0702150106h146f0e80u51220392524b0037@mail.gmail.com>
Message-ID: <45D43661.5000604@gmail.com>

Rikard Bosnjakovic wrote:
> On 2/15/07, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
>   
>> and that was a suggestion. (Thanks!) But can anyone explain why I can
>> shorten the code? I looked at it a long while yesterday, and came up with
>> nothing. The only thing I decided was to try to get it to the GUI stage.
>>     
>
> If you take a look at your if-cases, you see that a lot of strings in
> there are the same. The code is therefore redundant, and this is what
> can be trimmed down.
>
> Consider this code:
>
> if var1 = 1 and var2 = 0:
>   print "Var1 is 1, var2 is 0"
> if var1 = 0 and var2 = 0:
>   print "Var1 is 0, var2 is 0"
> if var1 = 1 and var2 = 1:
>   print "Var1 is 1, var2 is 1"
> if var1 = 0 and var2 = 1:
>   print "Var1 is 0, var2 is 1"
>   
I think Rikard meant '==' in the above cases.
Not meaning to nitpick, just don't want someone copying and pasting this 
and ending up with weird results.
> This scope is redundant in a lot of ways and can be trimmed down to
> one if and one print:
>
> if (var1 in [0,1]) and (var2 in [0,1]):
>   print "Var1 is %d, var2 is %d" % (var1, var2)
>
> Your code is similiar to the above. It takes time to learn how to trim
> down redundant code. Vast knowledge of a language itself is not
> required, but a pretty solid knowledge about the basics is probably
> required. If you are entirely new to programming, it might be
> cumbersome though.
>
> Give it a try, and don't hesitate to ask again.
>
>   


From geoframer at gmail.com  Thu Feb 15 11:43:55 2007
From: geoframer at gmail.com (Geoframer)
Date: Thu, 15 Feb 2007 11:43:55 +0100
Subject: [Tutor] [Tutor} Why doesn't it choose a new number each time?
In-Reply-To: <d9e88eaf0702150106h146f0e80u51220392524b0037@mail.gmail.com>
References: <BAY123-W9CB5490DC6D1445A6EF6FC4960@phx.gbl>
	<d9e88eaf0702150106h146f0e80u51220392524b0037@mail.gmail.com>
Message-ID: <5d8e35a70702150243maa94c3m541758cbf52b026a@mail.gmail.com>

The one thing people told me when i started learning python was that python
has this lovely structure called dictionaries. Your particular problem is
very easy to solve using dictionaries in about 12 lines (i coded it myself
just to see ;-)).

For instance you could define the various values as a dictionary :
values = {1:'rock', 2:'paper', 3:'scissors'}

and the outcome of possible combinations (cchoice, hchoice) as :
combinations = {(1,1):'Tie game!', (1,2):'You win!', (1,3):'You lost!',
(2,1):'You lost!', (2,2):'Tie game!', (2,3):'You win!',
                           (3,1):'You win!', (3,2):'You lost!', (3,3):'Tie
game!'}

That way it's very easy to take a random value for computer , get input for
human player and print the result in a single print like so :
print "AI chose %s, you chose %s. %s", %(values.get(cchoice),values.get
(hchoice),combinations.get((cchoice,hchoice)))

Probably this is not unlike Alan suggest, but i got confused when i read
about tables. Unless he means dictionaries instead.

HTH - Geoframer

On 2/15/07, Rikard Bosnjakovic <rikard.bosnjakovic at gmail.com> wrote:
>
> On 2/15/07, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
> > and that was a suggestion. (Thanks!) But can anyone explain why I can
> > shorten the code? I looked at it a long while yesterday, and came up
> with
> > nothing. The only thing I decided was to try to get it to the GUI stage.
>
> If you take a look at your if-cases, you see that a lot of strings in
> there are the same. The code is therefore redundant, and this is what
> can be trimmed down.
>
> Consider this code:
>
> if var1 = 1 and var2 = 0:
>   print "Var1 is 1, var2 is 0"
> if var1 = 0 and var2 = 0:
>   print "Var1 is 0, var2 is 0"
> if var1 = 1 and var2 = 1:
>   print "Var1 is 1, var2 is 1"
> if var1 = 0 and var2 = 1:
>   print "Var1 is 0, var2 is 1"
>
> This scope is redundant in a lot of ways and can be trimmed down to
> one if and one print:
>
> if (var1 in [0,1]) and (var2 in [0,1]):
>   print "Var1 is %d, var2 is %d" % (var1, var2)
>
> Your code is similiar to the above. It takes time to learn how to trim
> down redundant code. Vast knowledge of a language itself is not
> required, but a pretty solid knowledge about the basics is probably
> required. If you are entirely new to programming, it might be
> cumbersome though.
>
> Give it a try, and don't hesitate to ask again.
>
> --
> - Rikard.
> _______________________________________________
> 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/20070215/ea249ca9/attachment.html 

From andreengels at gmail.com  Thu Feb 15 13:49:42 2007
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 15 Feb 2007 13:49:42 +0100
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <eqvpml$3v8$1@sea.gmane.org>
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
	<eqvpml$3v8$1@sea.gmane.org>
Message-ID: <6faf39c90702150449j7145bc73k504a26b6c34662c1@mail.gmail.com>

2007/2/14, Alan Gauld <alan.gauld at btinternet.com>:

> Because hitting Reply and sending to a list would only be
> consistent if the list was the originator of the message.
> Some mailing lists do implement this bizarre and
> non-standard email behaviour but thankfully the Python
> community doesn't! This behaviour has been standard
> in email tools for over 25 years, let's not try to change
> it now!
>

It's getting to be the majority of mailing lists that do it the other way,
and I find it quite irritating that this list does not - I have had several
times that I sent a mail, and after sending it, sometimes long after sending
it, I realize I sent it to the sender instead of the list, so I send a
second message after it. Who knows how often I have failed to do that?

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070215/e2ec2f1f/attachment.html 

From emilia12 at mail.bg  Thu Feb 15 14:12:48 2007
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Thu, 15 Feb 2007 15:12:48 +0200
Subject: [Tutor] arguments
Message-ID: <1171545168.243a3889caf95@mail.bg>



Hi list,

I have a function with two arguments (say f(x,y))
and second which returns tuple (say def g(): return (xx,yy))

my question is how to put returned values from g() as
arguments to f ?

the direct way generates error:

f(g())
TypeError: ff() takes exactly 2 arguments (1 given)

and the hard way is
x, y = g()
f(x,y)

is ok but it uses two extra variables. Is there a simple way
to do this?

BTW f(g()[0], g()[1]) works too, but calls function g()
twice ...

thanks in advance
e.



-----------------------------

SCENA - ???????????? ????????? ???????? ?? ??????? ??????????? ? ??????????.
http://www.bgscena.com/


From kent37 at tds.net  Thu Feb 15 14:21:32 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Feb 2007 08:21:32 -0500
Subject: [Tutor] arguments
In-Reply-To: <1171545168.243a3889caf95@mail.bg>
References: <1171545168.243a3889caf95@mail.bg>
Message-ID: <45D45E5C.7000604@tds.net>

emilia12 at mail.bg wrote:
> 
> Hi list,
> 
> I have a function with two arguments (say f(x,y))
> and second which returns tuple (say def g(): return (xx,yy))
> 
> my question is how to put returned values from g() as
> arguments to f ?
> 
> the direct way generates error:
> 
> f(g())
> TypeError: ff() takes exactly 2 arguments (1 given)

Use f(*g())

The * syntax does exactly what you want - it takes a single sequence and 
interprets it as the full argument list.

Kent


From glingl at aon.at  Thu Feb 15 14:26:12 2007
From: glingl at aon.at (Gregor Lingl)
Date: Thu, 15 Feb 2007 14:26:12 +0100
Subject: [Tutor] arguments
In-Reply-To: <1171545168.243a3889caf95@mail.bg>
References: <1171545168.243a3889caf95@mail.bg>
Message-ID: <45D45F74.9030505@aon.at>

emilia12 at mail.bg schrieb:

>Hi list,
>
>I have a function with two arguments (say f(x,y))
>and second which returns tuple (say def g(): return (xx,yy))
>
>my question is how to put returned values from g() as
>arguments to f ?
>  
>
There is a special *-operator, which inserts the components of an Argument
(which must be a sequence) into the parametersof the calling function:
 >>> def f(x,y):
    print x,y

   
 >>> def g():
    return -5,1001

 >>> f(*g())
-5 1001
 >>>
Regards,
Gregor



>the direct way generates error:
>
>f(g())
>TypeError: ff() takes exactly 2 arguments (1 given)
>
>and the hard way is
>x, y = g()
>f(x,y)
>
>is ok but it uses two extra variables. Is there a simple way
>to do this?
>
>BTW f(g()[0], g()[1]) works too, but calls function g()
>twice ...
>
>thanks in advance
>e.
>
>
>
>-----------------------------
>
>SCENA - ???????????? ????????? ???????? ?? ??????? ??????????? ? ??????????.
>http://www.bgscena.com/
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


From rikard.bosnjakovic at gmail.com  Thu Feb 15 15:22:04 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 15 Feb 2007 15:22:04 +0100
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <6faf39c90702150449j7145bc73k504a26b6c34662c1@mail.gmail.com>
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
	<eqvpml$3v8$1@sea.gmane.org>
	<6faf39c90702150449j7145bc73k504a26b6c34662c1@mail.gmail.com>
Message-ID: <d9e88eaf0702150622i27fcc294o6a39d3eace24030@mail.gmail.com>

On 2/15/07, Andre Engels <andreengels at gmail.com> wrote:

> It's getting to be the majority of mailing lists that do it the other way,
> and I find it quite irritating that this list does not - I have had several
> times that I sent a mail, and after sending it, sometimes long after sending
> it, I realize I sent it to the sender instead of the list, so I send a
> second message after it. Who knows how often I have failed to do that?

I second that.

This list is the only one I've seen that does not utilize a
reply-to-tag in the postings. Lots of my replies has gone to the
poster in question and not to the list (which was the intention).


-- 
- Rikard.

From rikard.bosnjakovic at gmail.com  Thu Feb 15 15:24:25 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 15 Feb 2007 15:24:25 +0100
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <57B026980605A64F9B23484C5659E32E5B20EF@poccso.US.ad.atmel.com>
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
	<57B026980605A64F9B23484C5659E32E5B20EF@poccso.US.ad.atmel.com>
Message-ID: <d9e88eaf0702150624n6f5985ft1adbe8e2eeb2db61@mail.gmail.com>

On 2/14/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:

> The following tutor faq has an explanation:
>
> http://www.python.org/infogami-faq/tutor/tutor-why-do-my-replies-go-to-t
> he-person-who-sent-the-message-and-not-to-the-list/

I think the argument in that "explanation" sucks.

A asks something, B replies A. C replies to B's post, correcting him
on a few things and at the same time asks A some new questions.

There is no point in letting B having the sole post sent to his mailbox.

And these "flamewars" that the FAQ describes occur too seldom for it
to be an argument of the sake of not having a reply-to-tag.

Just my two cents.


-- 
- Rikard.

From rfquerin at gmail.com  Thu Feb 15 15:46:38 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Thu, 15 Feb 2007 09:46:38 -0500
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <d9e88eaf0702150624n6f5985ft1adbe8e2eeb2db61@mail.gmail.com>
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
	<57B026980605A64F9B23484C5659E32E5B20EF@poccso.US.ad.atmel.com>
	<d9e88eaf0702150624n6f5985ft1adbe8e2eeb2db61@mail.gmail.com>
Message-ID: <7d81675b0702150646t9307ac9hb25617b9e6a428f0@mail.gmail.com>

On 2/14/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:

>
> > The following tutor faq has an explanation:
> >
> > http://www.python.org/infogami-faq/tutor/tutor-why-do-my-replies-go-to-t
> > he-person-who-sent-the-message-and-not-to-the-list/



It seems like this is designed for the 5% case when it makes the other 95%
of normal reply cases more difficult. I would (like to) think that the vast
majority of replies are meant for all eyes. I would think it's the
responsibility of the person replying if he/she wants to respond privately
only rather than making that the defacto default.

Hitting reply in Gmail responds only back to the sender and not to the list.
I've been corrected (politely I might add) on more than one occasion.

Either way, it's a good list though. ;)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070215/5ec0f0f6/attachment.htm 

From alan.gauld at btinternet.com  Thu Feb 15 16:15:43 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Feb 2007 15:15:43 -0000
Subject: [Tutor] Replying to the tutor-list
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com><57B026980605A64F9B23484C5659E32E5B20EF@poccso.US.ad.atmel.com><d9e88eaf0702150624n6f5985ft1adbe8e2eeb2db61@mail.gmail.com>
	<7d81675b0702150646t9307ac9hb25617b9e6a428f0@mail.gmail.com>
Message-ID: <er1tf3$p96$1@sea.gmane.org>

"Richard Querin" <rfquerin at gmail.com> wrote
>>
>> > The following tutor faq has an explanation:
>> >
>> > http://www.python.org/infogami-faq/tutor/tutor-why-do-my-replies-go-to-t
>> > he-person-who-sent-the-message-and-not-to-the-list/
>
> It seems like this is designed for the 5% case when it makes the 
> other 95%
> of normal reply cases more difficult.

I dunno about you but 95% of my email is private, only
about 5% comes from mailing lists.

> I would (like to) think that the vast majority of replies are
> meant for all eyes.

Thats why its called Rely *ALL*. Private is Reply, Public is Reply 
ALL.
Thats what email tools have done from day one.

> responsibility of the person replying if he/she wants to respond 
> privately
> only rather than making that the defacto default.

The default is hit ReplyAll.
Only use Reply when you specifically want to send privately...
If there is only one sender ReplyAll will only send to them (unless
you have asked it to send to you too, but thats nearly always
configurable and only useful if you don't automatically create a
Sent entry)

> Hitting reply in Gmail responds only back to the sender and not to 
> the list.

That's true of the vast majority of mail tools.
Its what the email usability standard says is supposed to be the
meaning of those buttons. Thatsd why they are named that way.

> I've been corrected (politely I might add) on more than one 
> occasion.

So just use ReplyAll all the time... unless you only want to send to
the sender. (What I have noticed is that some web based mail tools
don't seem to have ReplyAll as the default which is downright 
unfriendly
design...)

I'm really confused about why mailing lists seem to be moving in
this direction. It adds nothing and makes a very inconsistent user
experience IMHO.

(But then, I'm equally confused as to why anyone would prefer a web
forum over a news group, and that seems to happen too. Newsgroups
are far more powerful and web forums add zero so far as I can tell...)

Alan G
An internet old-timer :-)




From alan.gauld at btinternet.com  Thu Feb 15 16:19:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Feb 2007 15:19:27 -0000
Subject: [Tutor] [Tutor} Why doesn't it choose a new number each time?
References: <BAY123-W9CB5490DC6D1445A6EF6FC4960@phx.gbl><d9e88eaf0702150106h146f0e80u51220392524b0037@mail.gmail.com>
	<5d8e35a70702150243maa94c3m541758cbf52b026a@mail.gmail.com>
Message-ID: <er1tm2$q37$1@sea.gmane.org>

"Geoframer" <geoframer at gmail.com> wrote

> Probably this is not unlike Alan suggest, but i got confused when i 
> read
> about tables. Unless he means dictionaries instead.

I meant tables in a generic sense. I actually started using
a dictionary then changed to a list because its more generic..
But it could have been tuples, dictionaries, even database tables.
Any 2D storage mechanism.

The principles are exactly the same.

Alan G. 



From rfquerin at gmail.com  Thu Feb 15 16:48:52 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Thu, 15 Feb 2007 10:48:52 -0500
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <er1tf3$p96$1@sea.gmane.org>
References: <d9e88eaf0702140820h22fd39fcne034df53fe14c589@mail.gmail.com>
	<57B026980605A64F9B23484C5659E32E5B20EF@poccso.US.ad.atmel.com>
	<d9e88eaf0702150624n6f5985ft1adbe8e2eeb2db61@mail.gmail.com>
	<7d81675b0702150646t9307ac9hb25617b9e6a428f0@mail.gmail.com>
	<er1tf3$p96$1@sea.gmane.org>
Message-ID: <7d81675b0702150748r33d2912aqe2d9e29d7770de48@mail.gmail.com>

On 2/15/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
>
> I dunno about you but 95% of my email is private, only
> about 5% comes from mailing lists.
>
>
Yeah, me too, but I guess it seems easier to just hit 'reply' 100% of the
time and have it go to the right recipient. My point really was that 95% of
the time, the recipient is everyone in the mailing list, and only 5% of the
time do I want to privately respond to a mailing list item.

I've just noticed that Gmail doesn't even show a reply-all button if there
is only one sender. If there is a cc included then it becomes available.
Either way I will just remember to hit reply-all. No big whup.

RQ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070215/4b455f6f/attachment.htm 

From andreengels at gmail.com  Thu Feb 15 16:49:09 2007
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 15 Feb 2007 16:49:09 +0100
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>
	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>
Message-ID: <6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com>

2007/2/15, ALAN GAULD <alan.gauld at btinternet.com>:

>  > realize I sent it to the sender instead of the list,
> > so I send a second message after it.
>
> So do you find it odd when dealing with normal email
> and you hit reply and it only goes to the sender?
>

No, because it is sent by the sender to me, not to some list.

 Or do you not use email beyond one to one and list
> membership? Surely you are introducing inconsistent
> behaviour between your private mail and your list mail??
>

No, in my private mail I hit 'reply' and I reply. In my mailing lists I hit
'reply' and reply.

I seriously cannot fathom why anyone would want a tool
> that makes things operate two differenmt ways, one for
> normal email and one for mailing lists. They all come into
> the same mailbox, I want them all to work the same way!
>

Well, what is the 'same way'? When I reply, I reply. When I get something
from a person, and reply it goes to that person. When I read something on a
newsgroup and reply, it goes to that newsgroup. When I read something on a
forum and reply, it goes to that forum.

As a matter of interest, what happens if you hit ReplyAll
> on the other style lists? I assume that would work as I
> would expect and send to the list and sender?
> If so how do you send to the sender only?
>

Change the address by hand. That's hard to do, it's true, but the number of
times I want to reply in person to a message on a list is so low that that's
no problem at all.


-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070215/c9aef446/attachment.html 

From mabystry at verizon.net  Thu Feb 15 18:04:18 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 15 Feb 2007 12:04:18 -0500
Subject: [Tutor] Convert my .bat and .vbs to .py
Message-ID: <45D49292.9010404@verizon.net>

Hello,

This is my first post. I have just begun to code with python. My goal is to convert about a dozen or 
so DOS/Windows batch scripts(.bat) and vbscripts(.vbs) that I use on a day-to-day basis to python so 
that they can be run on either my windows or linux workstations.

The first things that I want to learn is how to do basic stuff like copying, moving, and deleting 
files around from folder to folder. I have been in the help section of python (copyfile section) 
but I do not understand what I am doing wrong.


Here is my simple DOS batch file...

######################################################################
copy D:\PDF_Holding\*PRODUCTION.pdf Z:\
copy D:\PDF_Holding\*ILLUSTRATION.pdf H:\MARKETING\ILLUSTRATIONS\PRODUCT
pause

del *.pdf
######################################################################

Basically, it copies the "production" and "illustration" pdf files to certain folders than deletes 
the left over pdf files when done. Yes, I could move them instead of copying them.

I'm no asking for anyone to write this for me but if someone could lead me i the right direction, I 
would be grateful.

Thank-you.

Mark

From mail at timgolden.me.uk  Thu Feb 15 18:22:43 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 15 Feb 2007 17:22:43 +0000
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D49292.9010404@verizon.net>
References: <45D49292.9010404@verizon.net>
Message-ID: <45D496E3.9060602@timgolden.me.uk>

Mark Bystry wrote:

> The first things that I want to learn is how to do basic stuff like copying, moving, and deleting 
> files around from folder to folder. I have been in the help section of python (copyfile section) 
> but I do not understand what I am doing wrong.

Welcome to Python. You probably want to look at the shutil
module, possibly combined with the os module:

http://docs.python.org/lib/module-shutil.html
http://docs.python.org/lib/os-file-dir.html

TJG

From Mike.Hansen at atmel.com  Thu Feb 15 18:28:20 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 15 Feb 2007 10:28:20 -0700
Subject: [Tutor] Convert my .bat and .vbs to .py
References: <45D49292.9010404@verizon.net>
Message-ID: <57B026980605A64F9B23484C5659E32E5B21C8@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Mark Bystry
> Sent: Thursday, February 15, 2007 10:04 AM
> To: tutor at python.org
> Subject: [Tutor] Convert my .bat and .vbs to .py
> 
> Hello,
> 
> This is my first post. I have just begun to code with python. 
> My goal is to convert about a dozen or 
> so DOS/Windows batch scripts(.bat) and vbscripts(.vbs) that I 
> use on a day-to-day basis to python so 
> that they can be run on either my windows or linux workstations.
> 
> The first things that I want to learn is how to do basic 
> stuff like copying, moving, and deleting 
> files around from folder to folder. I have been in the help 
> section of python (copyfile section) 
> but I do not understand what I am doing wrong.
> 
> 
> Here is my simple DOS batch file...
> 
> ######################################################################
> copy D:\PDF_Holding\*PRODUCTION.pdf Z:\
> copy D:\PDF_Holding\*ILLUSTRATION.pdf 
> H:\MARKETING\ILLUSTRATIONS\PRODUCT
> pause
> 
> del *.pdf
> ######################################################################
> 
> Basically, it copies the "production" and "illustration" pdf 
> files to certain folders than deletes 
> the left over pdf files when done. Yes, I could move them 
> instead of copying them.
> 
> I'm no asking for anyone to write this for me but if someone 
> could lead me i the right direction, I 
> would be grateful.
> 
> Thank-you.
> 
> Mark

Maybe there's a way to use shutil's copytree function with os module's
remove function or shutil's rmtree function? If not, use the glob module
to gather the file names and then walk the results of the glob with a
for loop and use shutil's copyfile function.

Mike

From eric at ericwalstad.com  Thu Feb 15 18:36:48 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Thu, 15 Feb 2007 09:36:48 -0800
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D49292.9010404@verizon.net>
References: <45D49292.9010404@verizon.net>
Message-ID: <45D49A30.2050005@ericwalstad.com>

Hey Mark, welcome aboard!

There are a few different approaches you could take to convert your
scripts.  If most of your scripts are related to copying/moving files,
I'd have a look at Python's shutil module.  I think it'll work in both
Windows and Linux but I don't have a Windows machine handy to test it.

<http://docs.python.org/lib/module-shutil.html>

Have fun,

Eric.

From rob.andrews at gmail.com  Thu Feb 15 18:38:14 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Thu, 15 Feb 2007 11:38:14 -0600
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D49292.9010404@verizon.net>
References: <45D49292.9010404@verizon.net>
Message-ID: <8d757d2e0702150938p25ff98cbpce11a91df87808df@mail.gmail.com>

If you import os, os.path, and shutil (only the ones you need,
although I wind up using all three for this sort of task), you can do
all that you have in mind and more.

os.path opens up some pretty painless methods for doing things like
testing to make sure the file exists in a given location before
copying it (or deleting it), which can save a good bit of heartache.

shutil can be used for not only copying files, but even copying entire
directory trees.

-Rob A.

From alan.gauld at btinternet.com  Thu Feb 15 18:39:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Feb 2007 17:39:00 -0000
Subject: [Tutor] Convert my .bat and .vbs to .py
References: <45D49292.9010404@verizon.net>
Message-ID: <er25ro$8q4$1@sea.gmane.org>


"Mark Bystry" <mabystry at verizon.net> wrote

> My goal is to convert about a dozen or so DOS/Windows batch 
> scripts(.bat) and vbscripts(.vbs) that I use on a day-to-day basis 
> to python 

You might want to look at my Using the OS topic in my tutorial
It covers basic file manipulation and starting external programs 
etc.

> that they can be run on either my windows or linux workstations.

That might be harder than you think due to differences in paths etc.
Also some external commands will be different, and ones with the 
same name take different arguments/orders or args etc

If you write them in pure Python you should be OK but if you 
just run sequences of OS commands (typical of batch files) 
then you might run into problems.

> The first things that I want to learn is how to do basic stuff 
> like copying, moving, and deleting files around from folder to 
> folder. 

Try my tutor topic.


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


From rob.andrews at gmail.com  Thu Feb 15 18:42:07 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Thu, 15 Feb 2007 11:42:07 -0600
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D49A30.2050005@ericwalstad.com>
References: <45D49292.9010404@verizon.net> <45D49A30.2050005@ericwalstad.com>
Message-ID: <8d757d2e0702150942u4e80136bwfa4732d1c8303bd9@mail.gmail.com>

I can confirm it works nicely in Windows. I have a script I use
several times daily to create working directories on a local
workstation by copying over arbitrarily deep directory trees into an
"original files" directory under a root directory named by job number.
The local workstation on which I have python running is a Windows
machine, and it's agnostic about the operating systems of the network
drives from which the data is gathered.

Quite handy and not even a very long program after the try/except
bulletproofing is added.

-Rob A.

On 2/15/07, Eric Walstad <eric at ericwalstad.com> wrote:
> Hey Mark, welcome aboard!
>
> There are a few different approaches you could take to convert your
> scripts.  If most of your scripts are related to copying/moving files,
> I'd have a look at Python's shutil module.  I think it'll work in both
> Windows and Linux but I don't have a Windows machine handy to test it.

From mabystry at verizon.net  Thu Feb 15 19:21:12 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 15 Feb 2007 13:21:12 -0500
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <er25ro$8q4$1@sea.gmane.org>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
Message-ID: <45D4A498.3070905@verizon.net>

Wow! Got a lot of responses to my post. Thanks everyone. After reading all of them, I may have to 
learn by example after all.  I'm going to try Alan Gauld's tutorials first.

Mark

Alan Gauld wrote the following on 2/15/2007 12:39 PM:
> "Mark Bystry" <mabystry at verizon.net> wrote
> 
>> My goal is to convert about a dozen or so DOS/Windows batch 
>> scripts(.bat) and vbscripts(.vbs) that I use on a day-to-day basis 
>> to python 
> 
> You might want to look at my Using the OS topic in my tutorial
> It covers basic file manipulation and starting external programs 
> etc.
> 
>> that they can be run on either my windows or linux workstations.
> 
> That might be harder than you think due to differences in paths etc.
> Also some external commands will be different, and ones with the 
> same name take different arguments/orders or args etc
> 
> If you write them in pure Python you should be OK but if you 
> just run sequences of OS commands (typical of batch files) 
> then you might run into problems.
> 
>> The first things that I want to learn is how to do basic stuff 
>> like copying, moving, and deleting files around from folder to 
>> folder. 
> 
> Try my tutor topic.
> 
> 

From mabystry at verizon.net  Thu Feb 15 19:32:18 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 15 Feb 2007 13:32:18 -0500
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <8d757d2e0702151023s2dbf9a50m92f700f245ad6ac4@mail.gmail.com>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
	<45D4A498.3070905@verizon.net>
	<8d757d2e0702151023s2dbf9a50m92f700f245ad6ac4@mail.gmail.com>
Message-ID: <45D4A732.2000002@verizon.net>

You guys are great! I'm not sure how I found this mailing list but I'm glad that I subscribed.

Mark

Rob Andrews wrote the following on 2/15/2007 1:23 PM:
> We're good like that. heh
> 
> On 2/15/07, Mark Bystry <mabystry at verizon.net> wrote:
>> Wow! Got a lot of responses to my post. Thanks everyone. After reading all of them, I may have to
>> learn by example after all.  I'm going to try Alan Gauld's tutorials first.
>>
> 

From bill at celestial.net  Thu Feb 15 19:47:31 2007
From: bill at celestial.net (Bill Campbell)
Date: Thu, 15 Feb 2007 10:47:31 -0800
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>
	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>
	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com>
Message-ID: <20070215184731.GA20607@ayn.mi.celestial.com>

The major reason for not setting Reply-To: thelist is that it makes it
*SLIGHTLY* more difficult to post something to the list and replys should
go to the sender.  IHMO, one should have to go to a little bit of effort
before posting a message that may go to thousands of recipients.

Using the ``mutt'' mailer, this effort is simply pressing ``L'' instead of
``r'' when posting to the list and adding the listname to the subscribe
section of ~/.muttrc, hardly a major inconvenience.

	http://www.unicom.com/pw/reply-to-harmful.html

...
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

``We believe...that a mugger will kill you in the half-second it takes to
draw from the holster, but won't harm you while you dial the police on your
cell phone, talk to the dispatcher and wait half an hour for officers to
arrive.'' -- Gun-Control Net-work Credo

From mabystry at verizon.net  Thu Feb 15 20:21:57 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 15 Feb 2007 14:21:57 -0500
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <er25ro$8q4$1@sea.gmane.org>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
Message-ID: <45D4B2D5.1080701@verizon.net>

Well, immediately I am having problems. Be patient with me.

This what I have...

copy_file.py
############################################

import os
import shutil as sh

sh.copy('C:\testing_it.txt', 'D:\')
raw_input("Done!")

############################################

...and it's not working. Obviously, I'm trying to copy a text file on C:\ to D:\.

From rob.andrews at gmail.com  Thu Feb 15 20:29:53 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Thu, 15 Feb 2007 13:29:53 -0600
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D4B2D5.1080701@verizon.net>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
	<45D4B2D5.1080701@verizon.net>
Message-ID: <8d757d2e0702151129n944cefald691562280e0dd15@mail.gmail.com>

Ahh, yes. Your main trouble seems to be the use of \ instead of / in
'C:\testing_it.txt'

Windows uses \, whereas python uses /. So you can replace 'c:\....'
with your choice of the following:

'c:/....' (replacing \ with /)
r'c:\....' (the 'r' before the string tells python it's a raw string)
'c:\\....' (the first \ telling python to take the second \ at face value)

-Rob A.

On 2/15/07, Mark Bystry <mabystry at verizon.net> wrote:
> Well, immediately I am having problems. Be patient with me.
>
> This what I have...
>
> copy_file.py
> ############################################
>
> import os
> import shutil as sh
>
> sh.copy('C:\testing_it.txt', 'D:\')
> raw_input("Done!")
>
> ############################################

From kent37 at tds.net  Thu Feb 15 20:32:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Feb 2007 14:32:37 -0500
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D4B2D5.1080701@verizon.net>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
	<45D4B2D5.1080701@verizon.net>
Message-ID: <45D4B555.4010409@tds.net>

Mark Bystry wrote:
> Well, immediately I am having problems. Be patient with me.

We will be, you're doing great so far :-)
> 
> This what I have...
> 
> copy_file.py
> ############################################
> 
> import os
> import shutil as sh
> 
> sh.copy('C:\testing_it.txt', 'D:\')

Backslash is an escape character in Python string constants. \t actually 
inserts a tab character in the string.

You have several choices:

'C:/testing_it.txt' - forward slashes work fine too
'C:\\testing_it.txt' - double the \ to make it a literal.
r'C:\testing_it.txt' - 'r' prefix makes it a 'raw' string, backslashes 
are (mostly) treated as literals rather than escapes.

Kent


From mabystry at verizon.net  Thu Feb 15 20:43:51 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 15 Feb 2007 14:43:51 -0500
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <8d757d2e0702151129n944cefald691562280e0dd15@mail.gmail.com>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
	<45D4B2D5.1080701@verizon.net>
	<8d757d2e0702151129n944cefald691562280e0dd15@mail.gmail.com>
Message-ID: <45D4B7F7.7080805@verizon.net>

Jeez! I'm retarded. It works like a charm now.

Thanks for that Rob

Mark

Rob Andrews wrote the following on 2/15/2007 2:29 PM:
> Ahh, yes. Your main trouble seems to be the use of \ instead of / in
> 'C:\testing_it.txt'
> 
> Windows uses \, whereas python uses /. So you can replace 'c:\....'
> with your choice of the following:
> 
> 'c:/....' (replacing \ with /)
> r'c:\....' (the 'r' before the string tells python it's a raw string)
> 'c:\\....' (the first \ telling python to take the second \ at face value)
> 
> -Rob A.
> 
> On 2/15/07, Mark Bystry <mabystry at verizon.net> wrote:
>> Well, immediately I am having problems. Be patient with me.
>>
>> This what I have...
>>
>> copy_file.py
>> ############################################
>>
>> import os
>> import shutil as sh
>>
>> sh.copy('C:\testing_it.txt', 'D:\')
>> raw_input("Done!")
>>
>> ############################################
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From eric at ericwalstad.com  Thu Feb 15 20:58:11 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Thu, 15 Feb 2007 11:58:11 -0800
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D4B2D5.1080701@verizon.net>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
	<45D4B2D5.1080701@verizon.net>
Message-ID: <45D4BB53.2010301@ericwalstad.com>

Hey Mark,
Mark Bystry wrote:
> sh.copy('C:\testing_it.txt', 'D:\')

Also have a look at the os.path module.  Because you want these scripts
to work on both Linux and Windows, using os.path will let you avoid
writing platform specific code to handle your slashes.

For example:
import os
path_parts_list = ['C:', 'testing_it.txt']

Now, os.path.join will join those path parts together with whatever is
appropriate for the OS you are running on:

os.path.join(path_parts_list)

This should give you:
'c:\testing_it.txt' on Windows and
'c:/testing_it.txt' on Linux (which doesn't make sense, but demonstrates
how os.path can handle your os-specific slashes for you).

There are lots of helpful path related built-ins:
<http://docs.python.org/lib/module-os.path.html>

From mabystry at verizon.net  Thu Feb 15 21:10:00 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 15 Feb 2007 15:10:00 -0500
Subject: [Tutor] Convert my .bat and .vbs to .py
In-Reply-To: <45D4BB53.2010301@ericwalstad.com>
References: <45D49292.9010404@verizon.net> <er25ro$8q4$1@sea.gmane.org>
	<45D4B2D5.1080701@verizon.net> <45D4BB53.2010301@ericwalstad.com>
Message-ID: <45D4BE18.1070600@verizon.net>

Ahh. Great tip Eric. Thank-you.

Mark


Eric Walstad wrote the following on 2/15/2007 2:58 PM:
> Hey Mark,
> Mark Bystry wrote:
>> sh.copy('C:\testing_it.txt', 'D:\')
> 
> Also have a look at the os.path module.  Because you want these scripts
> to work on both Linux and Windows, using os.path will let you avoid
> writing platform specific code to handle your slashes.
> 
> For example:
> import os
> path_parts_list = ['C:', 'testing_it.txt']
> 
> Now, os.path.join will join those path parts together with whatever is
> appropriate for the OS you are running on:
> 
> os.path.join(path_parts_list)
> 
> This should give you:
> 'c:\testing_it.txt' on Windows and
> 'c:/testing_it.txt' on Linux (which doesn't make sense, but demonstrates
> how os.path can handle your os-specific slashes for you).
> 
> There are lots of helpful path related built-ins:
> <http://docs.python.org/lib/module-os.path.html>
> 

From gander_93 at hotmail.com  Fri Feb 16 01:48:37 2007
From: gander_93 at hotmail.com (C. Gander)
Date: Thu, 15 Feb 2007 18:48:37 -0600
Subject: [Tutor] How do I compile Python for people so they don't have to
	download?
Message-ID: <BAY120-F166AACDA8C296A9C61CD8F81950@phx.gbl>

I downloaded py2exe and I thought it was a program that you just browsed 
your driver and gave it the .py file and it would do the rest. But I 
downloaded it and I cannot figure out how to use it. Please help.

_________________________________________________________________
Get in the mood for Valentine's Day. View photos, recipes and more on your 
Live.com page. 
http://www.live.com/?addTemplate=ValentinesDay&ocid=T001MSN30A0701


From rikard.bosnjakovic at gmail.com  Fri Feb 16 02:01:51 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 16 Feb 2007 02:01:51 +0100
Subject: [Tutor] How do I compile Python for people so they don't have
	to download?
In-Reply-To: <BAY120-F166AACDA8C296A9C61CD8F81950@phx.gbl>
References: <BAY120-F166AACDA8C296A9C61CD8F81950@phx.gbl>
Message-ID: <d9e88eaf0702151701n5357ad2bmd1bb9aad0db00e0f@mail.gmail.com>

On 2/16/07, C. Gander <gander_93 at hotmail.com> wrote:

> I downloaded py2exe and I thought it was a program that you just browsed
> your driver and gave it the .py file and it would do the rest. But I
> downloaded it and I cannot figure out how to use it. Please help.

You don't have to "figure it out", you simply peek the tutorial. Have
it a go here:

http://www.py2exe.org/index.cgi/Tutorial

or the FAQ, here:

http://www.py2exe.org/index.cgi/FAQ


-- 
- Rikard.

From rabidpoobear at gmail.com  Fri Feb 16 05:18:39 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 15 Feb 2007 22:18:39 -0600
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <20070215184731.GA20607@ayn.mi.celestial.com>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com>
	<20070215184731.GA20607@ayn.mi.celestial.com>
Message-ID: <45D5309F.2060406@gmail.com>

Bill Campbell wrote:
> The major reason for not setting Reply-To: thelist is that it makes it
> *SLIGHTLY* more difficult to post something to the list and replys should
> go to the sender.  IHMO, one should have to go to a little bit of effort
> before posting a message that may go to thousands of recipients.
>
> Using the ``mutt'' mailer, this effort is simply pressing ``L'' instead of
> ``r'' when posting to the list and adding the listname to the subscribe
> section of ~/.muttrc, hardly a major inconvenience.
>   
It's not the inconvenience but the fact that it's nonstandard, as far as 
every mailing list i've been on except this.
You don't pick people to mail specifically on the mailing list, why 
should you reply to specific people, unless you hit a special button?
I didn't get the e-mail from you.  You posted the e-mail to the list and 
i received it because I'm a member of the list.
The list is the sender.  It aggregates posts to me.  When I reply it 
should put my post in the same thread, one level below and immediately after
the previous person's post, like i expect it to.
It has retrained me to use reply-all, but I still don't like it.
Also you end up CCing copies of your e-mails to everyone.
> 	http://www.unicom.com/pw/reply-to-harmful.html
>
> ...
> 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
>
> ``We believe...that a mugger will kill you in the half-second it takes to
> draw from the holster, but won't harm you while you dial the police on your
> cell phone, talk to the dispatcher and wait half an hour for officers to
> arrive.'' -- Gun-Control Net-work Credo
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From bill at celestial.net  Fri Feb 16 05:50:25 2007
From: bill at celestial.net (Bill Campbell)
Date: Thu, 15 Feb 2007 20:50:25 -0800
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <45D5309F.2060406@gmail.com>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>
	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>
	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com>
	<20070215184731.GA20607@ayn.mi.celestial.com>
	<45D5309F.2060406@gmail.com>
Message-ID: <20070216045025.GA4710@ayn.mi.celestial.com>

On Thu, Feb 15, 2007, Luke Paireepinart wrote:
>Bill Campbell wrote:
>> The major reason for not setting Reply-To: thelist is that it makes it
>> *SLIGHTLY* more difficult to post something to the list and replys should
>> go to the sender.  IHMO, one should have to go to a little bit of effort
>> before posting a message that may go to thousands of recipients.
>>
>> Using the ``mutt'' mailer, this effort is simply pressing ``L'' instead of
>> ``r'' when posting to the list and adding the listname to the subscribe
>> section of ~/.muttrc, hardly a major inconvenience.
>>   
>It's not the inconvenience but the fact that it's nonstandard, as far as 
>every mailing list i've been on except this.

Hardly non-standrd.  The option for this in the Mailman MLM is:

     Where are replies to list messages directed? Poster is strongly
     recommended for most mailing lists.

I've been maintaining various technical mailing lists for over twenty years
now, and see this same thread come up many times.

Having the Reply-To: to the original poster minimizes the probability of
somebody sending mail to a list that was intended for the original poster
(which may be private).  The only advantage of having it set to the list is
it makes it easier for lazy people to send nonsense to hundreds of people.

As I said in my original message, it should require a little bit of effort
to send messages to hundreds or thousands of recipients.

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

It is necessary for the welfare of society that genius should be
privileged to utter sedition, to blaspheme, to outrage good taste, to
corrupt the youthful mind, and generally to scandalize one's uncles.
                -- George Bernard Shaw

From carroll at tjc.com  Fri Feb 16 07:04:31 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 15 Feb 2007 22:04:31 -0800 (PST)
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <20070216045025.GA4710@ayn.mi.celestial.com>
Message-ID: <Pine.LNX.4.44.0702152153280.3153-100000@violet.rahul.net>

On Thu, 15 Feb 2007, Bill Campbell wrote:

> Having the Reply-To: to the original poster minimizes the probability of
> somebody sending mail to a list that was intended for the original poster
> (which may be private).  

Well, no.  It minimizes the probability of someone sending mail to a list.  

It equally minimizes that probability, regardless of whether the mail was 
intended to go to the list or privately to the original poster.

Most replies to this list are intended to go to the list.  At least a 
couple times a week we see messages from one of the more helpful tutors 
saying "please reply to the list, not just to me."  Just yesterday, I 
received an email in reply to one of my messages that was intended to 
assist the person I had replied to.  The intended recepient never got the 
email, because the sender, no doubt relying on the default, did not reply 
to the list.

Having reply-to go to the list is having it go to the most commonly 
preferred recipient.

So, minimizing the probability that the mail will go to the list, when 
most mail is intended to go to the list, is, I think, a Bad Thing.  Not 
that Bad a Thing, in the grand scheme of things, but a Bad Thing 
nonetheless.

> The only advantage of having it set to the list is it makes it easier
> for lazy people to send nonsense to hundreds of people.

That's way out of line.  The advantage of having it go to the list is to
make the default coincide with the usual intent; and that's what defaults
are for.

This is true regardless of whether the replying party is "lazy" or not;  
and regardless of whether the replying post is "nonsense" or not.

As I said, I have no particular dog in this fight.  The list uses a 
reply-to mechanism that I don't think makes sense, so I fixed it for 
myself with procmail.  But it's pretty arrogant to think that the divide 
of opinion on here is not a reasonable one, and that anyone who doesn't 
agree with your position must be lazy or writing nonsense.


From alan.gauld at btinternet.com  Fri Feb 16 10:45:46 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Feb 2007 09:45:46 -0000
Subject: [Tutor] New Tutor topic(almost)
References: <000501c74fb3$a0b7f860$6601a8c0@xp>
Message-ID: <er3uge$sap$1@sea.gmane.org>

"Alan Gauld" <alan.gauld at freenet.co.uk> wrote in 

> After a very long delay I finally got some work done on 
> my networking with sockets topic in my tutorial. There is 
> still a section to complete but the introductory explanations 
> and examples are now on the site.
> 
> http://www.freenetpages.co.uk/hp/alan.gauld/tutsocket.htm
> 
> If anyone has any feedback I'd love to hear it.

OK, I finished it, the final address book example is now there too.

Enjoy,

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


From lnhaig at gmail.com  Fri Feb 16 10:54:34 2007
From: lnhaig at gmail.com (Lance Haig)
Date: Fri, 16 Feb 2007 09:54:34 +0000
Subject: [Tutor] New Tutor topic(almost)
In-Reply-To: <er3uge$sap$1@sea.gmane.org>
References: <000501c74fb3$a0b7f860$6601a8c0@xp> <er3uge$sap$1@sea.gmane.org>
Message-ID: <45D57F5A.7040101@gmail.com>

Hi Alan,

Firstly thank you for the tutorials I have used your book and website to 
great affect.
I use the download on the train when I am travelling.

I have a question though.

Do you update the web page downloads every time you update the site?

I want to download a new copy and was hoping to get the latest one.

Thanks again

Lance




Alan Gauld wrote:
> "Alan Gauld" <alan.gauld at freenet.co.uk> wrote in 
>
>   
>> After a very long delay I finally got some work done on 
>> my networking with sockets topic in my tutorial. There is 
>> still a section to complete but the introductory explanations 
>> and examples are now on the site.
>>
>> http://www.freenetpages.co.uk/hp/alan.gauld/tutsocket.htm
>>
>> If anyone has any feedback I'd love to hear it.
>>     
>
> OK, I finished it, the final address book example is now there too.
>
> Enjoy,
>
>   

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

From alan.gauld at btinternet.com  Fri Feb 16 11:06:57 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Feb 2007 10:06:57 -0000
Subject: [Tutor] Replying to the tutor-list
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com><20070215184731.GA20607@ayn.mi.celestial.com>
	<45D5309F.2060406@gmail.com>
Message-ID: <er3vo5$to$1@sea.gmane.org>

"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

> It's not the inconvenience but the fact that it's nonstandard, as 
> far as
> every mailing list i've been on except this.

It is interesting to see this thread because its a hot button of mine
that many new mailing lists implement this non standard behaviour
- ie send replies to the list!

But its obvious there are two views at work here.

I see the standard behaviour of Reply as - It only ever sends
to one person. Thus if I use Reply I know, with absolute certainty,
that I will never, ever, be sending private views to anyone other than
the intended recipient. Now when a mailing list subverts that it
completely blows that contract out of the water. It means I have
to be much, much, more careful about checking what I send and
to whom. When dealing with 300+ emails per day, only a small
number of which are from lists, that's a major pain.

The other view is that Reply should send the mail to whatever the
original source of the message was whether it be a list, newsgroup,
forum or whatever. (But in that view what is the purpose of
ReplyALL - why is it there?) Particularly since doing it this way
actually loses the natural ability of the mail tool to send to an
individual!

> I didn't get the e-mail from you.  You posted the e-mail to the list 
> and
> i received it because I'm a member of the list.

But you didn't really get it from the list either. The list server 
does
occasionally send emails - bounces, errors, reminders etc - but
really it forwards mails from an originator. You do get mails from
me, not the list server. The list server is no different to your 
normal
SMTP relay. It simply forwards the mails I send, it is a mechanism
to replace everyone having to maintain their own copy of a very
large distribution list. But when I send a mail to tutor my mental
model is that the tutor addrsss is just a large distribution list.

As to standard list behaviour, I don't know of any list thats been
around for more than say 10 years that uses Reply to send to All.
This seems to be a very recent thing. (And most of the lists I am
on have been around for much more than 10 years! :-)

> The list is the sender.  It aggregates posts to me.

If you subscribe to the digest this is true, but you should never
reply to the digest! The individiual mails inside the digest are
all sent from the individual posters.

> When I reply it should put my post in the same thread,
> one level below and immediately after the previous person's
> post

Sorry, we are talking about a mailing list here, not a newsgroup
or forum. Mail doesn't naturally support threading, many mail
clients don't do it at all. Others simply sort by subject/date.
Threading of email is always a bit arbitrary and error prone in
my exprience. The concept is there but the implementation
is nearly always dependant on the client (from gmane to Outlook...).

> It has retrained me to use reply-all, but I still don't like it.
> Also you end up CCing copies of your e-mails to everyone.
>> http://www.unicom.com/pw/reply-to-harmful.html

That's a plus in my book because I use the digest (or gmane
newsgroup) so it keeps me in real-time sync with the threads
I'm actively involved with but leaves the others for batch mode
reading...

Regards,

Alan G.
Vive la difference! 



From mail at timgolden.me.uk  Fri Feb 16 11:24:21 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 16 Feb 2007 10:24:21 +0000
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <er3vo5$to$1@sea.gmane.org>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com><20070215184731.GA20607@ayn.mi.celestial.com>	<45D5309F.2060406@gmail.com>
	<er3vo5$to$1@sea.gmane.org>
Message-ID: <45D58655.1000902@timgolden.me.uk>

Alan Gauld wrote:
> But its obvious there are two views at work here.

(The one which sees an apostrophe in "it's" and the
one which doesn't? ;)

But, joking aside, I think you've summarised the situation
quite well, and I suspect that -- given the what must be
thousands of mailing lists and newsgroups out there --
anyones claim that "most x do y" is probably based on
anecdotal experience, matter how widespread and long-lived.

I would take minor issue -- with you, and with the creators
of Thunderbird which is my current mail client of choice. It
looks to me as though you're suggesting that the reply-all
button is there to reply to a list, whereas it seems to me
to be there to reply to all the recipients in the original
email, *not* just to reply to a group or other bulk originator.
Now that's what Thunderbird does: puts Alan Gauld in the To:
field and tutor at ... in cc: My problem there is that I usually
don't want to send the originating individual a private copy
of an email he/she is going to receive from the list in any
case, so I usually cut-and-paste around so that only the list
is in To: AFAIK, TB doesn't offer any configurability here,
neither a reply-to-list button, nor any option to treat a
list specially on a general reply-to-all.

I work with several different lists and simply work around
the differences between them so this is hardly problematic
for me, but if anyone knows of a TB configuration (or extension)
which offers reply-to-group please do let me know!

> Vive la difference! 

Indeed.

TJG

From mail at timgolden.me.uk  Fri Feb 16 11:30:11 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 16 Feb 2007 10:30:11 +0000
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <45D58655.1000902@timgolden.me.uk>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com><20070215184731.GA20607@ayn.mi.celestial.com>	<45D5309F.2060406@gmail.com>	<er3vo5$to$1@sea.gmane.org>
	<45D58655.1000902@timgolden.me.uk>
Message-ID: <45D587B3.1040703@timgolden.me.uk>

Tim Golden wrote:
> Alan Gauld wrote:
>> But its obvious there are two views at work here.
> 
> (The one which sees an apostrophe in "it's" and the
> one which doesn't? ;)
> 
> But, joking aside, I think you've summarised the situation
> quite well, and I suspect that -- given the what must be
> thousands of mailing lists and newsgroups out there --
> anyones claim 

Ouch! "anyone's claim..."

:)
TJG

From kent37 at tds.net  Fri Feb 16 12:12:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Feb 2007 06:12:37 -0500
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <45D58655.1000902@timgolden.me.uk>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com><20070215184731.GA20607@ayn.mi.celestial.com>	<45D5309F.2060406@gmail.com>	<er3vo5$to$1@sea.gmane.org>
	<45D58655.1000902@timgolden.me.uk>
Message-ID: <45D591A5.3010309@tds.net>

Tim Golden wrote:
> field and tutor at ... in cc: My problem there is that I usually
> don't want to send the originating individual a private copy
> of an email he/she is going to receive from the list in any
> case, so I usually cut-and-paste around so that only the list
> is in To: AFAIK, TB doesn't offer any configurability here,
> neither a reply-to-list button, nor any option to treat a
> list specially on a general reply-to-all.

I use TB too; if you reply-all and just delete the originator from To: 
(leaving the list as Cc:) it works fine. Though I have started leaving 
the originator in as some people seem to prefer that.

Kent


From toxiufeng at gmail.com  Fri Feb 16 08:01:43 2007
From: toxiufeng at gmail.com (xiufeng liu)
Date: Fri, 16 Feb 2007 09:01:43 +0200
Subject: [Tutor] how to wirte code In python :str = (a>b?"Yes":"NO")
Message-ID: <d9d086320702152301i5c21cbf4yc892409de9b29fe2@mail.gmail.com>

Hi, all,

In python if there is any similar way like in Java, or C++ to express
the following:
str = (a>b?"Yes":"NO")


thanks!

From mail at timgolden.me.uk  Fri Feb 16 12:28:21 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 16 Feb 2007 11:28:21 +0000
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <45D591A5.3010309@tds.net>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com><20070215184731.GA20607@ayn.mi.celestial.com>	<45D5309F.2060406@gmail.com>	<er3vo5$to$1@sea.gmane.org>
	<45D58655.1000902@timgolden.me.uk> <45D591A5.3010309@tds.net>
Message-ID: <45D59555.9080105@timgolden.me.uk>

Kent Johnson wrote:
> Tim Golden wrote:
>> field and tutor at ... in cc: My problem there is that I usually
>> don't want to send the originating individual a private copy
>> of an email he/she is going to receive from the list in any
>> case, so I usually cut-and-paste around so that only the list
>> is in To: AFAIK, TB doesn't offer any configurability here,
>> neither a reply-to-list button, nor any option to treat a
>> list specially on a general reply-to-all.
> 
> I use TB too; if you reply-all and just delete the originator from To: 
> (leaving the list as Cc:) it works fine. Though I have started leaving 
> the originator in as some people seem to prefer that.

Thanks for that; (testing it out on this post). My issue is that my 
procmail filter doesn't seem to pick up the list when it's cced.
But that's for me to sort out it :)

TJG

From arcege at gmail.com  Fri Feb 16 13:00:20 2007
From: arcege at gmail.com (Michael P. Reilly)
Date: Fri, 16 Feb 2007 07:00:20 -0500
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <er3vo5$to$1@sea.gmane.org>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>
	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>
	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com>
	<20070215184731.GA20607@ayn.mi.celestial.com>
	<45D5309F.2060406@gmail.com> <er3vo5$to$1@sea.gmane.org>
Message-ID: <7e5ba9220702160400m5a025e98yfec95a023d308c8d@mail.gmail.com>

On 2/16/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> As to standard list behaviour, I don't know of any list thats been
> around for more than say 10 years that uses Reply to send to All.
> This seems to be a very recent thing. (And most of the lists I am
> on have been around for much more than 10 years! :-)
>
> Regards,
>
> Alan G.
>
>
If I remember correctly, LISTSERV did not return replies to the original
poster but to the mailing list you were subscribed to.  LISTSERV, c. 1984,
is the first mailing list software package and was widely used at the time.
  I believe this is still the default behavior.

This is different because the postings are coming from LISTSERV, not the
original sender.  Based on documentation, there is currently an option to
add a reply-to of the original sender; but not all clients honor reply-to
fields.

However, the "standard behavior" at the time was that replies went back to
the mailing list, not to the original sender.
  -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/20070216/201d9445/attachment.htm 

From mabystry at verizon.net  Fri Feb 16 13:32:15 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Fri, 16 Feb 2007 07:32:15 -0500
Subject: [Tutor] New Tutor topic(almost)
In-Reply-To: <er3uge$sap$1@sea.gmane.org>
References: <000501c74fb3$a0b7f860$6601a8c0@xp> <er3uge$sap$1@sea.gmane.org>
Message-ID: <45D5A44F.7020201@verizon.net>

Well, I'm new here and for the most I haven't got a clue as to what I'm doing, however, I thought 
your website was a jewel. Most of it was over my head but sometime in the future I'm sure it will 
become a valuable resource for me. (btw, I'm heading to Borders tonight with my checkbook. Hoping to 
pick up some pyhton for complete n00bs reading)

Keep up the great work, Alan.

Mark

Alan Gauld wrote the following on 2/16/2007 4:45 AM:
> "Alan Gauld" <alan.gauld at freenet.co.uk> wrote in 
> 
>> After a very long delay I finally got some work done on 
>> my networking with sockets topic in my tutorial. There is 
>> still a section to complete but the introductory explanations 
>> and examples are now on the site.
>>
>> http://www.freenetpages.co.uk/hp/alan.gauld/tutsocket.htm
>>
>> If anyone has any feedback I'd love to hear it.
> 
> OK, I finished it, the final address book example is now there too.
> 
> Enjoy,
> 

From arcege at gmail.com  Fri Feb 16 14:14:29 2007
From: arcege at gmail.com (Michael P. Reilly)
Date: Fri, 16 Feb 2007 08:14:29 -0500
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <20070216121209.62719.qmail@web86107.mail.ird.yahoo.com>
References: <20070216121209.62719.qmail@web86107.mail.ird.yahoo.com>
Message-ID: <7e5ba9220702160514p7354ccd4idaeae3b61be34f74@mail.gmail.com>

On 2/16/07, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>
> > However, the "standard behavior" at the time was that
> > replies went back to the mailing list, not to the original sender.
>
> But the mailing list was the original sender so it was all wonderfully
> consistent. Reply  goes to sender only, which happens
> to be the list server...
>
> Ah, the good ol' days :-)
>
> Alan g.
>
> Alan,

The issue is not what the mailing list does, but what the user expects and
should do.  Listserv was the first mailing list system from 23 years ago.
The users expected, as standard behavior, that replies would go to the
mailing list, not to the original sender.  You had made a claim that more
than 10 years ago (when listserv was still in use) that the standard
behavior was that mailing lists was that users would reply to the original
sender.  I'm just offering up one, very well-known example to refute that.

Myself, I'm not a person who cares how the mailing list goes.  I'll adapt.
But it does irk me when "standards" are applied because of misunderstandings
of applications.  For example, the usual convention is that people attach
their comments below the respondent's.  At my work, they have tried to
convince me that the "standard" is to put it above simply because Outlook
does that.

When making arguments, please make the arguments on a technical basis, not
on "this was how it has been done in the past".  If that was the case, then
all the stuff you get in your mailbox isn't "spam" since spam related only
to cross-posting on newsgroups (anyone remember the Spam Wars?).  However,
the general collective has decided to expand the standard definition.

Times change, standards can evolve. Sometimes not for the better.  Make an
argument for keeping the "standards" how they should be technically, not
historically.

  -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/20070216/ef74342f/attachment.htm 

From wolfram.kraus at fen-net.de  Fri Feb 16 14:11:42 2007
From: wolfram.kraus at fen-net.de (Wolfram Kraus)
Date: Fri, 16 Feb 2007 14:11:42 +0100
Subject: [Tutor] how to wirte code In python :str = (a>b?"Yes":"NO")
In-Reply-To: <d9d086320702152301i5c21cbf4yc892409de9b29fe2@mail.gmail.com>
References: <d9d086320702152301i5c21cbf4yc892409de9b29fe2@mail.gmail.com>
Message-ID: <er4aie$5f1$1@sea.gmane.org>

On 16.02.2007 08:01, xiufeng liu wrote:
> Hi, all,
> 
> In python if there is any similar way like in Java, or C++ to express
> the following:
> str = (a>b?"Yes":"NO")
> 
> 
> thanks!

In Python 2.5 you can do the following (untested):

str = "Yes" if a>b else "No"

See: http://docs.python.org/whatsnew/pep-308.html

HTH,
Wolfram


From kent37 at tds.net  Fri Feb 16 14:35:03 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Feb 2007 08:35:03 -0500
Subject: [Tutor] New Tutor topic(almost)
In-Reply-To: <45D5A44F.7020201@verizon.net>
References: <000501c74fb3$a0b7f860$6601a8c0@xp> <er3uge$sap$1@sea.gmane.org>
	<45D5A44F.7020201@verizon.net>
Message-ID: <45D5B307.7010809@tds.net>

Mark Bystry wrote:
> Well, I'm new here and for the most I haven't got a clue as to what I'm doing, however, I thought 
> your website was a jewel. Most of it was over my head but sometime in the future I'm sure it will 
> become a valuable resource for me. (btw, I'm heading to Borders tonight with my checkbook. Hoping to 
> pick up some pyhton for complete n00bs reading)

Look for "Python Programming for the absolute beginner".

Kent


From arcege at gmail.com  Fri Feb 16 15:09:50 2007
From: arcege at gmail.com (Michael P. Reilly)
Date: Fri, 16 Feb 2007 09:09:50 -0500
Subject: [Tutor] how to wirte code In python :str = (a>b?"Yes":"NO")
In-Reply-To: <er4aie$5f1$1@sea.gmane.org>
References: <d9d086320702152301i5c21cbf4yc892409de9b29fe2@mail.gmail.com>
	<er4aie$5f1$1@sea.gmane.org>
Message-ID: <7e5ba9220702160609h6e6a4882r9ca590c5d1cc528@mail.gmail.com>

On 2/16/07, Wolfram Kraus <wolfram.kraus at fen-net.de> wrote:
>
> On 16.02.2007 08:01, xiufeng liu wrote:
> > Hi, all,
> >
> > In python if there is any similar way like in Java, or C++ to express
> > the following:
> > str = (a>b?"Yes":"NO")
> >
> >
> > thanks!
>
> In Python 2.5 you can do the following (untested):
>
> str = "Yes" if a>b else "No"
>
> See: http://docs.python.org/whatsnew/pep-308.html
>
> HTH,
> Wolfram
>

Before 2.5, you could generally write:

str = (a > b) and "Yes" or "No"

  -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/20070216/071d8ca2/attachment-0001.html 

From kent37 at tds.net  Fri Feb 16 15:32:59 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Feb 2007 09:32:59 -0500
Subject: [Tutor] how to wirte code In python :str = (a>b?"Yes":"NO")
In-Reply-To: <7e5ba9220702160609h6e6a4882r9ca590c5d1cc528@mail.gmail.com>
References: <d9d086320702152301i5c21cbf4yc892409de9b29fe2@mail.gmail.com>	<er4aie$5f1$1@sea.gmane.org>
	<7e5ba9220702160609h6e6a4882r9ca590c5d1cc528@mail.gmail.com>
Message-ID: <45D5C09B.4040901@tds.net>

Michael P. Reilly wrote:
> Before 2.5, you could generally write:
> 
> str = (a > b) and "Yes" or "No"

With a significant gotcha that you should definitely understand before 
you use this. For example this will not work as expected:
s = (a > b) and "" or "No"

In [1]: s = True and "" or "No"

In [2]: s
Out[2]: 'No'

because True and "" will always be False.

http://www.effbot.org/pyfaq/is-there-an-equivalent-of-c-s-ternary-operator.htm

Kent


From rschroev_nospam_ml at fastmail.fm  Fri Feb 16 15:44:01 2007
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Fri, 16 Feb 2007 15:44:01 +0100
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <45D58655.1000902@timgolden.me.uk>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<6faf39c90702150749y2e95762ep9dad4ea8e5b7f9bd@mail.gmail.com><20070215184731.GA20607@ayn.mi.celestial.com>	<45D5309F.2060406@gmail.com>	<er3vo5$to$1@sea.gmane.org>
	<45D58655.1000902@timgolden.me.uk>
Message-ID: <er4fvq$qqh$1@sea.gmane.org>

Tim Golden schreef:
> I would take minor issue -- with you, and with the creators
> of Thunderbird which is my current mail client of choice. It
> looks to me as though you're suggesting that the reply-all
> button is there to reply to a list, whereas it seems to me
> to be there to reply to all the recipients in the original
> email, *not* just to reply to a group or other bulk originator.
> Now that's what Thunderbird does: puts Alan Gauld in the To:
> field and tutor at ... in cc: My problem there is that I usually
> don't want to send the originating individual a private copy
> of an email he/she is going to receive from the list in any
> case, so I usually cut-and-paste around so that only the list
> is in To: AFAIK, TB doesn't offer any configurability here,
> neither a reply-to-list button, nor any option to treat a
> list specially on a general reply-to-all.

It's a missing feature in Thunderbird (and some other mail readers that 
call themselves 'modern'), IMO important enough to be called a bug. 
Luckily it seems to be worked on (see 
https://bugzilla.mozilla.org/show_bug.cgi?id=45715 and 
https://bugzilla.mozilla.org/show_bug.cgi?id=233417).

Meanwhile I work around the issue by subscribing to mailing lists 
indirectly via gmane. I like the interface offered by newsgroups better 
anyway for this kind of stuff.

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

Roel Schroeven


From mabystry at verizon.net  Fri Feb 16 16:01:15 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Fri, 16 Feb 2007 10:01:15 -0500
Subject: [Tutor] New Tutor topic(almost)
In-Reply-To: <45D5B307.7010809@tds.net>
References: <000501c74fb3$a0b7f860$6601a8c0@xp> <er3uge$sap$1@sea.gmane.org>
	<45D5A44F.7020201@verizon.net> <45D5B307.7010809@tds.net>
Message-ID: <45D5C73B.6040401@verizon.net>

I'll look for it. Perhaps I should pick up one of the "Dummies" book too.

Mark

Kent Johnson wrote the following on 2/16/2007 8:35 AM:
> Mark Bystry wrote:
>> Well, I'm new here and for the most I haven't got a clue as to what I'm doing, however, I thought 
>> your website was a jewel. Most of it was over my head but sometime in the future I'm sure it will 
>> become a valuable resource for me. (btw, I'm heading to Borders tonight with my checkbook. Hoping to 
>> pick up some pyhton for complete n00bs reading)
> 
> Look for "Python Programming for the absolute beginner".
> 
> Kent
> 
> 

From kent37 at tds.net  Fri Feb 16 16:15:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Feb 2007 10:15:42 -0500
Subject: [Tutor] New Tutor topic(almost)
In-Reply-To: <45D5C73B.6040401@verizon.net>
References: <000501c74fb3$a0b7f860$6601a8c0@xp>
	<er3uge$sap$1@sea.gmane.org>	<45D5A44F.7020201@verizon.net>
	<45D5B307.7010809@tds.net> <45D5C73B.6040401@verizon.net>
Message-ID: <45D5CA9E.70708@tds.net>

Mark Bystry wrote:
> I'll look for it. Perhaps I should pick up one of the "Dummies" book too.

There is a "Python for Dummies"; it is very recent and written by a 
respected member of the Python community. I haven't read it myself though.

Kent


From shadabsayani at yahoo.com  Fri Feb 16 16:19:38 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Fri, 16 Feb 2007 15:19:38 +0000 (GMT)
Subject: [Tutor] Reg Google Web Toolkit and Python
In-Reply-To: <45D5CA9E.70708@tds.net>
Message-ID: <20070216151938.77711.qmail@web38715.mail.mud.yahoo.com>

Hi ,
We have a project where I need to read files store
them in database in the backend.We have done this in
python.Now we decided to use Ajax technique for user
interface.For that we found that GWT is one of the
best toolkits.Now I got a doubt can I interface GWT
with python.
Thanks ,
Shadab.

Send instant messages to your online friends http://uk.messenger.yahoo.com 

From andreas at kostyrka.org  Fri Feb 16 16:20:53 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 16 Feb 2007 16:20:53 +0100
Subject: [Tutor] how to wirte code In python :str = (a>b?"Yes":"NO")
In-Reply-To: <er4aie$5f1$1@sea.gmane.org>
References: <d9d086320702152301i5c21cbf4yc892409de9b29fe2@mail.gmail.com>
	<er4aie$5f1$1@sea.gmane.org>
Message-ID: <20070216152053.GA15485@andi-lap.la.revver.com>

* Wolfram Kraus <wolfram.kraus at fen-net.de> [070216 15:23]:
> On 16.02.2007 08:01, xiufeng liu wrote:
> > Hi, all,
> > 
> > In python if there is any similar way like in Java, or C++ to express
> > the following:
> > str = (a>b?"Yes":"NO")
> > 
> > 
> > thanks!
> 
> In Python 2.5 you can do the following (untested):
> 
> str = "Yes" if a>b else "No"

In earler versions:

((a>b) and "Yes") or "NO"

Andreas

From kent37 at tds.net  Fri Feb 16 16:33:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Feb 2007 10:33:05 -0500
Subject: [Tutor] Reg Google Web Toolkit and Python
In-Reply-To: <20070216151938.77711.qmail@web38715.mail.mud.yahoo.com>
References: <20070216151938.77711.qmail@web38715.mail.mud.yahoo.com>
Message-ID: <45D5CEB1.7010205@tds.net>

Shadab Sayani wrote:
> Hi ,
> We have a project where I need to read files store
> them in database in the backend.We have done this in
> python.Now we decided to use Ajax technique for user
> interface.For that we found that GWT is one of the
> best toolkits.Now I got a doubt can I interface GWT
> with python.

GWT is written in Java so that is probably not the best choice. There is 
a Python port called pyjamas. There are many other AJAX toolkits, you 
might want to pick one that is not written in Java.

Kent


From jason.massey at gmail.com  Fri Feb 16 16:34:23 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Fri, 16 Feb 2007 09:34:23 -0600
Subject: [Tutor] Reg Google Web Toolkit and Python
In-Reply-To: <20070216151938.77711.qmail@web38715.mail.mud.yahoo.com>
References: <45D5CA9E.70708@tds.net>
	<20070216151938.77711.qmail@web38715.mail.mud.yahoo.com>
Message-ID: <7e3eab2c0702160734q68688e90u32204a9a9a9080a0@mail.gmail.com>

Oh, the irony...googling for python and gwt gave me:

http://pyjamas.pyworks.org/



On 2/16/07, Shadab Sayani <shadabsayani at yahoo.com> wrote:
>
> Hi ,
> We have a project where I need to read files store
> them in database in the backend.We have done this in
> python.Now we decided to use Ajax technique for user
> interface.For that we found that GWT is one of the
> best toolkits.Now I got a doubt can I interface GWT
> with python.
> Thanks ,
> Shadab.
>
> Send instant messages to your online friends http://uk.messenger.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/20070216/adea82d3/attachment.htm 

From bizag007 at yahoo.com  Fri Feb 16 16:41:54 2007
From: bizag007 at yahoo.com (ray sa)
Date: Fri, 16 Feb 2007 07:41:54 -0800 (PST)
Subject: [Tutor] control multiple FTP sessions using multiple ip connections
	via different com ports
Message-ID: <914477.72040.qm@web31205.mail.mud.yahoo.com>

Hi Kind people
   
  I have been successful to write an ftp script that logs into a server and collects files. What I would like to do but have no knowledge of is that I would like to run multiple ftp sessions using one laptop with two different connections. What I mean here is that you have a ethernet card connection to the ip world and then you have another connection using your EDGE terminal so in other words you have two ip address and I would like to write a script that controls which ip address to use or with com port to use. I was hoping someone could help to define how to force the ftp script to use the relevant connections on one laptop. You help and guidance will be most appreciated.
   
  Many thanks
   
  Ray

 
---------------------------------
Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070216/295ce8b4/attachment.htm 

From alan.gauld at btinternet.com  Fri Feb 16 17:12:30 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Feb 2007 16:12:30 -0000
Subject: [Tutor] New Tutor topic(almost)
References: <000501c74fb3$a0b7f860$6601a8c0@xp>
	<er3uge$sap$1@sea.gmane.org><45D5A44F.7020201@verizon.net>
	<45D5B307.7010809@tds.net> <45D5C73B.6040401@verizon.net>
Message-ID: <er4l5j$fbg$1@sea.gmane.org>

"Mark Bystry" <mabystry at verizon.net> wrote

> I'll look for it. Perhaps I should pick up one of the "Dummies" book 
> too.

I'm a big fan of Dummies books but not for concepts.
They are great if you want a flying start on a new language
or tool, but only if you already know the concepts.

For example, if you can already program and understand
web technology then the Struts for dummies book is great.
But their Programming for Dummies book didn't impress
me nearly as much. It was too many examples and too
little explanation of *why*...

But they do seem to have captured their powmn little
niche in the market.

Alan G. 



From Barry.Carroll at psc.com  Fri Feb 16 17:49:03 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 16 Feb 2007 08:49:03 -0800
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <mailman.12602.1171634993.32030.tutor@python.org>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595AFB@eugsrv400.psc.pscnet.com>

Greetings:

I just thought I'd throw my own hat into the ring.  I'm trying out my
new, asbestos-free, flame-retardant underwear.  ;^)

> -----Original Message-----
> Date: Fri, 16 Feb 2007 08:14:29 -0500
> From: "Michael P. Reilly" <arcege at gmail.com>
> Subject: Re: [Tutor] Replying to the tutor-list
> To: "ALAN GAULD" <alan.gauld at btinternet.com>
> Cc: Tutor <tutor at python.org>
> Message-ID:
> 	<7e5ba9220702160514p7354ccd4idaeae3b61be34f74 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> On 2/16/07, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> >
> > > However, the "standard behavior" at the time was that
> > > replies went back to the mailing list, not to the original sender.
> >
> > But the mailing list was the original sender so it was all
wonderfully
> > consistent. Reply  goes to sender only, which happens
> > to be the list server...
> >
> > Ah, the good ol' days :-)
> >
> > Alan g.
> >
> > Alan,
> 
> The issue is not what the mailing list does, but what the user expects
and
> should do.  

I agree.  However, it seems to me that the expectation in this case is
divided into two contradictory positions.  (The division seems pretty
even to me, but that's not necessarily a critical point.)

> Listserv was the first mailing list system from 23 years ago.
> The users expected, as standard behavior, that replies would go to the
> mailing list, not to the original sender.  You had made a claim that
more
> than 10 years ago (when listserv was still in use) that the standard
> behavior was that mailing lists was that users would reply to the
original
> sender.  I'm just offering up one, very well-known example to refute
that.

Again, I agree.  That is an excellent counter-example.  To me, it
demonstrates that this division of expectation existed from the
beginning of the technology.  
 
> Myself, I'm not a person who cares how the mailing list goes.  I'll
adapt.
> But it does irk me when "standards" are applied because of
> misunderstandings
> of applications.  For example, the usual convention is that people
attach
> their comments below the respondent's.  At my work, they have tried to
> convince me that the "standard" is to put it above simply because
Outlook
> does that.

Don't get me started on that.  I just got out of a minor fire fight on
another forum over that one. :^(

> When making arguments, please make the arguments on a technical basis,
not
> on "this was how it has been done in the past".  

I would agree with this, too, if this were a technical issue.  But it's
not.  Read on.  

> If that was the case, then
> all the stuff you get in your mailbox isn't "spam" since spam related
only
> to cross-posting on newsgroups (anyone remember the Spam Wars?).
However,
> the general collective has decided to expand the standard definition.
> 
> Times change, standards can evolve. Sometimes not for the better.
Make an
> argument for keeping the "standards" how they should be technically,
not
> historically.
> 

While I agree that appeals to historical authority aren't very helpful
in cases like this, assertions of technical superiority are equally
unproductive.  Again, IMHO, this not a technical issue.  Ring vs. bus
vs. star network topology is a technical issue.  This is an issue of
convenience, which is intensely personal.  The rightness or wrongness of
either position is subjective (purely so, I believe) and technical
discussion does not clarify.  That's why discussions like this so often
turn into religious wars (as this one nearly did a few posts back).  

There is a technical issue that relates, however.  Some posters have
touched on it.  Modern mail and news software should be flexible enough
to accommodate the user's preference in this regard.  A few are,
apparently.  Most are not.  Why not?  What should be done about it?  Who
has a Python implementation that makes the default "Reply to:" behavior
configurable?  Which is the most flexible?  How can it be improved?
These are questions that benefit from technical discussion.  I'd like to
see more posts on these topics, and less on whose personal preference is
"correct".

-Arcege
> --
> There's so many different worlds,
> So many different suns.
> And we have just one world,
> But we live in different ones.
> ------------------------------
> 

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 tavspam at gmail.com  Fri Feb 16 18:14:53 2007
From: tavspam at gmail.com (Thomas)
Date: Fri, 16 Feb 2007 17:14:53 +0000
Subject: [Tutor] regex eats even when not hungry
Message-ID: <493b81e30702160914q41bbe254jac2b903f320c55eb@mail.gmail.com>

I have the following mostly working function to strip the first 4
digit year out of some text. But a leading space confounds it for
years starting 20..:

import re
def getyear(text):
    s = """(?:.*?(19\d\d)|(20\d\d).*?)"""
    p = re.compile(s,re.IGNORECASE|re.DOTALL) #|re.VERBOSE
    y = p.match(text)
    try:
        return y.group(1) or y.group(2)
    except:
        return ''



>>> getyear('2002')
'2002'
>>> getyear(' 2002')
''
>>> getyear(' 1902')
'1902'

A regex of ".*?" means any number of any characters, with a non-greedy
hunger (so to speak) right?

Any ideas on what is causing this to fail?

Many thanks in advance,
Thomas

From kent37 at tds.net  Fri Feb 16 18:27:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Feb 2007 12:27:54 -0500
Subject: [Tutor] regex eats even when not hungry
In-Reply-To: <493b81e30702160914q41bbe254jac2b903f320c55eb@mail.gmail.com>
References: <493b81e30702160914q41bbe254jac2b903f320c55eb@mail.gmail.com>
Message-ID: <45D5E99A.1090804@tds.net>

Thomas wrote:
> I have the following mostly working function to strip the first 4
> digit year out of some text. But a leading space confounds it for
> years starting 20..:
> 
> import re
> def getyear(text):
>     s = """(?:.*?(19\d\d)|(20\d\d).*?)"""
>     p = re.compile(s,re.IGNORECASE|re.DOTALL) #|re.VERBOSE
>     y = p.match(text)
>     try:
>         return y.group(1) or y.group(2)
>     except:
>         return ''
> 
> 
> 
>>>> getyear('2002')
> '2002'
>>>> getyear(' 2002')
> ''
>>>> getyear(' 1902')
> '1902'
> 
> A regex of ".*?" means any number of any characters, with a non-greedy
> hunger (so to speak) right?
> 
> Any ideas on what is causing this to fail?

The | character has very low precedence in a regex. You are matching either
- any number of characters followed by 19xx
or,
- 20xx followed by any number of characters

You could use this instead:
.*?(?:(19\d\d)|(20\d\d)).*?

But why not use p.search(), which will find the string anywhere without 
needing the wildcards? Then your regex could be just
19\d\d|20\d\d

and you return just y.group()

Kent


From Barry.Carroll at psc.com  Fri Feb 16 19:28:02 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 16 Feb 2007 10:28:02 -0800
Subject: [Tutor] Picking Nits in "Learning to Program"
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595AFD@eugsrv400.psc.pscnet.com>

Alan:

This is arguably a minor detail, and not directly related to Python but, hey, I'm a programmer.  Minor details are my stock in trade.  So here goes.  

In "Learning to Program", look at "The Raw Materials", "Real Numbers".  The first sentence, "These are fractions" is technically incorrect, but incomplete.  While it's true that fractions (i.e. rational numbers) are real numbers, there are far more real numbers that cannot be expressed as a ratio of two integers.  Hence the name "Irrational Numbers".  The square root of two is the prime example. (Sorry, can't do the math symbol in Plain Text.)  

You might say something like, "Fractions are examples of real numbers."  

I know, I know.  Strictly speaking, integers are real numbers, too.  But let's not quibble. 8^)

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 rschroev_nospam_ml at fastmail.fm  Sat Feb 17 02:39:35 2007
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 17 Feb 2007 02:39:35 +0100
Subject: [Tutor] Picking Nits in "Learning to Program"
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595AFD@eugsrv400.psc.pscnet.com>
References: <2BBAEE949D384D40A2B851287ADB6A4304595AFD@eugsrv400.psc.pscnet.com>
Message-ID: <er5mcn$uec$1@sea.gmane.org>

Carroll, Barry schreef:
> Alan:
> 
> This is arguably a minor detail, and not directly related to Python
> but, hey, I'm a programmer.  Minor details are my stock in trade.  So
> here goes.
> 
> In "Learning to Program", look at "The Raw Materials", "Real
> Numbers".  The first sentence, "These are fractions" is technically
> incorrect, but incomplete.  While it's true that fractions (i.e.
> rational numbers) are real numbers, there are far more real numbers
> that cannot be expressed as a ratio of two integers.  Hence the name
> "Irrational Numbers".  The square root of two is the prime example.
> (Sorry, can't do the math symbol in Plain Text.)

That's all true, but it's also that true that real numbers as they are 
implemented in computers are not really real numbers. They are 
implemented as binary fractions multiplied by some power of two (just 
like scientific notation, but binary based instead of decimal based). 
Have a look at http://en.wikipedia.org/wiki/IEEE_754 for the details.

That makes them effectively rational numbers or fractions. It's about 
the best approximation for real numbers computers have to offer.

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

Roel Schroeven


From rschroev_nospam_ml at fastmail.fm  Sat Feb 17 02:47:56 2007
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 17 Feb 2007 02:47:56 +0100
Subject: [Tutor] Picking Nits in "Learning to Program"
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595AFD@eugsrv400.psc.pscnet.com>
References: <2BBAEE949D384D40A2B851287ADB6A4304595AFD@eugsrv400.psc.pscnet.com>
Message-ID: <er5msd$veu$1@sea.gmane.org>

Carroll, Barry schreef:
> In "Learning to Program", look at "The Raw Materials", "Real
> Numbers".  The first sentence, "These are fractions" is technically
> incorrect, but incomplete.  While it's true that fractions (i.e.
> rational numbers) are real numbers, there are far more real numbers
> that cannot be expressed as a ratio of two integers.  Hence the name
> "Irrational Numbers".  The square root of two is the prime example.
> (Sorry, can't do the math symbol in Plain Text.)
> 
> You might say something like, "Fractions are examples of real
> numbers."

Notwithstanding my other mail, it might be better to use another term. 
Alan, you already use the name 'floating point numbers' in that section; 
I think it's a bit better to always refer to those numbers by that name, 
and mention 'real numbers' as an alternative name. The opposite of the 
current situation more or less actually.

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

Roel Schroeven


From alan.gauld at btinternet.com  Sat Feb 17 02:48:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Feb 2007 01:48:53 -0000
Subject: [Tutor] Picking Nits in "Learning to Program"
References: <2BBAEE949D384D40A2B851287ADB6A4304595AFD@eugsrv400.psc.pscnet.com>
Message-ID: <er5mua$vio$1@sea.gmane.org>

"Carroll, Barry" <Barry.Carroll at psc.com> wrote

> "Real Numbers".  The first sentence, "These are fractions" is 
> technically incorrect, but incomplete.  

Yep, I thought I'd changed that following a discussion 
with Dick Moores about the same section.

> While it's true that fractions (i.e. rational numbers) 

But here we come to an interesting divergence of opinion. 
You see, in UK Math classes fractions cover more than 
the rational numbers. A fraction is any number which is 
not a whole number(*). That's their definition in English (here) 
too. Of course that still makes my Real numbers wrong 
since, as you say, Reals include both whole numbers and 
fractions. 

(*) Thus we have decimal fractions...Blood fractions, 
atomic fractions etc etc...

> real numbers that cannot be expressed as a ratio of 
> two integers.  Hence the name "Irrational Numbers".  

I prefer rational and irrational as definitions because they 
mean the same both sides of the pond!

> "Fractions are examples of real numbers."  

And that's almost what I thought I'd said....

It seems I didn't upload the changed version. 
It now says of Reals: 'These include fractions'

I'll get the changed version uploaded over the weekend.
I'm happy for the nitpicking, because I do try to be very 
careful about my terminology, because as you say it is 
extremely important to be precise in programming. 
Occasionally we get these minor trans-Atlantic glitches 
but usually it's consistent :-)

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


From alan.gauld at btinternet.com  Sat Feb 17 10:42:08 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Feb 2007 09:42:08 -0000
Subject: [Tutor] Picking Nits in "Learning to Program"
References: <2BBAEE949D384D40A2B851287ADB6A4304595AFD@eugsrv400.psc.pscnet.com>
	<er5msd$veu$1@sea.gmane.org>
Message-ID: <er6ill$lf8$1@sea.gmane.org>


"Roel Schroeven" <rschroev_nospam_ml at fastmail.fm> wrote

> Notwithstanding my other mail, it might be better to use another 
> term.
> Alan, you already use the name 'floating point numbers' in that 
> section;

I did consider that but since some programming languages specifically
have a "Real" type(Pascal, Modula, etc) I decided to leave it as it 
was.
Even though the 'Real' is really a Float...

> I think it's a bit better to always refer to those numbers by that 
> name,
> and mention 'real numbers' as an alternative name. The opposite of 
> the
> current situation more or less actually.

Yeah, That might be a better way to deal with it.
I'll consider a rewrite of that section to that style next time 
through.
For now its not top of my priority list! :-)

Alan G. 



From johan at accesstel.co.za  Sat Feb 17 11:23:20 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Sat, 17 Feb 2007 12:23:20 +0200
Subject: [Tutor] control multiple FTP sessions using multiple ip
	connectionsvia different com ports
In-Reply-To: <914477.72040.qm@web31205.mail.mud.yahoo.com>
Message-ID: <200702171017.l1HAHaLs020855@mail.mtn.co.za>

Well, I'm not a great expert on this, but in the FTPlib, it makes use of
sockets.
 
Maybe Alan can comment if socket.getaddrinfo(host, port) can be manipulated
to change the outgoing interface.
 
Good topic.
 
Johan

   _____  

From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of ray sa
Sent: 16 February 2007 05:42 PM
To: tutor at python.org
Subject: [Tutor] control multiple FTP sessions using multiple ip
connectionsvia different com ports


Hi Kind people
 
I have been successful to write an ftp script that logs into a server and
collects files. What I would like to do but have no knowledge of is that I
would like to run multiple ftp sessions using one laptop with two different
connections. What I mean here is that you have a ethernet card connection to
the ip world and then you have another connection using your EDGE terminal
so in other words you have two ip address and I would like to write a script
that controls which ip address to use or with com port to use. I was hoping
someone could help to define how to force the ftp script to use the relevant
connections on one laptop. You help and guidance will be most appreciated.
 
Many thanks
 
Ray


   _____  

HYPERLINK
"http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolbar/fea
tures/mail/"Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives.HYPERLINK
"http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolbar/fea
tures/mail/" Check it out.


--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date: 2007/02/13
10:01 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date: 2007/02/13
10:01 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070217/fcb9fd7d/attachment.html 

From alan.gauld at btinternet.com  Sat Feb 17 18:55:03 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Feb 2007 17:55:03 -0000
Subject: [Tutor] control multiple FTP sessions using multiple ip
	connectionsvia different com ports
References: <914477.72040.qm@web31205.mail.mud.yahoo.com>
Message-ID: <er7fhs$5ga$1@sea.gmane.org>


"ray sa" <bizag007 at yahoo.com> wrote 

>  I have been successful to write an ftp script that logs 
> into a server and collects files. 

> ...I would like to run multiple ftp sessions using one laptop 
> with two different connections. 

Do you mean you want the server on the laptop accepting 
using two connections or do you mean that you want
the client on the laptop and have different sessions sending 
outgoing requests to the server via two different IP addresses?

If the former its easy, just set up two servers, one on each 
IP address. The port will nbe the same on both, ISTR its port 
21 for ftp?

If you want to specify which IP address you send the 
client request from, I'm afraid I have no idea how you specify 
that. I've only ever used multiple network cards at the server 
end!

> another connection using your EDGE terminal 

As a matter of interest what is an EDGE terminal? 
A new term for me...

> I would like to write a script that controls which ip 
> address to use or with com port to use. 

Until we know which end you mean its hard to hgive more 
specific advice.

Alan G.


From bizag007 at yahoo.com  Sun Feb 18 03:16:27 2007
From: bizag007 at yahoo.com (ray sa)
Date: Sat, 17 Feb 2007 18:16:27 -0800 (PST)
Subject: [Tutor] control multiple FTP sessions using multiple ip
	connectionsvia different com ports
In-Reply-To: <er7fhs$5ga$1@sea.gmane.org>
Message-ID: <213033.60687.qm@web31204.mail.mud.yahoo.com>

Hi Alan et al
   
  Many thanks for your time on this.
   
  I was referring to the client end. 
   
  An EDGE terminal is a phone that has the capability of connecting to the internet. We use mobile phones to make a voice call that make use of a circuit switched connection. By using a GPRS connection we can use the mobile device to connect to the packet switched domain. You might have heard about making data connection using your phone like GPRS, 3G etc. EDGE is just faster than a GPRS connection and 3G is supposedly faster than GPRS and EDGE. 
   
  May be I can give you more information about what I am trying to do. So you can understand what I am trying to achieve. Basically, I am trying to decide whether I should change my ADSL fixed solution to a higher speed connection using a mobile solution. Where I live the mobile operator is offering a mobile solution which is cheaper than my fixed solution
.and is faster than my ADSL connection, please read on
   
  I have my ADSL broadband connection to my service provider that I use to connect to the internet. I have just bought a GPRS/EDGE/3G terminal and wanted to benchmark the speed I am getting by using my mobile device as opposed to my fixed connection.
   
  My desktop machine is connected to my ADSL provider using a USB modem which is assigned a particular COM port on my machine. Then I have connected my mobile handset also using a USB connection connected to a different COM port.
   
  Now I have two ip addresses
   
    
   ADSL ? COM port 4 with ip addres from my ADSL service provider  
   Mobile Handset ? COM port 5 with another ip address from my mobile provider
   
  I have written a script that connects to a ftp server within my home country and downloads a file. But this script uses one of the connections above. There must be away to tell the script and control which connection to use. So I can get to see real time which connection is faster. So I can run the script pointing to one IP address and at the same time run another script using the other connection. 
   
  I think there must be a method that finds out which connection is connected to which com port and then in my script I need to point towards that connection so my script knows which channel to use when downloading the file.
   
  I hope this helps sorry for too much text couldn?t really find a simpler way to explain this. 
   
  Once again I really appreciate the help on this forum...../Ray
  

Alan Gauld <alan.gauld at btinternet.com> wrote:
  
"ray sa" wrote 

> I have been successful to write an ftp script that logs 
> into a server and collects files. 

> ...I would like to run multiple ftp sessions using one laptop 
> with two different connections. 

Do you mean you want the server on the laptop accepting 
using two connections or do you mean that you want
the client on the laptop and have different sessions sending 
outgoing requests to the server via two different IP addresses?

If the former its easy, just set up two servers, one on each 
IP address. The port will nbe the same on both, ISTR its port 
21 for ftp?

If you want to specify which IP address you send the 
client request from, I'm afraid I have no idea how you specify 
that. I've only ever used multiple network cards at the server 
end!

> another connection using your EDGE terminal 

As a matter of interest what is an EDGE terminal? 
A new term for me...

> I would like to write a script that controls which ip 
> address to use or with com port to use. 

Until we know which end you mean its hard to hgive more 
specific advice.

Alan G.

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


 
---------------------------------
No need to miss a message. Get email on-the-go 
with Yahoo! Mail for Mobile. Get started.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070217/26ed3915/attachment.html 

From alan.gauld at btinternet.com  Sun Feb 18 09:57:28 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 18 Feb 2007 08:57:28 -0000
Subject: [Tutor] control multiple FTP sessions using multiple
	ipconnectionsvia different com ports
References: <er7fhs$5ga$1@sea.gmane.org>
	<213033.60687.qm@web31204.mail.mud.yahoo.com>
Message-ID: <er94du$rpj$1@sea.gmane.org>

"ray sa" <bizag007 at yahoo.com> wrote 

>   An EDGE terminal is a phone that has the capability of 
> connecting to the internet. 
> ...EDGE is just faster than a GPRS connection and 3G is 
> supposedly faster than GPRS and EDGE. 

Thanks. I'm familiar with GPRS and 3G but never heard of EDGE.
Looks like time I did some research...
   
>  I have written a script that connects to a ftp server within 
> my home country and downloads a file. 

OK, In that case you speed will be governed by many things:
1) The slowest link between you and the server
2) The queue size at the server
3) The speed of the server

Using the Internet to guage the speed of your connection 
is not a very useful test unless you repeat it many times 
at different times of day etc and take an average.

Even when I only had 512K broadband I rarely gor that 
speed on long internet connections because the links 
elsewhere or the destination were busy.

Now I have 8M broadband I still often only get 300K or 
less on an internet connection to the U?S for example.
In other words the increased bandwidth does not translate
directly to faster speeds for long connections. Once a 
connection is established - like your ftp session - then 
downloads are faster so its ot a totally useless test, 
but it may not accurately reflect your connection speeds!

Can you get access to a local server at your ISP? 
Download the same file from there? - You may have 
to upload it first! That would be a better test of your 
end of the link. And you wouldn't need to run both 
connections together, just time several download 
sessions to each ISP and average the times.

> There must be away to tell the script and control 
> which connection to use.

But this is the real question, and I confess I'm not sure
how you do it. I will have a dig around though, because 
you have aroused my interest!

>  I hope this helps sorry for too much text couldn't 
> really find a simpler way to explain this. 

No its fine. Having the context uis always helpful.

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


From kubota2550 at gmail.com  Sun Feb 18 15:38:18 2007
From: kubota2550 at gmail.com (kubota2550 at gmail.com)
Date: Sun, 18 Feb 2007 09:38:18 -0500
Subject: [Tutor] Error when calling a class
Message-ID: <5900d730702180638k174ef77cs8fcc31f17f973236@mail.gmail.com>

I'm learning about creating classes and have created the simple class below:


class Temperature (object):

    def fahrenheit(self):
        return 32 + (1.8 * self.celsius)


d = Temperature()

d.celsius = float(input())
print d.fahrenheit()



This works fine stand-alone but I can't get it to work when I try to call it
from another program.  This program is called classctof and the call program
is:





import classctof

y=classctof.fahrenheit(1)

print y



What am I doing wrong to get it to pass the answer back to the calling
program?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070218/0fa8b04b/attachment.html 

From rikard.bosnjakovic at gmail.com  Sun Feb 18 16:04:22 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sun, 18 Feb 2007 16:04:22 +0100
Subject: [Tutor] Error when calling a class
In-Reply-To: <5900d730702180638k174ef77cs8fcc31f17f973236@mail.gmail.com>
References: <5900d730702180638k174ef77cs8fcc31f17f973236@mail.gmail.com>
Message-ID: <d9e88eaf0702180704p176da404qfcdd7f1d0322be0a@mail.gmail.com>

On 2/18/07, kubota2550 at gmail.com <kubota2550 at gmail.com> wrote:

> import classctof
> y=classctof.fahrenheit(1)
> print y
>
> What am I doing wrong to get it to pass the answer back to the calling
> program?

You need to instancify the class first before calling its methods:


import classctof

# make an instance
y = classctof.Temperature()

# add the property. it's usually better to let the method handle this
y.celcius = 42

# convert
f = y.fahrenheit()




-- 
- Rikard.

From kent37 at tds.net  Sun Feb 18 18:47:22 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Feb 2007 12:47:22 -0500
Subject: [Tutor] Error when calling a class
In-Reply-To: <d9e88eaf0702180704p176da404qfcdd7f1d0322be0a@mail.gmail.com>
References: <5900d730702180638k174ef77cs8fcc31f17f973236@mail.gmail.com>
	<d9e88eaf0702180704p176da404qfcdd7f1d0322be0a@mail.gmail.com>
Message-ID: <45D8912A.50700@tds.net>

Rikard Bosnjakovic wrote:
> On 2/18/07, kubota2550 at gmail.com <kubota2550 at gmail.com> wrote:
> 
>> import classctof
>> y=classctof.fahrenheit(1)
>> print y
>>
>> What am I doing wrong to get it to pass the answer back to the calling
>> program?
> 
> You need to instancify the class first before calling its methods:
> 
> 
> import classctof
> 
> # make an instance
> y = classctof.Temperature()
> 
> # add the property. it's usually better to let the method handle this
> y.celcius = 42

The __init__() method, in particular:
class Temperature(object):
   def __init__(self, celcius):
     self.celcius = celcius
etc.

But in this example there doesn't seem to be any need fo a class to hold 
this function. You could make a standalone function 
celciusToFahrenheit() that takes the celcius temperature as a parameter 
and returns the fahrenheit temperature.

Kent


From dkuhlman at rexx.com  Sun Feb 18 20:10:08 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 18 Feb 2007 11:10:08 -0800
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <45D59555.9080105@timgolden.me.uk>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>
	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>
	<45D5309F.2060406@gmail.com> <er3vo5$to$1@sea.gmane.org>
	<45D58655.1000902@timgolden.me.uk> <45D591A5.3010309@tds.net>
	<45D59555.9080105@timgolden.me.uk>
Message-ID: <20070218191008.GA67322@cutter.rexx.com>

On Fri, Feb 16, 2007 at 11:28:21AM +0000, Tim Golden wrote:
> Kent Johnson wrote:
> > Tim Golden wrote:
> >> field and tutor at ... in cc: My problem there is that I usually
> >> don't want to send the originating individual a private copy
> >> of an email he/she is going to receive from the list in any
> >> case, so I usually cut-and-paste around so that only the list
> >> is in To: AFAIK, TB doesn't offer any configurability here,
> >> neither a reply-to-list button, nor any option to treat a
> >> list specially on a general reply-to-all.

MailMan provides an administrative option to remove duplicates:

    "Filter out duplicate messages to list members (if possible)"

I believe that it is on by default.

Am I right that, if set, this eliminates your problem?

> > 
> > I use TB too; if you reply-all and just delete the originator from To: 
> > (leaving the list as Cc:) it works fine. Though I have started leaving 
> > the originator in as some people seem to prefer that.
> 
> Thanks for that; (testing it out on this post). My issue is that my 
> procmail filter doesn't seem to pick up the list when it's cced.
> But that's for me to sort out it :)

Maybe a procmail rule something like this:

    :0:
    * ^(To|Cc):.*tutor at python.org
    tutor-python-folder

Note the Cc.

Dave


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

From mail at timgolden.me.uk  Sun Feb 18 20:28:09 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Sun, 18 Feb 2007 19:28:09 +0000
Subject: [Tutor] Replying to the tutor-list
In-Reply-To: <20070218191008.GA67322@cutter.rexx.com>
References: <242792.57713.qm@web86111.mail.ird.yahoo.com>	<6faf39c90702150748o5cc24681lb5784b04e074c2be@mail.gmail.com>	<45D5309F.2060406@gmail.com>
	<er3vo5$to$1@sea.gmane.org>	<45D58655.1000902@timgolden.me.uk>
	<45D591A5.3010309@tds.net>	<45D59555.9080105@timgolden.me.uk>
	<20070218191008.GA67322@cutter.rexx.com>
Message-ID: <45D8A8C9.6000403@timgolden.me.uk>

Dave Kuhlman wrote:
> On Fri, Feb 16, 2007 at 11:28:21AM +0000, Tim Golden wrote:
>> Kent Johnson wrote:
>>> Tim Golden wrote:
>>>> field and tutor at ... in cc: My problem there is that I usually
>>>> don't want to send the originating individual a private copy
>>>> of an email he/she is going to receive from the list in any
>>>> case, so I usually cut-and-paste around so that only the list
>>>> is in To: AFAIK, TB doesn't offer any configurability here,
>>>> neither a reply-to-list button, nor any option to treat a
>>>> list specially on a general reply-to-all.
> 
> MailMan provides an administrative option to remove duplicates:
> 
>     "Filter out duplicate messages to list members (if possible)"
> 
> I believe that it is on by default.
> 
> Am I right that, if set, this eliminates your problem?

Thanks very much for that info. Yes, it's not that I've received
irate messages from people who've received a message twice! More
that it "feels" untidy, but I suspect that you're right and that
any real problem is neatly solved by Mailman.

>> Thanks for that; (testing it out on this post). My issue is that my 
>> procmail filter doesn't seem to pick up the list when it's cced.
>> But that's for me to sort out it :)
> 
> Maybe a procmail rule something like this:
> 
>     :0:
>     * ^(To|Cc):.*tutor at python.org
>     tutor-python-folder
> 
> Note the Cc.

I'm actually using the List-Id header:

:0:
* ^List-Id:.*tutor.python.org
IN-lists

so I'm surprised it fell through; I would expect the
List-Id to appear in the headers anyway. If it happens
again, I'll look more closely at the headers. It hasn't
yet. Thanks for the hint, though.

TJG

From janos.juhasz at VELUX.com  Sun Feb 18 21:47:44 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sun, 18 Feb 2007 21:47:44 +0100
Subject: [Tutor] report service
Message-ID: <OF5F306DE6.CA601785-ONC1257286.006E1D93-C1257286.00723BA4@velux.com>

Dear All!

May someone recommend any simple solution to distribute some dozen 
parametrizable sql reports 
for some dozen users with a minimal access controll.
Some kind of charting possibilty needed, but I needn't web-based front 
end.


Yours sincerely,
______________________________
J?nos Juh?sz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070218/560bd332/attachment.html 

From kent37 at tds.net  Sun Feb 18 23:32:02 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Feb 2007 17:32:02 -0500
Subject: [Tutor] report service
In-Reply-To: <OF5F306DE6.CA601785-ONC1257286.006E1D93-C1257286.00723BA4@velux.com>
References: <OF5F306DE6.CA601785-ONC1257286.006E1D93-C1257286.00723BA4@velux.com>
Message-ID: <45D8D3E2.7000306@tds.net>

J?nos Juh?sz wrote:
> 
> Dear All!
> 
> May someone recommend any simple solution to distribute some dozen 
> parametrizable sql reports
> for some dozen users with a minimal access controll.
> Some kind of charting possibilty needed, but I needn't web-based front end.

I'm not sure I understand your requirements. Do you want a way for a 
dozen users to be able to create reports from a database, where they 
select some parameters and create the report on demand?

Dabo might be useful for that: http://dabodev.com/
The docs are kind of sparse, I think the screencasts are the best way to 
get started. I haven't used this myself but I know some people like it a 
lot.

Kent


From kent37 at tds.net  Mon Feb 19 02:28:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Feb 2007 20:28:45 -0500
Subject: [Tutor] Follow Up
In-Reply-To: <5900d730702181718v78b5c55bub4523d82002c5473@mail.gmail.com>
References: <5900d730702181718v78b5c55bub4523d82002c5473@mail.gmail.com>
Message-ID: <45D8FD4D.6070801@tds.net>

kubota2550 at gmail.com wrote:
> I thought that I would be able to treat this like one of the standard
> 
libraries (ie random) where I just include the random lib and then use a
command such as random.randrange(x,y). Will this not work with a custom
class?

Yes you can do that with a custom class or with a plain function. With a 
class you have to import and instantiate the class as Rikard showed.

Kent

PS Please respond to the list, not to me personally.

> 
> 
> Rikard Bosnjakovic wrote:
>>/ On 2/18/07, kubota2550 at gmail.com <http://mail.python.org/mailman/listinfo/tutor> <kubota2550 at gmail.com
>  <http://mail.python.org/mailman/listinfo/tutor>> wrote:
> />/ 
> />>/ import classctof
> />>/ y=classctof.fahrenheit(1)
> />>/ print y
> />>/
> />>/ What am I doing wrong to get it to pass the answer back to the calling
> 
> />>/ program?
> />/ 
> />/ You need to instancify the class first before calling its methods:
> />/ 
> />/ 
> />/ import classctof
> />/ 
> />/
>  # make an instance
> />/ y = classctof.Temperature()
> />/ 
> />/ # add the property. it's usually better to let the method handle this
> />/ y.celcius = 42
> /
> The __init__() method, in particular:
> 
> class Temperature(object):
>    def __init__(self, celcius):
>      self.celcius = celcius
> etc.
> 
> But in this example there doesn't seem to be any need fo a class to hold 
> this function. You could make a standalone function 
> 
> celciusToFahrenheit() that takes the celcius temperature as a parameter 
> and returns the fahrenheit temperature.
> 
> Kent
> 



From johan at accesstel.co.za  Mon Feb 19 06:32:07 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Mon, 19 Feb 2007 07:32:07 +0200
Subject: [Tutor] control multiple FTP sessions using multiple
	ipconnectionsvia different com ports
In-Reply-To: <213033.60687.qm@web31204.mail.mud.yahoo.com>
Message-ID: <20070219052557.5539A16777@mail.accesstel.co.za>

Will it be possible to disconnect one of the links during your test and
reconnect it and disconnect the other connection once the ftp test is
finished on the first connection? This way it will force the test script to
use the active route to the internet.
 
Not the most elegant way, but something to look at in the mean time.
 
Johan

   _____  

From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of ray sa
Sent: 18 February 2007 04:16 AM
To: Alan Gauld; tutor at python.org
Subject: Re: [Tutor] control multiple FTP sessions using multiple
ipconnectionsvia different com ports


Hi Alan et al
 
Many thanks for your time on this.
 
I was referring to the client end. 
 
An EDGE terminal is a phone that has the capability of connecting to the
internet. We use mobile phones to make a voice call that make use of a
circuit switched connection. By using a GPRS connection we can use the
mobile device to connect to the packet switched domain. You might have heard
about making data connection using your phone like GPRS, 3G etc. EDGE is
just faster than a GPRS connection and 3G is supposedly faster than GPRS and
EDGE. 
 
May be I can give you more information about what I am trying to do. So you
can understand what I am trying to achieve. Basically, I am trying to decide
whether I should change my ADSL fixed solution to a higher speed connection
using a mobile solution. Where I live the mobile operator is offering a
mobile solution which is cheaper than my fixed solution?.and is faster than
my ADSL connection, please read on
 
I have my ADSL broadband connection to my service provider that I use to
connect to the internet. I have just bought a GPRS/EDGE/3G terminal and
wanted to benchmark the speed I am getting by using my mobile device as
opposed to my fixed connection.
 
My desktop machine is connected to my ADSL provider using a USB modem which
is assigned a particular COM port on my machine. Then I have connected my
mobile handset also using a USB connection connected to a different COM
port.
 
Now I have two ip addresses
 

1.	ADSL ? COM port 4 with ip addres from my ADSL service provider 

2.	Mobile Handset ? COM port 5 with another ip address from my mobile
provider

 
I have written a script that connects to a ftp server within my home country
and downloads a file. But this script uses one of the connections above.
There must be away to tell the script and control which connection to use.
So I can get to see real time which connection is faster. So I can run the
script pointing to one IP address and at the same time run another script
using the other connection. 
 
I think there must be a method that finds out which connection is connected
to which com port and then in my script I need to point towards that
connection so my script knows which channel to use when downloading the
file.
 
I hope this helps sorry for too much text couldn?t really find a simpler way
to explain this. 
 
Once again I really appreciate the help on this forum...../Ray


Alan Gauld <alan.gauld at btinternet.com> wrote:


"ray sa" wrote 

> I have been successful to write an ftp script that logs 
> into a server and collects files. 

> ...I would like to run multiple ftp sessions using one laptop 
> with two different connections. 

Do you mean you want the server on the laptop accepting 
using two connections or do you mean that you want
the client on the laptop and have different sessions sending 
outgoing requests to the server via two different IP addresses?

If the former its easy, just set up two servers, one on each 
IP address. The port will nbe the same on both, ISTR its port 
21 for ftp?

If you want to specify which IP address you send the 
client request from, I'm afraid I have no idea how you specify 
that. I've only ever used multiple network cards at the server 
end!

> another connection using your EDGE terminal 

As a matter of interest what is an EDGE terminal? 
A new term for me...

> I would like to write a script that controls which ip 
> address to use or with com port to use. 

Until we know which end you mean its hard to hgive more 
specific advice.

Alan G.

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




   _____  

No need to miss a message. HYPERLINK
"http://us.rd.yahoo.com/evt=43910/*http://mobile.yahoo.com/mail"Get email
on-the-go 
with Yahoo! Mail for Mobile. HYPERLINK
"http://us.rd.yahoo.com/evt=43910/*http://mobile.yahoo.com/mail"Get started.


--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date: 2007/02/13
10:01 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/edccf74c/attachment-0001.html 

From janos.juhasz at VELUX.com  Mon Feb 19 10:23:11 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Mon, 19 Feb 2007 10:23:11 +0100
Subject: [Tutor] report service
In-Reply-To: <45D8D3E2.7000306@tds.net>
Message-ID: <OFF10862D2.A7FEF41F-ONC1257287.0027D7ED-C1257287.00338F85@velux.com>

Dear Kent,


> > May someone recommend any simple solution to distribute some dozen
> > parametrizable sql reports
> > for some dozen users with a minimal access controll.
> > Some kind of charting possibilty needed, but I needn't web-based front 
end.

> I'm not sure I understand your requirements. Do you want a way for a
> dozen users to be able to create reports from a database, where they
> select some parameters and create the report on demand?

Currently I have some crystal reports, some dozen excel tables with simple 
or complicated 
database queries and some delphi programs with some grids and sometimes 
with charts. 
All of these 'reports' and it's contents are managed by the IT department.
My dream to have a central repository of database reports, 
organized based on the workflow and controlled by the controlling 
department.
The distribution can be made by filesystem level (each report a separate 
file),
or by application level (the report manager shows a tree with the 
accessible reports).

The candidates are till now:
 crystal report server
 ms reporting services
 commercial reportlab



Yours sincerely,
______________________________
J?nos Juh?sz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/ae6e19ba/attachment.html 

From rdm at rcblue.com  Mon Feb 19 10:45:09 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 19 Feb 2007 01:45:09 -0800
Subject: [Tutor] What is the augmented assignment operator "^="
Message-ID: <20070219094524.10B1F1E4006@bag.python.org>

The docs list it at <http://docs.python.org/ref/augassign.html>, and 
send you to <http://docs.python.org/ref/primaries.html#primaries>, 
which seems a dead end.

I've tried "^=" out a bit:

 >>> n = 5
 >>> n ^= 8
 >>> n
13
 >>> n ^= 8
 >>> n
5
 >>> n ^= 8
 >>> n
13
 >>> n ^= 8
 >>> n
5

and get that strange alternating behavior. Can someone explain?  And 
while at it, please also explain "&=" and "|=".

Thanks,

Dick Moores


From bizag007 at yahoo.com  Mon Feb 19 10:53:58 2007
From: bizag007 at yahoo.com (ray sa)
Date: Mon, 19 Feb 2007 01:53:58 -0800 (PST)
Subject: [Tutor] control multiple FTP sessions using multiple
	ipconnectionsvia different com ports
In-Reply-To: <20070219052557.5539A16777@mail.accesstel.co.za>
Message-ID: <728330.93619.qm@web31203.mail.mud.yahoo.com>

Hi
   
  Well now I have configured an old machine in the garage to run at the same time. 
   
  I would really like to find out how to do this as it must be possible. I have been googling like mad and can't find how. Kind of frustrating when you don't know how. At the same time a challenge to seek.
   
  I am kind of hoping that someone on this forum will know how. In the mean time I can continue with my testing.
   
  Many thanks for your help; really appreciate it.
   
  /Ray

Johan Geldenhuys <johan at accesstel.co.za> wrote:
      Will it be possible to disconnect one of the links during your test and reconnect it and disconnect the other connection once the ftp test is finished on the first connection? This way it will force the test script to use the active route to the internet.
   
  Not the most elegant way, but something to look at in the mean time.
   
  Johan

    
---------------------------------
  From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of ray sa
Sent: 18 February 2007 04:16 AM
To: Alan Gauld; tutor at python.org
Subject: Re: [Tutor] control multiple FTP sessions using multiple ipconnectionsvia different com ports


  
  Hi Alan et al
   
  Many thanks for your time on this.
   
  I was referring to the client end. 
   
  An EDGE terminal is a phone that has the capability of connecting to the internet. We use mobile phones to make a voice call that make use of a circuit switched connection. By using a GPRS connection we can use the mobile device to connect to the packet switched domain. You might have heard about making data connection using your phone like GPRS, 3G etc. EDGE is just faster than a GPRS connection and 3G is supposedly faster than GPRS and EDGE. 
   
  May be I can give you more information about what I am trying to do. So you can understand what I am trying to achieve. Basically, I am trying to decide whether I should change my ADSL fixed solution to a higher speed connection using a mobile solution. Where I live the mobile operator is offering a mobile solution which is cheaper than my fixed solution
.and is faster than my ADSL connection, please read on
   
  I have my ADSL broadband connection to my service provider that I use to connect to the internet. I have just bought a GPRS/EDGE/3G terminal and wanted to benchmark the speed I am getting by using my mobile device as opposed to my fixed connection.
   
  My desktop machine is connected to my ADSL provider using a USB modem which is assigned a particular COM port on my machine. Then I have connected my mobile handset also using a USB connection connected to a different COM port.
   
  Now I have two ip addresses
   
    
   ADSL ? COM port 4 with ip addres from my ADSL service provider   
   Mobile Handset ? COM port 5 with another ip address from my mobile provider
   
  I have written a script that connects to a ftp server within my home country and downloads a file. But this script uses one of the connections above. There must be away to tell the script and control which connection to use. So I can get to see real time which connection is faster. So I can run the script pointing to one IP address and at the same time run another script using the other connection. 
   
  I think there must be a method that finds out which connection is connected to which com port and then in my script I need to point towards that connection so my script knows which channel to use when downloading the file.
   
  I hope this helps sorry for too much text couldn?t really find a simpler way to explain this. 
   
  Once again I really appreciate the help on this forum...../Ray
  

Alan Gauld <alan.gauld at btinternet.com> wrote:
  
"ray sa" wrote 

> I have been successful to write an ftp script that logs 
> into a server and collects files. 

> ...I would like to run multiple ftp sessions using one laptop 
> with two different connections. 

Do you mean you want the server on the laptop accepting 
using two connections or do you mean that you want
the client on the laptop and have different sessions sending 
outgoing requests to the server via two different IP addresses?

If the former its easy, just set up two servers, one on each 
IP address. The port will nbe the same on both, ISTR its port 
21 for ftp?

If you want to specify which IP address you send the 
client request from, I'm afraid I have no idea how you specify 
that. I've only ever used multiple network cards at the server 
end!

> another connection using your EDGE terminal 

As a matter of interest what is an EDGE terminal? 
A new term for me...

> I would like to write a script that controls which ip 
> address to use or with com port to use. 

Until we know which end you mean its hard to hgive more 
specific advice.

Alan G.

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

    
---------------------------------
  No need to miss a message. Get email on-the-go 
with Yahoo! Mail for Mobile. Get started.
  --
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date: 2007/02/13 10:01 PM

  

  --
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18 04:35 PM

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


 
---------------------------------
It's here! Your new message!
Get new email alerts with the free Yahoo! Toolbar.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/dabd9fa8/attachment.htm 

From rikard.bosnjakovic at gmail.com  Mon Feb 19 11:13:57 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 19 Feb 2007 11:13:57 +0100
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <20070219094524.10B1F1E4006@bag.python.org>
References: <20070219094524.10B1F1E4006@bag.python.org>
Message-ID: <d9e88eaf0702190213m59cb6a7ahdc53ef63df2a083a@mail.gmail.com>

On 2/19/07, Dick Moores <rdm at rcblue.com> wrote:

> I've tried "^=" out a bit:
[...]
> and get that strange alternating behavior. Can someone explain?
> And while at it, please also explain "&=" and "|=".

^ is XOR, & is AND, | is OR, all bitwise.

You can read more about them here: http://www.somacon.com/p125.php
under "C bitwise operators".


-- 
- Rikard.

From andreengels at gmail.com  Mon Feb 19 11:17:07 2007
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 19 Feb 2007 11:17:07 +0100
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <20070219094524.10B1F1E4006@bag.python.org>
References: <20070219094524.10B1F1E4006@bag.python.org>
Message-ID: <6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.com>

2007/2/19, Dick Moores <rdm at rcblue.com>:
>
> The docs list it at <http://docs.python.org/ref/augassign.html>, and
> send you to <http://docs.python.org/ref/primaries.html#primaries>,
> which seems a dead end.
>
> I've tried "^=" out a bit:
>
> >>> n = 5
> >>> n ^= 8
> >>> n
> 13
> >>> n ^= 8
> >>> n
> 5
> >>> n ^= 8
> >>> n
> 13
> >>> n ^= 8
> >>> n
> 5
>
> and get that strange alternating behavior. Can someone explain?  And
> while at it, please also explain "&=" and "|=".
>

To understand these operators, you will have to think of the numbers as
binary numbers. Look at the digits. For two numbers x and y, x^y is the
effect of doing an exclusive or on all digits (that is, 0^1 = 1^0 = 1 and
0^0 = 1^1 = 0), & of doing an and (1&1 = 1, 1&0=0&1=0&0=0) and | is an or on
all digits (1|1=1|0=0|1 = 1, 0|0 = 0).

So 5^8 = 110 ^ 1000 = 0110 ^ 1000 = 1110 = 13
and 13^8 = 1110 ^ 1000 = 0110 = 5



-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/0ca2aed0/attachment-0001.htm 

From kent37 at tds.net  Mon Feb 19 12:16:16 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Feb 2007 06:16:16 -0500
Subject: [Tutor] control multiple FTP sessions using
 multiple	ipconnectionsvia different com ports
In-Reply-To: <728330.93619.qm@web31203.mail.mud.yahoo.com>
References: <728330.93619.qm@web31203.mail.mud.yahoo.com>
Message-ID: <45D98700.6030006@tds.net>

ray sa wrote:
> Hi
>  
> Well now I have configured an old machine in the garage to run at the 
> same time.
>  
> I would really like to find out how to do this as it must be possible. I 
> have been googling like mad and can't find how. Kind of frustrating when 
> you don't know how. At the same time a challenge to seek.

You might want to ask on comp.lang.python since no one here seems to 
know the answer.

Kent


From rdm at rcblue.com  Mon Feb 19 12:20:06 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 19 Feb 2007 03:20:06 -0800
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.co
 m>
References: <20070219094524.10B1F1E4006@bag.python.org>
	<6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.com>
Message-ID: <20070219112034.45D0D1E4006@bag.python.org>

At 02:17 AM 2/19/2007, Andre Engels wrote:

>To understand these operators, you will have to think of the numbers 
>as binary numbers. Look at the digits. For two numbers x and y, x^y 
>is the effect of doing an exclusive or on all digits (that is, 0^1 = 
>1^0 = 1 and 0^0 = 1^1 = 0), & of doing an and (1&1 = 1, 
>1&0=0&1=0&0=0) and | is an or on all digits (1|1=1|0=0|1 = 1, 0|0 = 0).
>
>So 5^8 = 110 ^ 1000 = 0110 ^ 1000 = 1110 = 13
>and 13^8 = 1110 ^ 1000 = 0110 = 5

Thanks, Andre! I've got it for the three operators, for non-negative 
integers. But I'm not sure I understand how negative integers work. 
For example, is 3 & -3 = 1
because it is 11 & -11 = 01, and that's because one of the first 
digits of 11 and -11 is not 1, and both of their 2nd digits ARE 1, Q.E.D.?

Also, of what practical use are these things?

Dick



From kent37 at tds.net  Mon Feb 19 12:27:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Feb 2007 06:27:15 -0500
Subject: [Tutor] report service
In-Reply-To: <OFF10862D2.A7FEF41F-ONC1257287.0027D7ED-C1257287.00338F85@velux.com>
References: <OFF10862D2.A7FEF41F-ONC1257287.0027D7ED-C1257287.00338F85@velux.com>
Message-ID: <45D98993.3040506@tds.net>

J?nos Juh?sz wrote:
> 
> Dear Kent,
> 
> 
>  > > May someone recommend any simple solution to distribute some dozen
>  > > parametrizable sql reports
>  > > for some dozen users with a minimal access controll.
>  > > Some kind of charting possibilty needed, but I needn't web-based 
> front end.
> 
>  > I'm not sure I understand your requirements. Do you want a way for a
>  > dozen users to be able to create reports from a database, where they
>  > select some parameters and create the report on demand?
> 
> Currently I have some crystal reports, some dozen excel tables with 
> simple or complicated
> database queries and some delphi programs with some grids and sometimes 
> with charts.
> All of these 'reports' and it's contents are managed by the IT department.
> My dream to have a central repository of database reports,
> organized based on the workflow and controlled by the controlling 
> department.
> The distribution can be made by filesystem level (each report a separate 
> file),
> or by application level (the report manager shows a tree with the 
> accessible reports).
> 
> The candidates are till now:
>  crystal report server
>  ms reporting services
>  commercial reportlab

So you want a program that will generate the report files automatically?
What about the open source ReportLab?

You might still want to look at Dabo, it has a report generator built on 
ReportLab that adds some database integration.

Kent


From kent37 at tds.net  Mon Feb 19 12:32:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Feb 2007 06:32:25 -0500
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <20070219094524.10B1F1E4006@bag.python.org>
References: <20070219094524.10B1F1E4006@bag.python.org>
Message-ID: <45D98AC9.8010004@tds.net>

Dick Moores wrote:
> The docs list it at <http://docs.python.org/ref/augassign.html>, and 
> send you to <http://docs.python.org/ref/primaries.html#primaries>, 
> which seems a dead end.

a += n is more-or-less a shortcut for a = a + n. There are a few 
subtleties which the first page you reference talks about, but you can 
generally think of it as a handy abbreviation.

For other operations, the same is true:
a <op>= n is the same as a = a <op> n

> I've tried "^=" out a bit and get that strange alternating behavior.

which is normal operation of ^. Try it with + or * for a simpler example.

Kent


From rdm at rcblue.com  Mon Feb 19 12:40:20 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 19 Feb 2007 03:40:20 -0800
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <45D98AC9.8010004@tds.net>
References: <20070219094524.10B1F1E4006@bag.python.org>
	<45D98AC9.8010004@tds.net>
Message-ID: <20070219114024.E91331E400E@bag.python.org>

At 03:32 AM 2/19/2007, you wrote:
>Dick Moores wrote:
>>The docs list it at <http://docs.python.org/ref/augassign.html>, 
>>and send you to 
>><http://docs.python.org/ref/primaries.html#primaries>, which seems a dead end.
>
>a += n is more-or-less a shortcut for a = a + n. There are a few 
>subtleties which the first page you reference talks about, but you 
>can generally think of it as a handy abbreviation.
>
>For other operations, the same is true:
>a <op>= n is the same as a = a <op> n
>
>>I've tried "^=" out a bit and get that strange alternating behavior.
>
>which is normal operation of ^. Try it with + or * for a simpler example.

Of those listed on <http://docs.python.org/ref/augassign.html>,  I 
already use and understand "+=" | "-=" | "*=" | "/=" | "%=" | "**=" . 
It's the remaining seven I'm wondering about, or really about >>, <<, 
&, ^, and | . Andre's given me a good start, as you may have seen by now.

Dick



From rikard.bosnjakovic at gmail.com  Mon Feb 19 12:45:27 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 19 Feb 2007 12:45:27 +0100
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <20070219114024.E91331E400E@bag.python.org>
References: <20070219094524.10B1F1E4006@bag.python.org>
	<45D98AC9.8010004@tds.net> <20070219114024.E91331E400E@bag.python.org>
Message-ID: <d9e88eaf0702190345s49acafe1gd1b354093e68cf00@mail.gmail.com>

On 2/19/07, Dick Moores <rdm at rcblue.com> wrote:

> It's the remaining seven I'm wondering about, or really about >>, <<,
> &, ^, and | .

This webpage will tell you - in detail - about all the operators:
http://www.lnf.infn.it/Calcolo/doc/aixcxx/html/language/ref/ruclxbin.htm

The bitwise operators are hard to understand without proper knowledge
about the binary number system. I recommend you to read up about it,
if you feel the operators are somewhat difficult to understand.


-- 
- Rikard.

From andreengels at gmail.com  Mon Feb 19 12:46:08 2007
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 19 Feb 2007 12:46:08 +0100
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <45d987ff.2146c09f.4d63.15d7SMTPIN_ADDED@mx.google.com>
References: <20070219094524.10B1F1E4006@bag.python.org>
	<6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.com>
	<45d987ff.2146c09f.4d63.15d7SMTPIN_ADDED@mx.google.com>
Message-ID: <6faf39c90702190346p68a4156bg20aff237dd932931@mail.gmail.com>

2007/2/19, Dick Moores <rdm at rcblue.com>:
>
> At 02:17 AM 2/19/2007, Andre Engels wrote:
>
> >To understand these operators, you will have to think of the numbers
> >as binary numbers. Look at the digits. For two numbers x and y, x^y
> >is the effect of doing an exclusive or on all digits (that is, 0^1 =
> >1^0 = 1 and 0^0 = 1^1 = 0), & of doing an and (1&1 = 1,
> >1&0=0&1=0&0=0) and | is an or on all digits (1|1=1|0=0|1 = 1, 0|0 = 0).
> >
> >So 5^8 = 110 ^ 1000 = 0110 ^ 1000 = 1110 = 13
> >and 13^8 = 1110 ^ 1000 = 0110 = 5
>
> Thanks, Andre! I've got it for the three operators, for non-negative
> integers. But I'm not sure I understand how negative integers work.
> For example, is 3 & -3 = 1
> because it is 11 & -11 = 01, and that's because one of the first
> digits of 11 and -11 is not 1, and both of their 2nd digits ARE 1, Q.E.D.?


This has to do with the internal representation of negative numbers: -1 is
represented as 111....111, with one 1 more than maxint. -2 is 111...110 and
-3 is 111...101. Thus 3 & -3 is 11 & 111...101 = 1

Also, of what practical use are these things?
>

I guess they have their uses for people accustomed to dealing with hardware.
Apart from that, you can get a very space-efficient representation for
multiple boolean variables. If you have what looks like an array of
booleans, you could also represent it as a single natural number, for
example [true, true, false, false, true, false] would then be 1*1 + 1*2 +
0*4 + 0*8 + 1*16 + 0*32 = 19. Using such a representation and the above
operators would enable one to write

z = x & y

instead of

z = [x[i] and y[i] for i in range(len(x))]

when modelling the same using lists.

Of course this does come at the price of complicating

x[i] = true

to

x |= 2 ** i

which though not really longer does definitely look harder to understand.

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/dd5741b5/attachment.html 

From alan.gauld at btinternet.com  Mon Feb 19 13:54:13 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Feb 2007 12:54:13 -0000
Subject: [Tutor] What is the augmented assignment operator "^="
References: <20070219094524.10B1F1E4006@bag.python.org><6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.com>
	<6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.co m>
	<20070219112034.45D0D1E4006@bag.python.org>
Message-ID: <erc6ls$4bl$1@sea.gmane.org>

"Dick Moores" <rdm at rcblue.com> wrote

> Thanks, Andre! I've got it for the three operators, for non-negative
> integers. But I'm not sure I understand how negative integers work.
> For example, is 3 & -3 = 1
> because it is 11 & -11 = 01, and that's because one of the first
> digits of 11 and -11 is not 1, and both of their 2nd digits ARE 1, 
> Q.E.D.?

Remember that the digits are 32 bits long so 3 is not  11
but
00000000000000000000000000000000011

And the representation of negative numbers is more complex
than you might think.

You can see the full hex representations using struct:

>>> import struct
>>> struct.pack('i',-3)
'\xfd\xff\xff\xff'
>>> struct.pack('i',3)
'\x03\x00\x00\x00'

Since most of 3 is zeros the and results will be zro, so
lets look at the significant bits:

>>> 0xfd & 0x03
1
>>>

voila!

> Also, of what practical use are these things?

Take a look at my Using the OS topic, there is a side-bar(box)
just short of half way down that describes how these can be
used to test file status. There are many other uses too, but
that's one real-world case.

HTH,

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




From johan at accesstel.co.za  Mon Feb 19 15:19:28 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Mon, 19 Feb 2007 16:19:28 +0200
Subject: [Tutor] Struct the solution for Hex translation
Message-ID: <20070219141318.521871792B@mail.accesstel.co.za>

Hi all,
 
I read in some conversations that the struct module maybe helpful in
converting Hex values to binary or decimal. Maybe I understood it
incorrectly.
 
Here is my problem.
 
I have a 22 byte data packet on a tcp socket connection. My data field is
from the 6th byte to byte 20. 14 bytes in total.
The first two bytes of the data is a 16 bit value. Eg: "\xe2\x01'
 
I can the first byte into binary if I use 'e2', but I don't know how to get
the '\x' out of the first byte to use it in python. My data has the '\x' and
all I need is the 'e2'.
 
Any advice of the usage of the struct module or how I can get rid of the
'\x' in my data?
 
Hopefully I have given enough information.
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/a4dd2d0e/attachment.htm 

From dperlman at wisc.edu  Mon Feb 19 14:51:30 2007
From: dperlman at wisc.edu (David Perlman)
Date: Mon, 19 Feb 2007 07:51:30 -0600
Subject: [Tutor] control multiple FTP sessions using multiple
 ipconnectionsvia different com ports
In-Reply-To: <728330.93619.qm@web31203.mail.mud.yahoo.com>
References: <728330.93619.qm@web31203.mail.mud.yahoo.com>
Message-ID: <E82EE665-DF4F-4219-A4FF-2A0868EEE438@wisc.edu>

This kind of thing is usually handled at the level of the OS's  
routing table.  Routing tables have an entry called "metric" that is  
used to weight the different routes, so that when there are multiple  
possible links available, the one with the lowest metric is used  
first.  In Unix at least, you'll be able to use either the command  
"route" or "routed" to manually change the routing table; you can  
change the metrics for the two interfaces to control which one gets  
used.  unfortunately this will change the routing globally, not just  
for a specific connection.  I don't think the routing systems on  
ordinary computers were designed with the idea in mind that you might  
want to use a specific link for a specific connection.

If you're on UNIX, run netstat -nr.  If you're on Windoze, run route  
print.  You should be able to see the metric for each entry.
http://www.pku.edu.cn/academic/research/computer-center/tc/html/ 
TC0310.html
Unfortunately, the "metric" column doesn't show up under OS X, and I  
haven't been able to figure out why in 5 minutes of searching.  Also  
unfortunately, I don't know any more about this, and searching on  
Google was not revealing immediate results.  But hopefully this will  
get you started in the right direction!

So the bottom line, I guess, is that a) this is a routing question,  
not a python question; and b) it's not an easy question.  :)

On Feb 19, 2007, at 3:53 AM, ray sa wrote:

> Hi
>
> Well now I have configured an old machine in the garage to run at  
> the same time.
>
> I would really like to find out how to do this as it must be  
> possible. I have been googling like mad and can't find how. Kind of  
> frustrating when you don't know how. At the same time a challenge  
> to seek.
>
> I am kind of hoping that someone on this forum will know how. In  
> the mean time I can continue with my testing.
>
> Many thanks for your help; really appreciate it.
>
> /Ray
>
> Johan Geldenhuys <johan at accesstel.co.za> wrote:
> Will it be possible to disconnect one of the links during your test  
> and reconnect it and disconnect the other connection once the ftp  
> test is finished on the first connection? This way it will force  
> the test script to use the active route to the internet.
>
> Not the most elegant way, but something to look at in the mean time.
>
> Johan
>
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On  
> Behalf Of ray sa
> Sent: 18 February 2007 04:16 AM
> To: Alan Gauld; tutor at python.org
> Subject: Re: [Tutor] control multiple FTP sessions using multiple  
> ipconnectionsvia different com ports
>
> Hi Alan et al
>
> Many thanks for your time on this.
>
> I was referring to the client end.
>
> An EDGE terminal is a phone that has the capability of connecting  
> to the internet. We use mobile phones to make a voice call that  
> make use of a circuit switched connection. By using a GPRS  
> connection we can use the mobile device to connect to the packet  
> switched domain. You might have heard about making data connection  
> using your phone like GPRS, 3G etc. EDGE is just faster than a GPRS  
> connection and 3G is supposedly faster than GPRS and EDGE.
>
> May be I can give you more information about what I am trying to  
> do. So you can understand what I am trying to achieve. Basically, I  
> am trying to decide whether I should change my ADSL fixed solution  
> to a higher speed connection using a mobile solution. Where I live  
> the mobile operator is offering a mobile solution which is cheaper  
> than my fixed solution?.and is faster than my ADSL connection,  
> please read on
>
> I have my ADSL broadband connection to my service provider that I  
> use to connect to the internet. I have just bought a GPRS/EDGE/3G  
> terminal and wanted to benchmark the speed I am getting by using my  
> mobile device as opposed to my fixed connection.
>
> My desktop machine is connected to my ADSL provider using a USB  
> modem which is assigned a particular COM port on my machine. Then I  
> have connected my mobile handset also using a USB connection  
> connected to a different COM port.
>
> Now I have two ip addresses
>
> ADSL ? COM port 4 with ip addres from my ADSL service provider
> Mobile Handset ? COM port 5 with another ip address from my mobile  
> provider
>
> I have written a script that connects to a ftp server within my  
> home country and downloads a file. But this script uses one of the  
> connections above. There must be away to tell the script and  
> control which connection to use. So I can get to see real time  
> which connection is faster. So I can run the script pointing to one  
> IP address and at the same time run another script using the other  
> connection.
>
> I think there must be a method that finds out which connection is  
> connected to which com port and then in my script I need to point  
> towards that connection so my script knows which channel to use  
> when downloading the file.
>
> I hope this helps sorry for too much text couldn?t really find a  
> simpler way to explain this.
>
> Once again I really appreciate the help on this forum...../Ray
>
>
> Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "ray sa" wrote
>
> > I have been successful to write an ftp script that logs
> > into a server and collects files.
>
> > ...I would like to run multiple ftp sessions using one laptop
> > with two different connections.
>
> Do you mean you want the server on the laptop accepting
> using two connections or do you mean that you want
> the client on the laptop and have different sessions sending
> outgoing requests to the server via two different IP addresses?
>
> If the former its easy, just set up two servers, one on each
> IP address. The port will nbe the same on both, ISTR its port
> 21 for ftp?
>
> If you want to specify which IP address you send the
> client request from, I'm afraid I have no idea how you specify
> that. I've only ever used multiple network cards at the server
> end!
>
> > another connection using your EDGE terminal
>
> As a matter of interest what is an EDGE terminal?
> A new term for me...
>
> > I would like to write a script that controls which ip
> > address to use or with com port to use.
>
> Until we know which end you mean its hard to hgive more
> specific advice.
>
> Alan G.
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
> No need to miss a message. Get email on-the-go
> with Yahoo! Mail for Mobile. Get started.
> --
> No virus found in this incoming message.
> Checked by AVG Free Edition.
> Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date:  
> 2007/02/13 10:01 PM
>
> --
> No virus found in this outgoing message.
> Checked by AVG Free Edition.
> Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date:  
> 2007/02/18 04:35 PM
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> It's here! Your new message!
> Get new email alerts with the free Yahoo! Toolbar.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From alan.gauld at btinternet.com  Mon Feb 19 16:04:21 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Feb 2007 15:04:21 -0000
Subject: [Tutor] Struct the solution for Hex translation
References: <20070219141318.521871792B@mail.accesstel.co.za>
Message-ID: <erce9s$esd$1@sea.gmane.org>


"Johan Geldenhuys" <johan at accesstel.co.za> wrote 

> The first two bytes of the data is a 16 bit value. Eg: "\xe2\x01'
> 
> I can the first byte into binary if I use 'e2', but I don't know 
> how to get the '\x' out of the first byte to use it in python. 

Are you sure it is there?
Usually the \x is only part of the repr string, its not actually 
in the data. What do you get is you do:

byte = data[0]  # get the first byte
print len(byte)   # should only be one byte
print byte     # should get '\xe2' or whatever.

> My data has the '\x' and all I need is the 'e2'.

If you do have the \xe2  that implies you have 4 characters, 
ie 4 bytes, so to get the real value use int(data[2:],16)

> Any advice of the usage of the struct module or how 
> I can get rid of the '\x' in my data?

I'm not sure where the struct module comes in? Are 
you using struct to read the data? If so you should be 
able to use unpack the data into the format you need 
by specifying a format string.

eg

struct.unpack('cc5s',data)

Should return two characters(bytes) and a 98 character 
string. Like so:

>>> struct.unpack('cc5s','\x12\x23abcde')
('\x12', '#', 'abcde')
>>>

Is that what you want?
Notice that the first value is actially a single byte of 
value 12 hex. The \x are only in the display.

The >>> prompt is a great place to experiment with struct
format strings etc.

HTH,

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


From rdm at rcblue.com  Mon Feb 19 16:07:57 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 19 Feb 2007 07:07:57 -0800
Subject: [Tutor] What is the augmented assignment operator "^="
In-Reply-To: <erc6ls$4bl$1@sea.gmane.org>
References: <20070219094524.10B1F1E4006@bag.python.org>
	<6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.com>
	<6faf39c90702190217y263fdb72rd2431ce84c90ac8e@mail.gmail.co m>
	<20070219112034.45D0D1E4006@bag.python.org>
	<erc6ls$4bl$1@sea.gmane.org>
Message-ID: <20070219150813.5F21F1E4006@bag.python.org>

My sincere thanks to Rikard Bosnjakovic, Andre Engels, and Alan 
Gauld. I think you've given me a good start toward understanding the 
operators >>, <<,  &, ^, and  | ; 32-bit numbers, and negative binary numbers.

Dick Moores



From rdm at rcblue.com  Mon Feb 19 16:25:07 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 19 Feb 2007 07:25:07 -0800
Subject: [Tutor] Where is the __builtin__ module?
Message-ID: <20070219152526.02A621E4014@bag.python.org>

"import __builtin__" occurs frequently in files in Lib/, but I'm 
unable to find a module named "__builtin__" or "__builtin__.py" 
anywhere in my Python 2.5. Is there one? If there is, where is it?

Thanks,

Dick Moores 


From johan at accesstel.co.za  Mon Feb 19 16:25:25 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Mon, 19 Feb 2007 17:25:25 +0200
Subject: [Tutor] Struct the solution for Hex translation
In-Reply-To: <erce9s$esd$1@sea.gmane.org>
Message-ID: <20070219151915.7DFD116675@mail.accesstel.co.za>

 Here is what I have:

>>> data
'\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00\x00\x17\x
01C\xc7'
>>> data[0]
'\xa5'
>>> len(data[0])
1
>>>

You see that data[0] is only one byte and it doesn't see all four
characters.

If I want to do this:

>>> int(data[0], 16)
  File "<console>", line 1, in ?
''' exceptions.ValueError : invalid literal for int(): ? '''


But I can do this:

>>> int('a5', 16)
165
>>>

If I use data[0] as it is, I get errors. That why I want to know how I can
strip away the '\x'.

Here is some other code to convert Hex to Binary:

hex2bin = {
"0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011", 
"4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111", 
"8" : "1000", "9" : "1001", "a" : "1010", "b" : "1011", 
"c" : "1100", "d" : "1101", "e" : "1110", "f" : "1111"
}

>>> def hexBin(hexchars):
...     s = ""
        for hexchar in hexchars:
            s += hex2bin[hexchar]
        return s.rstrip("\n")
... 
>>> hexBin('a5')
'10100101'

This however does not work if my argument is '\xa5'.

>>> hexBin('\xa5')
  File "<console>", line 1, in ?
  File "<console>", line 5, in hexBin
''' exceptions.KeyError : '\xa5' '''
>>> 

Thanks

Johan

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Alan Gauld
Sent: 19 February 2007 05:04 PM
To: tutor at python.org
Subject: Re: [Tutor] Struct the solution for Hex translation


"Johan Geldenhuys" <johan at accesstel.co.za> wrote 

> The first two bytes of the data is a 16 bit value. Eg: "\xe2\x01'
> 
> I can the first byte into binary if I use 'e2', but I don't know how 
> to get the '\x' out of the first byte to use it in python.

Are you sure it is there?
Usually the \x is only part of the repr string, its not actually in the
data. What do you get is you do:

byte = data[0]  # get the first byte
print len(byte)   # should only be one byte
print byte     # should get '\xe2' or whatever.

> My data has the '\x' and all I need is the 'e2'.

If you do have the \xe2  that implies you have 4 characters, ie 4 bytes, so
to get the real value use int(data[2:],16)

> Any advice of the usage of the struct module or how I can get rid of 
> the '\x' in my data?

I'm not sure where the struct module comes in? Are you using struct to read
the data? If so you should be able to use unpack the data into the format
you need by specifying a format string.

eg

struct.unpack('cc5s',data)

Should return two characters(bytes) and a 98 character 
string. Like so:

>>> struct.unpack('cc5s','\x12\x23abcde')
('\x12', '#', 'abcde')
>>>

Is that what you want?
Notice that the first value is actially a single byte of 
value 12 hex. The \x are only in the display.

The >>> prompt is a great place to experiment with struct
format strings etc.

HTH,

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

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

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 


From dperlman at wisc.edu  Mon Feb 19 16:56:09 2007
From: dperlman at wisc.edu (David Perlman)
Date: Mon, 19 Feb 2007 09:56:09 -0600
Subject: [Tutor] Struct the solution for Hex translation
In-Reply-To: <20070219151915.7DFD116675@mail.accesstel.co.za>
References: <20070219151915.7DFD116675@mail.accesstel.co.za>
Message-ID: <743FCAF0-DC27-487C-A79E-5CE98AE55D27@wisc.edu>

You're way off base... :)

On Feb 19, 2007, at 9:25 AM, Johan Geldenhuys wrote:

>  Here is what I have:
>
>>>> data
> '\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00 
> \x00\x17\x
> 01C\xc7'
>>>> data[0]
> '\xa5'
>>>> len(data[0])
> 1
>>>>
>
> You see that data[0] is only one byte and it doesn't see all four
> characters.
>
> If I want to do this:
>
>>>> int(data[0], 16)
>   File "<console>", line 1, in ?
> ''' exceptions.ValueError : invalid literal for int(): ? '''
>
>
> But I can do this:
>
>>>> int('a5', 16)
> 165
>>>>
>
> If I use data[0] as it is, I get errors. That why I want to know  
> how I can
> strip away the '\x'.

This is what you want to do:
 >>> import struct
 >>> struct.unpack('B',data[0])
(165,)

Once again, the \x doesn't really exist, any more than the quotation  
marks do.  They're just ways of indicating on the screen what kind of  
data is being displayed.

> Here is some other code to convert Hex to Binary:
>
> hex2bin = {
> "0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011",
> "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111",
> "8" : "1000", "9" : "1001", "a" : "1010", "b" : "1011",
> "c" : "1100", "d" : "1101", "e" : "1110", "f" : "1111"
> }
>
>>>> def hexBin(hexchars):
> ...     s = ""
>         for hexchar in hexchars:
>             s += hex2bin[hexchar]
>         return s.rstrip("\n")
> ...
>>>> hexBin('a5')
> '10100101'
>
> This however does not work if my argument is '\xa5'.
>
>>>> hexBin('\xa5')
>   File "<console>", line 1, in ?
>   File "<console>", line 5, in hexBin
> ''' exceptions.KeyError : '\xa5' '''
>>>>

This function is useless in this case because you don't actually have  
a string of letters and numbers; you just have raw binary data.

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From les.hazlett at navteq.com  Mon Feb 19 17:15:08 2007
From: les.hazlett at navteq.com (Hazlett, Les)
Date: Mon, 19 Feb 2007 10:15:08 -0600
Subject: [Tutor] Main program confusion
Message-ID: <B76F47F45A9B184781E0A41F711B516CC8292B@NAEXC.ad.navteq.com>

Hello,

 

I am trying to understand some sample code that includes the following
for a main program:

 

def runTest(frame, nb, log):

    win = TestPanel(nb, log)

    return win

 

if __name__ == '__main__':

    import sys,os

    import run

    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

 

I understand that win is an object of the class TestPanel.  The class
code for TestPanel preceded

the code which I copied above.  The object win clearly is instantiated.
I understand how the 

if__name__=='__main__' only runs when this program file is executed.

But, I can't find any reference to a module run and I don't see how the
"run.main([" line casues 

the "runTest(" function to run.

 

What am I missing?

 

Thanks for any help.

 

Les Hazlett



The information contained in this communication may be CONFIDENTIAL and is intended only for the use of the recipient(s) named above. If you are not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication, or any of its contents, is strictly prohibited. If you have received this communication in error, please notify the sender and delete/destroy the original message and any copy of it from your computer or paper files.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/f7e414b7/attachment-0001.htm 

From alan.gauld at btinternet.com  Mon Feb 19 17:24:48 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Feb 2007 16:24:48 -0000
Subject: [Tutor] Struct the solution for Hex translation
References: <erce9s$esd$1@sea.gmane.org>
	<20070219151915.7DFD116675@mail.accesstel.co.za>
Message-ID: <ercj0n$9e0$1@sea.gmane.org>


"Johan Geldenhuys" <johan at accesstel.co.za> wrote

>>> data
'\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00\x00\x17\x
01C\xc7'
>>> data[0]
'\xa5'
>>> len(data[0])
1
>>>

OK, So that tells you that you have one byte.
The '\xa5' is a 4 character representation of that byte but it
is only one byte with hex value a5. You don;t need to strip
anything, you have your byte.

>>> int(data[0], 16)
  File "<console>", line 1, in ?
''' exceptions.ValueError : invalid literal for int(): ? '''

Its already an int (well a byte) you don;t need to use int()

>>> int('a5', 16)
165

Because that passes the 2 byte string 'a5' to int. But you
don't need that your byte actualoly is a5

> If I use data[0] as it is, I get errors. That why I want to
> know how I can strip away the '\x'.

The \x doesn't exist its purely a part of the replresentation
that Python uses to display the data. Its like the L at the
end of a long interer. The number doesn't really have an L
at the end its just put there by Python to show the type.
Similarly the '\x' is prepended by Python to show that this
is a hex value.

>>> def hexBin(hexchars):
...     s = ""
        for hexchar in hexchars:
            s += hex2bin[hexchar]
        return s.rstrip("\n")
...
>>> hexBin('a5')
'10100101'

This however does not work if my argument is '\xa5'.

>>> hexBin('\xa5')
  File "<console>", line 1, in ?
  File "<console>", line 5, in hexBin
''' exceptions.KeyError : '\xa5' '''

Because you are now passing a single character which
is not a valid hex character.

So far as I can see you actually have the data you want!


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



From rikard.bosnjakovic at gmail.com  Mon Feb 19 17:36:15 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 19 Feb 2007 17:36:15 +0100
Subject: [Tutor] Where is the __builtin__ module?
In-Reply-To: <20070219152526.02A621E4014@bag.python.org>
References: <20070219152526.02A621E4014@bag.python.org>
Message-ID: <d9e88eaf0702190836x194f9c66r8a2ce533eb761b59@mail.gmail.com>

On 2/19/07, Dick Moores <rdm at rcblue.com> wrote:

> Is there one? If there is, where is it?

Yes, there is one. It's....builtin(!) in the interpreter! ;-)

-- 
- Rikard.

From alan.gauld at btinternet.com  Mon Feb 19 17:39:13 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Feb 2007 16:39:13 -0000
Subject: [Tutor] Where is the __builtin__ module?
References: <20070219152526.02A621E4014@bag.python.org>
Message-ID: <ercjrp$dqg$1@sea.gmane.org>

"Dick Moores" <rdm at rcblue.com> wrote

> "import __builtin__" occurs frequently in files in Lib/,

Really? I'm surprised, I can't think why.

> unable to find a module named "__builtin__" or "__builtin__.py"
> anywhere in my Python 2.5. Is there one? If there is, where is it?

It's C code so it's not a .py file.
There is probably a C library/DLL somewhere but the whole
point of builtin is that it is built in to the core Python interpreter
so there is no physically separate file you can see.

You can read the C source here:

http://svn.python.org/view/python/trunk/Python/bltinmodule.c?rev=52315&view=markup

However you'll find that most of them basically just forward the
call to another function elsewhere - sometimes with a bit of
input validation first. See the abs() function as a short example:

static PyObject *
builtin_abs(PyObject *self, PyObject *v)
{
	return PyNumber_Absolute(v);
}

HTH,

Alan G. 



From dkuhlman at rexx.com  Mon Feb 19 17:47:06 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 19 Feb 2007 08:47:06 -0800
Subject: [Tutor] Main program confusion
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CC8292B@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CC8292B@NAEXC.ad.navteq.com>
Message-ID: <20070219164706.GA85681@cutter.rexx.com>

On Mon, Feb 19, 2007 at 10:15:08AM -0600, Hazlett, Les wrote:

> 
> if __name__ == '__main__':
>     import sys,os
>     import run
>     run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
>  
[snip]
> if__name__=='__main__' only runs when this program file is executed.
> 
> But, I can't find any reference to a module run and I don't see how the
> "run.main([" line casues 
> 
> the "runTest(" function to run.

Step 1 -- Find the run module.  If the import of "run" succeeds,
you can find out where the module run is installed on your system
by adding a print statement:

    import run
    print "run module:", run

That will show you where Python is finding the run module.  

And, if the import statement is failing, then you are likely to
need to install something in order to execute that sample code.

Once you have found the run module, ...

Step 2 -- Read the source in the run module.  In particular, you
are looking for a function named main.

Dave

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

From rabidpoobear at gmail.com  Mon Feb 19 17:52:21 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 19 Feb 2007 10:52:21 -0600
Subject: [Tutor] Main program confusion
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CC8292B@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CC8292B@NAEXC.ad.navteq.com>
Message-ID: <45D9D5C5.5060403@gmail.com>

Hazlett, Les wrote:
>
> Hello,
>
> I am trying to understand some sample code that includes the following 
> for a main program:
>
> def runTest(frame, nb, log):
>
> win = TestPanel(nb, log)
>
> return win
>
> if __name__ == '__main__':
>
> import sys,os
>
> import run
>
> run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
>
> I understand that win is an object of the class TestPanel. The class 
> code for TestPanel preceded
>
> the code which I copied above. The object win clearly is instantiated. 
> I understand how the
>
> if__name__==?__main__? only runs when this program file is executed.
>
> But, I can?t find any reference to a module run and I don?t see how 
> the ?run.main([? line casues
>
> the ?runTest(? function to run.
>
I've never heard of this module. Where did this code come from?
Have you tried the code? Either run is some builtin I haven't heard of, 
or the code is in some library/turorial that defines a custom module.
-Luke
>
> What am I missing?
>
> Thanks for any help.
>
> Les Hazlett
>
> ------------------------------------------------------------------------
> The information contained in this communication may be CONFIDENTIAL 
> and is intended only for the use of the recipient(s) named above. If 
> you are not the intended recipient, you are hereby notified that any 
> dissemination, distribution, or copying of this communication, or any 
> of its contents, is strictly prohibited. If you have received this 
> communication in error, please notify the sender and delete/destroy 
> the original message and any copy of it from your computer or paper 
> files.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From alan.gauld at btinternet.com  Mon Feb 19 18:00:58 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Feb 2007 17:00:58 -0000
Subject: [Tutor] control multiple FTP sessions using multiple
	ipconnectionsvia different com ports
References: <728330.93619.qm@web31203.mail.mud.yahoo.com>
	<E82EE665-DF4F-4219-A4FF-2A0868EEE438@wisc.edu>
Message-ID: <ercl4h$ind$1@sea.gmane.org>


"David Perlman" <dperlman at wisc.edu> wrote

> first.  In Unix at least, you'll be able to use either the command
> "route" or "routed" to manually change the routing table; ....
> I don't think the routing systems on  ordinary computers
> were designed with the idea in mind that you might
> want to use a specific link for a specific connection.

That's true, however....

> So the bottom line, I guess, is that a) this is a routing
> question,  not a python question; and b) it's not an easy
> question.  :)

Only because its so rarely done.
After a bit of digging it seems that socket.bind() can be
used on the client side as well as on the server side.
Thus if you really do want to limit your connections
you can tell the socket which interface to use.
You need to know the IP address of the interface
of course.

Caveat: I've never done this, nor even seen it done.
But the book Python Network Programming by Goerzen
specifically says its possible, although even it doesn't
give an example...

Regards,

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



From kent37 at tds.net  Mon Feb 19 18:21:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Feb 2007 12:21:25 -0500
Subject: [Tutor] Where is the __builtin__ module?
In-Reply-To: <d9e88eaf0702190836x194f9c66r8a2ce533eb761b59@mail.gmail.com>
References: <20070219152526.02A621E4014@bag.python.org>
	<d9e88eaf0702190836x194f9c66r8a2ce533eb761b59@mail.gmail.com>
Message-ID: <45D9DC95.3010007@tds.net>

Rikard Bosnjakovic wrote:
> On 2/19/07, Dick Moores <rdm at rcblue.com> wrote:
> 
>> Is there one? If there is, where is it?
> 
> Yes, there is one. It's....builtin(!) in the interpreter! ;-)

More info here:
http://docs.python.org/lib/module-builtin.html

Kent


From tomdrak at gmail.com  Mon Feb 19 18:23:08 2007
From: tomdrak at gmail.com (tomdrak at gmail.com)
Date: Mon, 19 Feb 2007 18:23:08 +0100
Subject: [Tutor] Main program confusion
In-Reply-To: <45D9D5C5.5060403@gmail.com>
Message-ID: <45d9dd00.35f293e8.4082.7472@mx.google.com>


It's wxpython demo's code.
It's necessary to have the run.py in the same path, to make it run, and usually also some other files.

--
Tom, http://www.vscripts.net

>
I've never heard of this module. Where did this code come from?


From les.hazlett at navteq.com  Mon Feb 19 18:27:11 2007
From: les.hazlett at navteq.com (Hazlett, Les)
Date: Mon, 19 Feb 2007 11:27:11 -0600
Subject: [Tutor] Main program confusion
Message-ID: <B76F47F45A9B184781E0A41F711B516CC82A37@NAEXC.ad.navteq.com>

Dave, 

Thanks for the guidance.  I followed your advice and learned the
following:

>>> import run

>>> print "run module:", run

run module: <module 'run' from 'C:\Python25\Lib\idlelib\run.pyc'>

 

The run.py file is there also.  I can read but not understand what
run.py does.  It may be something new in 

Python 2.5.  I have unistalled Python 2.4 so I can't tell.

 

Luke,

I found this mystery main program in the extensive demos in \wsPython2.8
Docs and Demos\demo\.  It is 

used throughout the demo code - in every demo sample I have looked at.  

 

It was a mystery to me when I found it there and tried to understand it.
It is still a mystery.  I guess that, 

I will just accept it as "pure magic" and go on with my effort to
understand the many demo segments found 

there.

 

Thanks,

Les



The information contained in this communication may be CONFIDENTIAL and is intended only for the use of the recipient(s) named above. If you are not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication, or any of its contents, is strictly prohibited. If you have received this communication in error, please notify the sender and delete/destroy the original message and any copy of it from your computer or paper files.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/e031abba/attachment-0001.htm 

From kent37 at tds.net  Mon Feb 19 18:38:03 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Feb 2007 12:38:03 -0500
Subject: [Tutor] Main program confusion
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CC82A37@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CC82A37@NAEXC.ad.navteq.com>
Message-ID: <45D9E07B.5050402@tds.net>

Hazlett, Les wrote:
> Dave,
> 
> Thanks for the guidance.  I followed your advice and learned the following:
> 
>> >> import run
> 
>> >> print "run module:", run
> 
> run module: <module 'run' from 'C:\Python25\Lib\idlelib\run.pyc'>

I don't think that is the correct run.py.

> Luke,
> 
> I found this mystery main program in the extensive demos in \wsPython2.8 
> Docs and Demos\demo\.  It is
> 
> used throughout the demo code ? in every demo sample I have looked at. 

There is a run.py in the demo folder, that is the one you get when you 
run the demos.

Kent


From les.hazlett at navteq.com  Mon Feb 19 18:54:52 2007
From: les.hazlett at navteq.com (Hazlett, Les)
Date: Mon, 19 Feb 2007 11:54:52 -0600
Subject: [Tutor] Main program confusion
Message-ID: <B76F47F45A9B184781E0A41F711B516CC82A8C@NAEXC.ad.navteq.com>

Thanks Kent,

 

Yes, there is a run.py in the demo folder.  I is the one that runs and
not the one in the Python25 lib.  

 

So, I tried to see if I could find it if I previously imported
everything that the code imports.   It didn't - see below:

 

 

IDLE 1.2      

>>> import wx

>>> import sys,os

>>> import run

>>> print "run module", run

run module <module 'run' from 'C:\Python25\Lib\idlelib\run.pyc'>

>>> 

 

This has been a good lesson in my learning process.  Thanks everyone.

 

Les Hazlett



The information contained in this communication may be CONFIDENTIAL and is intended only for the use of the recipient(s) named above. If you are not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication, or any of its contents, is strictly prohibited. If you have received this communication in error, please notify the sender and delete/destroy the original message and any copy of it from your computer or paper files.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/977cbb21/attachment.html 

From rabidpoobear at gmail.com  Mon Feb 19 19:13:36 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 19 Feb 2007 12:13:36 -0600
Subject: [Tutor] Main program confusion
In-Reply-To: <B76F47F45A9B184781E0A41F711B516CC82A8C@NAEXC.ad.navteq.com>
References: <B76F47F45A9B184781E0A41F711B516CC82A8C@NAEXC.ad.navteq.com>
Message-ID: <45D9E8D0.6030708@gmail.com>

Hazlett, Les wrote:
>
> Thanks Kent,
>
> Yes, there is a run.py in the demo folder. I is the one that runs and 
> not the one in the Python25 lib.
>
> So, I tried to see if I could find it if I previously imported 
> everything that the code imports. It didn?t ? see below:
>
> IDLE 1.2
>
> >>> import wx
>
> >>> import sys,os
>
> >>> import run
>
> >>> print "run module", run
>
> run module <module 'run' from 'C:\Python25\Lib\idlelib\run.pyc'>
>
> >>>
>
> This has been a good lesson in my learning process. Thanks everyone.
>
It's not finding it because you're running your code in the directory 
that IDLE is located in!
If you start a Python interpreter in the Demo directory, you will be 
able to find the file you need.
Python searches the current working directory for modules first before 
it does anything else.
Coincidentally, Idle has a module named 'run' and since the 
interpreter's current working directory is IDLE's directory,
it imports that one.
Try using the commands
import os
os.chdir("Path/To/Demo/Directory")

and import the module.
You should get the correct one, then.

HTH,
-Luke

From chris.lasher at gmail.com  Tue Feb 20 00:31:56 2007
From: chris.lasher at gmail.com (Chris Lasher)
Date: Mon, 19 Feb 2007 18:31:56 -0500
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <eqtban$ick$1@sea.gmane.org>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
	<eqtban$ick$1@sea.gmane.org>
Message-ID: <128a885f0702191531o42c80892hcda76701493a4d60@mail.gmail.com>

Thanks very much for your responses, all. Just to clarify, yes, by
"through class methods" I actually meant "through methods of instances
of a class".

Now for more discussion: I'm confused. On the one hand we have Mr.
Kent Johnson's statement:

On 2/13/07, Kent Johnson <kent37 at tds.net> wrote:
> Python practice is to use direct attribute access. If you need to do
> something special when an attribute is read or set, you can create a
> property. This allows you to define methods to be called when the
> attribute is accessed, without having to change the client code.

So to paraphrase, he states it's the Python way to do:
my_instance = MyClass()
my_instance.x = 42

On the other hand, we have Mr. Alan Gauld, who states:

On 2/13/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> Its generally good OOP practice to interact with object via messages.
> Its also good practice NOT to access an objects attributes directly
> (and that includes via get/set methods) A class should publish a
> set of operations. The attributes should be there to support
> those operations.

So to paraphrase, he states it's the right way, regardless of language, to do:
my_instance = MyClass()
my_instance.setx(42)

I'm used to just setting and getting attributes straight, which would
be Pythonic according to Kent and yet also outright wrong according to
Alan and academic papers. So is direct access actually not Pythonic,
or is it Pythonic and Pythonistas spit in the face of Demeter and her
lovely laws?

Curious,
Chris

From python at venix.com  Tue Feb 20 01:04:03 2007
From: python at venix.com (Python)
Date: Mon, 19 Feb 2007 19:04:03 -0500
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <128a885f0702191531o42c80892hcda76701493a4d60@mail.gmail.com>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
	<eqtban$ick$1@sea.gmane.org>
	<128a885f0702191531o42c80892hcda76701493a4d60@mail.gmail.com>
Message-ID: <1171929843.22126.21.camel@www.venix.com>

On Mon, 2007-02-19 at 18:31 -0500, Chris Lasher wrote:
> I'm used to just setting and getting attributes straight, which would
> be Pythonic according to Kent and yet also outright wrong according to
> Alan and academic papers. So is direct access actually not Pythonic,
> or is it Pythonic and Pythonistas spit in the face of Demeter and her
> lovely laws?

Kent and Alan can speak quite eloquently for themselves, but just to
provide a more immediate answer, I expect they mostly agree with each
other.

The issue isn't whether you code:
        my.x = 42
        or
        my.setx = 42

Alan is saying you should not generally be twiddling attributes in an
object.

Kent is suggesting that if you do decide to twiddle attributes in
Python, just do it directly.  If later on you decide you need some
method logic to control the attribute twiddling, you can use
        property
to invoke methods when directly accessing the attribute.  I do not think
there is anything to be gained in Python by expecting your object
interface to depend on the use of get/set methods.

-- 
Lloyd Kvam
Venix Corp


From alan.gauld at btinternet.com  Tue Feb 20 01:07:15 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 20 Feb 2007 00:07:15 -0000
Subject: [Tutor] Accessing class attributes: use methods only?
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com><eqtban$ick$1@sea.gmane.org>
	<128a885f0702191531o42c80892hcda76701493a4d60@mail.gmail.com>
Message-ID: <erde3r$23a$1@sea.gmane.org>

"Chris Lasher" <chris.lasher at gmail.com> wrote

> Now for more discussion: I'm confused.

:-)
Actually there is no real contradiction. I'll try to explain
and if I misrepresent Kent I'm sure he'll say so!

> Kent Johnson's statement:

>> Python practice is to use direct attribute access. If you need to 
>> do
>
> So to paraphrase, he states it's the Python way to do:
> my_instance = MyClass()
> my_instance.x = 42

And this is quite correct. In fact I specifically said in my reply
that if you really *must* access an attribute of a class it is
better to just do it directly than to write setX/getX methods

> On the other hand, we have Mr. Alan Gauld, who states:
>> Its generally good OOP practice to interact with object via 
>> messages.
>> Its also good practice NOT to access an objects attributes directly

So what I'm saying is that you should try to write classes
such that nobody ever needs to access the internal data. If a
user needs access to the internals it is often a sign that there
is some functionality of the class missing. Why do you need
the data? Shouldn't the class that owns the data do all the
manipulation of it? That's what OOP is supposed to be
about - creating objects which receive messages that tell
them what to do. Some of those methods will return data
values but you should neither know nor care whether they
are data attributes internally or whether they are calculated
values.

> So to paraphrase, he states it's the right way, regardless
> of language, to do:
> my_instance = MyClass()
> my_instance.setx(42)

No, I'm saying it's the wrong way regardless of language to do that.
(With the exception of JavaBeans - and not all Java classes need
to be beans! - because they rely on the set/get protocol to
support IDEs etc)

More usefully you should hopefully have a method that has a
meaningful, operation-based name, that results in the internal
variable x being set to 42. But that should be a by-product.
The user of the class should not, in general, even know that
x exists!

Now that's in an ideal world and as such it doesn't exist. So we
don't always have that luxury. And some objects are more or less
just data stores - but they should be the exception not the rule!
In those exceptional cases, if you need to access a data attribute,
then it's OK to use direct access in Python.

> I'm used to just setting and getting attributes straight, which 
> would
> be Pythonic according to Kent and yet also outright wrong according 
> to
> Alan and academic papers. So is direct access actually not Pythonic,

Direct access is Pythonic *when necessary*.
Direct access 9including via set/get) is wrong in an OOP sense in
any language. The methods should expose a set of operations which
do everything you need to do without your knowing about the
internals of the object.

> Pythonistas spit in the face of Demeter and her lovely laws?

Nope, but Python allows you to break the laws in the simplest
and most direct manner. One of Python's tenets is that we are
all responsible programmers. When we break the laws of good
programming we do so in a deliberate way, fully aware of why
we do it and of the potential consequences.

So both Kent and I are saying the same thing: don't use
setX/getX; use direct access if you have to. But I add the caveat
that you should try to avoid the need for direct access in the first
place.

HTH,

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



From chris.lasher at gmail.com  Tue Feb 20 01:44:12 2007
From: chris.lasher at gmail.com (Chris Lasher)
Date: Mon, 19 Feb 2007 19:44:12 -0500
Subject: [Tutor] Accessing class attributes: use methods only?
In-Reply-To: <erde3r$23a$1@sea.gmane.org>
References: <128a885f0702131116n1469b250g44dc6902a6baaac6@mail.gmail.com>
	<eqtban$ick$1@sea.gmane.org>
	<128a885f0702191531o42c80892hcda76701493a4d60@mail.gmail.com>
	<erde3r$23a$1@sea.gmane.org>
Message-ID: <128a885f0702191644s12a38802x112e511301ed0fb7@mail.gmail.com>

Ah ha! All is clear, now. I understand what I misinterpreted in your
first post, Alan. Thanks also to Lloyd for reinforcing the concept.
Much appreciated!

Chris

From johan at accesstel.co.za  Tue Feb 20 07:35:28 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Tue, 20 Feb 2007 08:35:28 +0200
Subject: [Tutor] Struct the solution for Hex translation
In-Reply-To: <743FCAF0-DC27-487C-A79E-5CE98AE55D27@wisc.edu>
Message-ID: <20070220062917.3EF56E4C1@mail.accesstel.co.za>

 Thanks, Dave.

On the struct module, How can I het the binary 1's and 0's of the Hex value?
Let say I want to get the 8 bit value of '\xe2', can I use struct to convert
that into binary code so that I get 8 binary bits as a string?

Thanks for helping with struct.

Johan

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of David Perlman
Sent: 19 February 2007 05:56 PM
To: tutor at python.org
Subject: Re: [Tutor] Struct the solution for Hex translation

You're way off base... :)

On Feb 19, 2007, at 9:25 AM, Johan Geldenhuys wrote:

>  Here is what I have:
>
>>>> data
> '\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00
> \x00\x17\x
> 01C\xc7'
>>>> data[0]
> '\xa5'
>>>> len(data[0])
> 1
>>>>
>
> You see that data[0] is only one byte and it doesn't see all four 
> characters.
>
> If I want to do this:
>
>>>> int(data[0], 16)
>   File "<console>", line 1, in ?
> ''' exceptions.ValueError : invalid literal for int(): ? '''
>
>
> But I can do this:
>
>>>> int('a5', 16)
> 165
>>>>
>
> If I use data[0] as it is, I get errors. That why I want to know how I 
> can strip away the '\x'.

This is what you want to do:
 >>> import struct
 >>> struct.unpack('B',data[0])
(165,)

Once again, the \x doesn't really exist, any more than the quotation marks
do.  They're just ways of indicating on the screen what kind of data is
being displayed.

> Here is some other code to convert Hex to Binary:
>
> hex2bin = {
> "0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011", "4" : "0100", 
> "5" : "0101", "6" : "0110", "7" : "0111", "8" : "1000", "9" : "1001", 
> "a" : "1010", "b" : "1011", "c" : "1100", "d" : "1101", "e" : "1110", 
> "f" : "1111"
> }
>
>>>> def hexBin(hexchars):
> ...     s = ""
>         for hexchar in hexchars:
>             s += hex2bin[hexchar]
>         return s.rstrip("\n")
> ...
>>>> hexBin('a5')
> '10100101'
>
> This however does not work if my argument is '\xa5'.
>
>>>> hexBin('\xa5')
>   File "<console>", line 1, in ?
>   File "<console>", line 5, in hexBin
> ''' exceptions.KeyError : '\xa5' '''
>>>>

This function is useless in this case because you don't actually have a
string of letters and numbers; you just have raw binary data.

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 


From ajkadri at googlemail.com  Tue Feb 20 10:46:51 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Tue, 20 Feb 2007 09:46:51 +0000
Subject: [Tutor] Visual Basic versus Python.. What to choose??
Message-ID: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>

Hi folks,

I want to develop an application which uses a database and some forms to
enter/modify the database.
The application should also generate reports based on some fields.

What should I be using? Python or VB...

I want to use Python.. IN that case, what should be my choice for the
Database..

Thanks in anticipation.

Best Regards,
Asrarahmed Kadri




-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070220/53ae6b4c/attachment.html 

From David.Barton at nottingham.ac.uk  Tue Feb 20 13:09:07 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Tue, 20 Feb 2007 12:09:07 -0000
Subject: [Tutor] file.read() doesn't give full contents of compressed files
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A3031C35CB@VUIEXCH1.ad.nottingham.ac.uk>

Hi,
I'm really confused, and I hope somebody can explain this for me...
 
I've been playing with compression and archives, and have some .zip,
.tar, .gz and .tgz example files to test my code on.
I can read them using either zipfile, tarfile, gzip or zlib, and that's
fine. But just reading them in 'raw' doesn't give me the whole string of
(compressed) bytes.
 
i.e...
 
len( file("mytestfile","r").read() ) != os.path.getsize("mytestfile")
 
Not even close, in fact. It seems like file.read() just stops after
reading a small portion of each example file, but why would that happen?
And what could I do if I wanted to read in the entire (compressed)
contents as a string?
 
thanks for any insight,
 
Dave (using Python 2.4 and windows)

This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070220/4793c3b8/attachment.htm 

From kent37 at tds.net  Tue Feb 20 13:53:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Feb 2007 07:53:01 -0500
Subject: [Tutor] file.read() doesn't give full contents of compressed
 files
In-Reply-To: <BAA2EE790D828F4E8B262F17B3B0A7A3031C35CB@VUIEXCH1.ad.nottingham.ac.uk>
References: <BAA2EE790D828F4E8B262F17B3B0A7A3031C35CB@VUIEXCH1.ad.nottingham.ac.uk>
Message-ID: <45DAEF2D.7040103@tds.net>

Barton David wrote:
> Hi,
> I'm really confused, and I hope somebody can explain this for me...
>  
> I've been playing with compression and archives, and have some .zip, 
> .tar, .gz and .tgz example files to test my code on.
> I can read them using either zipfile, tarfile, gzip or zlib, and that's 
> fine. But just reading them in 'raw' doesn't give me the whole string of 
> (compressed) bytes.
>  
> i.e...
>  
> len( file("mytestfile","r").read() ) != os.path.getsize("mytestfile")
>  
> Not even close, in fact. It seems like file.read() just stops after 
> reading a small portion of each example file, but why would that happen? 
> And what could I do if I wanted to read in the entire (compressed) 
> contents as a string?

Why do you think it stops reading? len() should be giving a bigger 
number than getsize() because you are reading the file in text mode 
which will convert \n to \r\n. Try file("mytestfile","rb").

Kent


From David.Barton at nottingham.ac.uk  Tue Feb 20 14:18:05 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Tue, 20 Feb 2007 13:18:05 -0000
Subject: [Tutor] file.read() doesn't give full contents of compressed
	files
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A3031C36C7@VUIEXCH1.ad.nottingham.ac.uk>

Oh... of course. Thanks and sorry for missing the bleeding obvious.

Mind you, when reading in 'txt mode' rather than binary, len() actually
gives a much *smaller* size than getsize. Does the conversion into txt
happen to introduce some sort of terminator character that stops
file.read() from going to the end?

Dave


-----Original Message-----
From: Kent Johnson [mailto:kent37 at tds.net] 
Sent: 20 February 2007 12:53
To: Barton David
Cc: tutor at python.org
Subject: Re: [Tutor] file.read() doesn't give full contents of
compressed files

Barton David wrote:
> Hi,
> I'm really confused, and I hope somebody can explain this for me...
>  
> I've been playing with compression and archives, and have some .zip, 
> .tar, .gz and .tgz example files to test my code on.
> I can read them using either zipfile, tarfile, gzip or zlib, and 
> that's fine. But just reading them in 'raw' doesn't give me the whole 
> string of
> (compressed) bytes.
>  
> i.e...
>  
> len( file("mytestfile","r").read() ) != os.path.getsize("mytestfile")
>  
> Not even close, in fact. It seems like file.read() just stops after 
> reading a small portion of each example file, but why would that
happen?
> And what could I do if I wanted to read in the entire (compressed) 
> contents as a string?

Why do you think it stops reading? len() should be giving a bigger
number than getsize() because you are reading the file in text mode
which will convert \n to \r\n. Try file("mytestfile","rb").

Kent


This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.


From kent37 at tds.net  Tue Feb 20 14:29:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Feb 2007 08:29:51 -0500
Subject: [Tutor] file.read() doesn't give full contents of compressed
 files
In-Reply-To: <BAA2EE790D828F4E8B262F17B3B0A7A3031C36C7@VUIEXCH1.ad.nottingham.ac.uk>
References: <BAA2EE790D828F4E8B262F17B3B0A7A3031C36C7@VUIEXCH1.ad.nottingham.ac.uk>
Message-ID: <45DAF7CF.9040401@tds.net>

Barton David wrote:
> Oh... of course. Thanks and sorry for missing the bleeding obvious.
> 
> Mind you, when reading in 'txt mode' rather than binary, len() actually
> gives a much *smaller* size than getsize. Does the conversion into txt
> happen to introduce some sort of terminator character that stops
> file.read() from going to the end?

Actually, yes. A ctrl-Z is treated as an end-of-file when reading a file 
in text mode on Windows.
http://groups.google.com/group/comp.lang.python/msg/4604aac0222a0043?hl=en&

Kent


From David.Barton at nottingham.ac.uk  Tue Feb 20 14:45:05 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Tue, 20 Feb 2007 13:45:05 -0000
Subject: [Tutor] file.read() doesn't give full contents of compressed
	files
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A3031C3718@VUIEXCH1.ad.nottingham.ac.uk>

I see. Thanks for that.

dave 

-----Original Message-----
From: Kent Johnson [mailto:kent37 at tds.net] 
Sent: 20 February 2007 13:30
To: Barton David
Cc: tutor at python.org
Subject: Re: [Tutor] file.read() doesn't give full contents of
compressed files

Barton David wrote:
> Oh... of course. Thanks and sorry for missing the bleeding obvious.
> 
> Mind you, when reading in 'txt mode' rather than binary, len() 
> actually gives a much *smaller* size than getsize. Does the conversion

> into txt happen to introduce some sort of terminator character that 
> stops
> file.read() from going to the end?

Actually, yes. A ctrl-Z is treated as an end-of-file when reading a file
in text mode on Windows.
http://groups.google.com/group/comp.lang.python/msg/4604aac0222a0043?hl=
en&

Kent


This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.


From carpentier.th at free.fr  Tue Feb 20 15:25:17 2007
From: carpentier.th at free.fr (carpentier.th at free.fr)
Date: Tue, 20 Feb 2007 15:25:17 +0100
Subject: [Tutor] Visual Basic versus Python.. What to choose??
In-Reply-To: <1171966635.45dacaabb2654@imp.free.fr>
References: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>
	<1171966635.45dacaabb2654@imp.free.fr>
Message-ID: <1171981517.45db04cd7d730@imp.free.fr>

Selon carpentier.th at free.fr:

> Hi!
>
> With python, you can work with a lot of Database, likes mysql, oracle,
> sqlite,
> SQLServer, PostgreSQL....
>
> If you use Python2.5, sqlite3 is already installed.
>
> However, you can choose any data base which you want to use.
>
> Thomas
>
>
> Selon Asrarahmed Kadri <ajkadri at googlemail.com>:
>
> > Hi folks,
> >
> > I want to develop an application which uses a database and some forms to
> > enter/modify the database.
> > The application should also generate reports based on some fields.
> >
> > What should I be using? Python or VB...
> >
> > I want to use Python.. IN that case, what should be my choice for the
> > Database..
> >
> > Thanks in anticipation.
> >
> > Best Regards,
> > Asrarahmed Kadri
> >
> >
> >
> >
> > --
> > To HIM you shall return.
> >
>
>
>



From bgailer at alum.rpi.edu  Tue Feb 20 15:47:58 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 20 Feb 2007 06:47:58 -0800
Subject: [Tutor] Visual Basic versus Python.. What to choose??
In-Reply-To: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>
References: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>
Message-ID: <45DB0A1E.70205@alum.rpi.edu>

Asrarahmed Kadri wrote:
>
> Hi folks,
>  
> I want to develop an application which uses a database and some forms 
> to enter/modify the database.
> The application should also generate reports based on some fields.
>  
> What should I be using? Python or VB...
>  
> I want to use Python.. IN that case, what should be my choice for the 
> Database..
The choice of DB, IMHO, is independent of the programming language. Both 
VB and Python can interact with almost any database system.

What are your criteria for a database? Single or multiple user? Local or 
remote server? Size? Transaction rate?

-- 
Bob Gailer
510-978-4454


From nospamformeSVP at gmail.com  Tue Feb 20 15:49:05 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Tue, 20 Feb 2007 09:49:05 -0500
Subject: [Tutor] Visual Basic versus Python.. What to choose??
In-Reply-To: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>
References: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>
Message-ID: <erf1p6$4sj$1@sea.gmane.org>

Asrarahmed Kadri wrote:

> I want to develop an application which uses a database and some forms to 
> enter/modify the database.
> The application should also generate reports based on some fields.
>  
> What should I be using? Python or VB...

That is both a religious question, and fighting words...
>  
> I want to use Python.. IN that case, what should be my choice for the 
> Database..
>

Ahhh, that is ok then.

Assuming this is not a web-based application, then take a look at the 
Dabo framework:

http://dabodev.com/

It supports MySQL, PostgreSQL, Firebird and SQLite backends at the moment.

Take a look through the screencasts to get an idea about what Dabo can 
do for you.

http://dabodev.com/documentation

Don.


From jfabiani at yolo.com  Tue Feb 20 16:31:11 2007
From: jfabiani at yolo.com (johnf)
Date: Tue, 20 Feb 2007 07:31:11 -0800
Subject: [Tutor] Visual Basic versus Python.. What to choose??
In-Reply-To: <erf1p6$4sj$1@sea.gmane.org>
References: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>
	<erf1p6$4sj$1@sea.gmane.org>
Message-ID: <200702200731.11532.jfabiani@yolo.com>

On Tuesday 20 February 2007 06:49, Don Taylor wrote:
> Asrarahmed Kadri wrote:
> > I want to develop an application which uses a database and some forms to
> > enter/modify the database.
> > The application should also generate reports based on some fields.
> >
> > What should I be using? Python or VB...
>
> That is both a religious question, and fighting words...
>
> > I want to use Python.. IN that case, what should be my choice for the
> > Database..
>
> Ahhh, that is ok then.
>
> Assuming this is not a web-based application, then take a look at the
> Dabo framework:
>
> http://dabodev.com/
>
> It supports MySQL, PostgreSQL, Firebird and SQLite backends at the moment.
>
> Take a look through the screencasts to get an idea about what Dabo can
> do for you.
>
> http://dabodev.com/documentation
>
> Don.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
Supports Ms SQL too.  
-- 
John Fabiani

From deliberatus at verizon.net  Tue Feb 20 16:46:11 2007
From: deliberatus at verizon.net (Kirk Z Bailey)
Date: Tue, 20 Feb 2007 10:46:11 -0500
Subject: [Tutor] It lives...
Message-ID: <45DB17C3.1060301@verizon.net>

I'm back.

Melted my life, got a divorce, gutted the house, acquired true love, 2 
cats, redid house, new job, and dentures. Let's see, I still need a 
total blood change-out, but other than that, I did it all.

Now I can start paying attention to python and wiki's again.

And this is good, because the new edition of python does not like my 
windows wiki very well. Seems when it reads the page in, it creates the 
data in a list- with everything in one cell, not one line per cell. 
Hmmm.... it did not used to do this... bitrot?


-- 
end

Very Truly yours,
                  - Kirk Bailey,
                    Largo Florida

                        kniht
                       +-----+
                       | BOX |
                       +-----+
                        think


From ajkadri at googlemail.com  Tue Feb 20 20:58:46 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Tue, 20 Feb 2007 19:58:46 +0000
Subject: [Tutor] Visual Basic versus Python.. What to choose??
In-Reply-To: <1171966635.45dacaabb2654@imp.free.fr>
References: <b4e894c70702200146q523f0c7cnb113a729aefeec7a@mail.gmail.com>
	<1171966635.45dacaabb2654@imp.free.fr>
Message-ID: <b4e894c70702201158v74af246ey4a576579d22e9cc1@mail.gmail.com>

Thanks a lot for the support.......

Cheers

On 2/20/07, carpentier.th at free.fr <carpentier.th at free.fr> wrote:
>
> Hi!
>
> With python, you can work with a lot of Database, likes mysql, oracle,
> sqlite,
> SQLServer, PostgreSQL....
>
> If you use Python2.5, sqlite3 is already installed.
>
> However, you can choose any data base which you want to use.
>
> Thomas
>
>
> Selon Asrarahmed Kadri <ajkadri at googlemail.com>:
>
> > Hi folks,
> >
> > I want to develop an application which uses a database and some forms to
> > enter/modify the database.
> > The application should also generate reports based on some fields.
> >
> > What should I be using? Python or VB...
> >
> > I want to use Python.. IN that case, what should be my choice for the
> > Database..
> >
> > Thanks in anticipation.
> >
> > Best Regards,
> > Asrarahmed Kadri
> >
> >
> >
> >
> > --
> > To HIM you shall return.
> >
>
>
>


-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070220/6ea666cc/attachment.html 

From pine508 at hotmail.com  Tue Feb 20 21:33:46 2007
From: pine508 at hotmail.com (Pine Marten)
Date: Tue, 20 Feb 2007 15:33:46 -0500
Subject: [Tutor] using SQLite with matplotlib - queries vs. lists
Message-ID: <BAY18-F9DF3BADA71643C3114AFCE0890@phx.gbl>

I'm a novice hoping to use data stored in an SQLite database to make simple 
graphs using matplotlib embedded in a wxPython GUI.  I noticed that 
matplotlib uses lists of integers to make graphs, such as the simple example 
(from the tutorial) of:

from pylab import *
plot([1,2,3,4])
show()

But SQLite queries return as a list of tuples in rows, not a list of 
numbers.  For some reason I haven't found a way any ready-made converter for 
this purpose.  As an exercise, I've wrote this function that converts them:

#takes the result of a fetchall() in sql and returns it as a list of numbers
#assumes you've done the query first, i.e. cur.execute('SELECT * FROM 
table')
import sqlite3
import string
def query_to_list():
    queryresult = cur.fetchall()
    print "Queryresult is ", queryresult
    queryrows = []
    for tuple in queryresult:
        num = tuple[0]
        queryrows.append(num)
    querylist = []
    for row in queryrows:
        num = int(row)
        querylist.append(num)
    print "Query list is: ", querylist

My question is, is there a better way to do this, or is there a ready-made 
way to go from an sql database to matplotlib?  I tried searching for it in 
various ways but haven't found anything.  I feel as though there should be a 
more direct way to go from a db to a plot.

Thanks in advance,
Chae

_________________________________________________________________
Mortgage rates as low as 4.625% - Refinance $150,000 loan for $579 a month. 
Intro*Terms  http://www.NexTag.com


From kent37 at tds.net  Tue Feb 20 21:52:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Feb 2007 15:52:42 -0500
Subject: [Tutor] using SQLite with matplotlib - queries vs. lists
In-Reply-To: <BAY18-F9DF3BADA71643C3114AFCE0890@phx.gbl>
References: <BAY18-F9DF3BADA71643C3114AFCE0890@phx.gbl>
Message-ID: <45DB5F9A.8060103@tds.net>

Pine Marten wrote:
> I'm a novice hoping to use data stored in an SQLite database to make simple 
> graphs using matplotlib embedded in a wxPython GUI.  I noticed that 
> matplotlib uses lists of integers to make graphs, such as the simple example 
> (from the tutorial) of:
> 
> from pylab import *
> plot([1,2,3,4])
> show()
> 
> But SQLite queries return as a list of tuples in rows, not a list of 
> numbers.  For some reason I haven't found a way any ready-made converter for 
> this purpose.  As an exercise, I've wrote this function that converts them:
> 
> #takes the result of a fetchall() in sql and returns it as a list of numbers
> #assumes you've done the query first, i.e. cur.execute('SELECT * FROM 
> table')
> import sqlite3
> import string
> def query_to_list():
>     queryresult = cur.fetchall()
>     print "Queryresult is ", queryresult
>     queryrows = []
>     for tuple in queryresult:
>         num = tuple[0]
>         queryrows.append(num)
>     querylist = []
>     for row in queryrows:
>         num = int(row)
>         querylist.append(num)
>     print "Query list is: ", querylist

This whole function can be replaced with
     querylist = [ int(row[0]) for rowin cur.fetchall() ]

PS Don't use tuple as a variable name, you will shadow the built-in tuple.

Kent

> 
> My question is, is there a better way to do this, or is there a ready-made 
> way to go from an sql database to matplotlib?  I tried searching for it in 
> various ways but haven't found anything.  I feel as though there should be a 
> more direct way to go from a db to a plot.
> 
> Thanks in advance,
> Chae
> 
> _________________________________________________________________
> Mortgage rates as low as 4.625% - Refinance $150,000 loan for $579 a month. 
> Intro*Terms  http://www.NexTag.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From nephish at gmail.com  Tue Feb 20 23:02:16 2007
From: nephish at gmail.com (shawn bright)
Date: Tue, 20 Feb 2007 16:02:16 -0600
Subject: [Tutor] how to read one bit of a byte
Message-ID: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>

lo there all,

i am reading a binary file with open('myfile', 'rb')

then i do a read(1) to read one byte. cool so far.

but how do i read the individual bits of a byte

i mean if i have a = read(1)

how do i know what the msb of a is ?

i need to know because i have to see if the msb is set and i also need to
know the value of the next bit.

any tips would be greatly appreciated.

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070220/22b579ed/attachment.htm 

From rabidpoobear at gmail.com  Tue Feb 20 23:15:22 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 20 Feb 2007 16:15:22 -0600
Subject: [Tutor] how to read one bit of a byte
In-Reply-To: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>
Message-ID: <45DB72FA.5040602@gmail.com>

shawn bright wrote:
> lo there all,
>
> i am reading a binary file with open('myfile', 'rb')
>
> then i do a read(1) to read one byte. cool so far.
>
> but how do i read the individual bits of a byte
>
> i mean if i have a = read(1)
>
> how do i know what the msb of a is ?
>
> i need to know because i have to see if the msb is set and i also need 
> to know the value of the next bit.
Well, you know the value of the MSB is...
1 2 4 8 16 32 64 128
so if you divide the value by 128, and get a 1 and not a 0, then it's set.
People commonly write functions to make binary lists from values.
-Luke
>
> any tips would be greatly appreciated.
>
> thanks
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From marilyn at deliberate.com  Wed Feb 21 00:05:04 2007
From: marilyn at deliberate.com (Marilyn Davis)
Date: Tue, 20 Feb 2007 15:05:04 -0800
Subject: [Tutor] re and MULTILINE
Message-ID: <20070220235005.9F8D91E4002@bag.python.org>

Hello Tutors,

I'm trying to get a grip on MULTILINE and I guess I don't have it.

Here's some code:

#!/usr/bin/env python
import re

def sub_it(mo):
    return 'xxx'

def test(re_str, data):
    return re.sub(re_str, sub_it, data, re.MULTILINE)
        
if __name__ == '__main__':
    data = '''Betty Boop:245-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000
'''
    re_str = r'''(d+)$'''
    print test(re_str, data)    
    
    re_str = r'''(d+)'''
    print test(re_str, data)

'''
./re_test2.py
Betty Boop:245-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:xxx

Betty Boop:xxx-xxx-xxx:xxx Ware Road, Milton, PA xxx:xxx/xxx/xxx:43500
Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000
'''

If I don't anchor it with '$', it gets all the digit-groups in the first line except the last one.  Why not the last one?  Whay not the other lines?

If I do anchor it, it only gets the last group on the last line.  What's up with that?

What I really want, is to mess with each of the last digit-groups on each line.  But I can't find them.

The exercise is from Ellie Quigley's "Perl by Example"

Thank you for any help.

Marilyn Davis



From shadabsayani at yahoo.com  Wed Feb 21 01:41:26 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Wed, 21 Feb 2007 00:41:26 +0000 (GMT)
Subject: [Tutor] Reading compressed files
Message-ID: <20070221004126.39723.qmail@web38708.mail.mud.yahoo.com>

Hi,
  I have compressed files compressed using different techniques  (especially unix compress). So I want to have a module that reads any  of these (.Z,.bz,.tgz files) files and manipulates the data.
  The data has a syntax.It contains
  HEADER (some information)
  BODY      (some information)
  FOOTER   (some information)
  If it were a normal text file I can get the values corresponding to HEADER BODY and FOOTER by open function.
  But here the files are in different format .Z , .bz ,.tgz,.gz .But I  know these are the only formats.Also I cannot rely upon the extensions  of the file (a .Z file can have no extension at all).Is there a way to  identify  which file am I reading and then  read it?If so how  to read it?
  Thanks and Regards,
  Shadab.
 Send instant messages to your online friends http://uk.messenger.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070221/6622e934/attachment.htm 

From kent at kentsjohnson.com  Wed Feb 21 03:15:50 2007
From: kent at kentsjohnson.com (Kent Johnson)
Date: Tue, 20 Feb 2007 21:15:50 -0500
Subject: [Tutor] re and MULTILINE
In-Reply-To: <20070220235005.9F8D91E4002@bag.python.org>
References: <20070220235005.9F8D91E4002@bag.python.org>
Message-ID: <45DBAB56.3020905@kentsjohnson.com>

Marilyn Davis wrote:
> Hello Tutors,
>
> I'm trying to get a grip on MULTILINE and I guess I don't have it.
>
> Here's some code:
>
> #!/usr/bin/env python
> import re
>
> def sub_it(mo):
>     return 'xxx'
>
> def test(re_str, data):
>     return re.sub(re_str, sub_it, data, re.MULTILINE)
>   
The fourth argument to re.sub() is a count, not flags. You have to 
compile the regex and pass the MULTILINE flag to the compile, or include 
the flag in the actual regex with *|(?m)|*.

Kent


>         
> if __name__ == '__main__':
>     data = '''Betty Boop:245-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
> Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
> James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000
> '''
>     re_str = r'''(d+)$'''
>     print test(re_str, data)    
>     
>     re_str = r'''(d+)'''
>     print test(re_str, data)
>
> '''
> ./re_test2.py
> Betty Boop:245-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
> Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
> James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:xxx
>
> Betty Boop:xxx-xxx-xxx:xxx Ware Road, Milton, PA xxx:xxx/xxx/xxx:43500
> Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
> James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000
> '''
>
> If I don't anchor it with '$', it gets all the digit-groups in the first line except the last one.  Why not the last one?  Whay not the other lines?
>
> If I do anchor it, it only gets the last group on the last line.  What's up with that?
>
> What I really want, is to mess with each of the last digit-groups on each line.  But I can't find them.
>
> The exercise is from Ellie Quigley's "Perl by Example"
>
> Thank you for any help.
>
> Marilyn Davis
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From cspears2002 at yahoo.com  Wed Feb 21 03:32:30 2007
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Tue, 20 Feb 2007 18:32:30 -0800 (PST)
Subject: [Tutor] summer_v04.py
Message-ID: <946814.6943.qm@web51602.mail.yahoo.com>

I've been working on a version of a script I found in
"Programming Python".  The helpful users of this forum
gave me some advice to make the code less wordy.  Here
is the code:

#!/usr/bin/python
import string

def find_longest_line(fileName):
	line_list = [line.split() for line in open(fileName,
'r').readlines()]
	numCols = max(len(cols) for cols in line_list)
	#print numCols
	return numCols

def summer(fileName):
	length_longest_col = find_longest_line(fileName)
	sums = [0] * length_longest_col
	for line in line_list:
		cols = string.split(line)
		for i in range(len(cols)):
			sums[i] = sums[i] + float(cols[i])
	return sums
			
if __name__ == '__main__':
	import sys
	print summer(sys.argv[1])
	#print find_longest_line(sys.argv[1])
	
The code opens a file called table.txt:
1       5       10      2       1.0
2       10      20      4       2.0     3
3       15      30      8       3       2       1
4       20      40      16      4.0

Then the script adds the columns in the file together.

However, when I run the script, I get a syntax error:

io at io-station-1 ./text_proc 151> ./summer_v04.py
table.txt
  File "./summer_v04.py", line 6
    numCols = max(len(cols) for cols in line_list)
                              ^
SyntaxError: invalid syntax

I can't figure out what the error is.

-Chris

From john at fouhy.net  Wed Feb 21 03:55:18 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 21 Feb 2007 15:55:18 +1300
Subject: [Tutor] summer_v04.py
In-Reply-To: <946814.6943.qm@web51602.mail.yahoo.com>
References: <946814.6943.qm@web51602.mail.yahoo.com>
Message-ID: <5e58f2e40702201855w620a2edesa14144653e405627@mail.gmail.com>

On 21/02/07, Christopher Spears <cspears2002 at yahoo.com> wrote:
> io at io-station-1 ./text_proc 151> ./summer_v04.py
> table.txt
>   File "./summer_v04.py", line 6
>     numCols = max(len(cols) for cols in line_list)
>                               ^
> SyntaxError: invalid syntax

What version of python are you running?

If you are running 2.3.x or earlier, you will need to rewrite this as:

    numCols = max([len(cols) for cols in line_list])

(because you are using a generator expression, and they were only
introduced in 2.4)

-- 
John.

From marilyn at deliberate.com  Wed Feb 21 04:02:12 2007
From: marilyn at deliberate.com (Marilyn Davis)
Date: Tue, 20 Feb 2007 19:02:12 -0800 (PST)
Subject: [Tutor] re and MULTILINE
In-Reply-To: <45DBAB56.3020905@kentsjohnson.com>
Message-ID: <Pine.LNX.4.44.0702201857070.29957-100000@localhost.localdomain>

On Tue, 20 Feb 2007, Kent Johnson wrote:

> Marilyn Davis wrote:
> > Hello Tutors,
> >
> > I'm trying to get a grip on MULTILINE and I guess I don't have it.
> >
> > Here's some code:
> >
> > #!/usr/bin/env python
> > import re
> >
> > def sub_it(mo):
> >     return 'xxx'
> >
> > def test(re_str, data):
> >     return re.sub(re_str, sub_it, data, re.MULTILINE)
> >   
> The fourth argument to re.sub() is a count, not flags. You have to 
> compile the regex and pass the MULTILINE flag to the compile, or include 
> the flag in the actual regex with *|(?m)|*.

Thank you so much!!  Duh.  Geeso, I looked at that for hours.

I should have asked for help sooner.

Gratefully,

Marilyn

> 
> Kent
> 
> 
> >         
> > if __name__ == '__main__':
> >     data = '''Betty Boop:245-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
> > Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
> > James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000
> > '''
> >     re_str = r'''(d+)$'''
> >     print test(re_str, data)    
> >     
> >     re_str = r'''(d+)'''
> >     print test(re_str, data)
> >
> > '''
> > ./re_test2.py
> > Betty Boop:245-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
> > Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
> > James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:xxx
> >
> > Betty Boop:xxx-xxx-xxx:xxx Ware Road, Milton, PA xxx:xxx/xxx/xxx:43500
> > Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
> > James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000
> > '''
> >
> > If I don't anchor it with '$', it gets all the digit-groups in the first line except the last one.  Why not the last one?  Whay not the other lines?
> >
> > If I do anchor it, it only gets the last group on the last line.  What's up with that?
> >
> > What I really want, is to mess with each of the last digit-groups on each line.  But I can't find them.
> >
> > The exercise is from Ellie Quigley's "Perl by Example"
> >
> > Thank you for any help.
> >
> > Marilyn Davis
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >   
> 
> 

-- 


From rikard.bosnjakovic at gmail.com  Wed Feb 21 04:39:05 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 21 Feb 2007 04:39:05 +0100
Subject: [Tutor] summer_v04.py
In-Reply-To: <5e58f2e40702201855w620a2edesa14144653e405627@mail.gmail.com>
References: <946814.6943.qm@web51602.mail.yahoo.com>
	<5e58f2e40702201855w620a2edesa14144653e405627@mail.gmail.com>
Message-ID: <d9e88eaf0702201939k2e3afcedh66394f4c6515265f@mail.gmail.com>

On 2/21/07, John Fouhy <john at fouhy.net> wrote:

> (because you are using a generator expression, and they were only
> introduced in 2.4)

List comprehensions were implemented in v2.0. The OP probably does not
use an older version, but as far as I can see, his syntax error line
uses parenthesis - not brackets - hence the error.


-- 
- Rikard.

From nephish at gmail.com  Wed Feb 21 05:40:30 2007
From: nephish at gmail.com (shawn bright)
Date: Tue, 20 Feb 2007 22:40:30 -0600
Subject: [Tutor] how to read one bit of a byte
In-Reply-To: <45DB72FA.5040602@gmail.com>
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>
	<45DB72FA.5040602@gmail.com>
Message-ID: <384c93600702202040k627ecb6vfd9f1588e1df364b@mail.gmail.com>

great, thanks for this. appreciate it a lot.

sk

On 2/20/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> shawn bright wrote:
> > lo there all,
> >
> > i am reading a binary file with open('myfile', 'rb')
> >
> > then i do a read(1) to read one byte. cool so far.
> >
> > but how do i read the individual bits of a byte
> >
> > i mean if i have a = read(1)
> >
> > how do i know what the msb of a is ?
> >
> > i need to know because i have to see if the msb is set and i also need
> > to know the value of the next bit.
> Well, you know the value of the MSB is...
> 1 2 4 8 16 32 64 128
> so if you divide the value by 128, and get a 1 and not a 0, then it's set.
> People commonly write functions to make binary lists from values.
> -Luke
> >
> > any tips would be greatly appreciated.
> >
> > thanks
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > 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/20070220/7557e2e1/attachment.htm 

From rdm at rcblue.com  Wed Feb 21 05:47:28 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 20 Feb 2007 20:47:28 -0800
Subject: [Tutor] Function for converting ints from base10 to base2?
Message-ID: <20070221044827.3E1931E4002@bag.python.org>

I was surprised to be unable to find a function in Python for 
converting ints from base10 to base2. Is there one?

I wrote one, but have I reinvented the wheel again? (Even if I have, 
it was an interesting exercise for me.)

I know some of you CS people won't like what I do with negative ints, 
but I wanted it this way. On other points than that, I'd appreciate 
criticism/suggestions.

===========================================================
def computeBin(n):
     """converts base10 integer n to base2 b as string"""
     from math import log, floor
     sign = ''
     if n == 0:
         b = '0'
     else:
         if n < 0:
             sign = "-"
             n = -n
         e = int(floor(log(n,2)))
         b = '1'

         for x in range(e):
             r = n % 2**e
             if r >= 2**(e-1):
                 b += '1'
             else:
                 b += '0'
             e -= 1
     return sign + b

def printResult(n,b):
     print "%d is %s" % (n, b)

def confirmResult(n,b):
     print "Confirming using int():"
     print "int(%s,2) is %s" % (b, int(b,2))

if __name__ == '__main__':
     n = 1234567890
     b = computeBin(n)
     printResult(n,b)
     confirmResult(n,b)
==============================================

Dick Moores


From dperlman at wisc.edu  Wed Feb 21 06:04:37 2007
From: dperlman at wisc.edu (David Perlman)
Date: Tue, 20 Feb 2007 23:04:37 -0600
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <20070221044827.3E1931E4002@bag.python.org>
References: <20070221044827.3E1931E4002@bag.python.org>
Message-ID: <2E1A0C48-5927-40EA-B54A-FF45F009B55A@wisc.edu>

I suspect the function I sent out earlier, using octal conversion and  
a lookup table, will be faster.  But it would be very interesting to  
see some simple benchmarks.

On Feb 20, 2007, at 10:47 PM, Dick Moores wrote:

> I was surprised to be unable to find a function in Python for
> converting ints from base10 to base2. Is there one?
>
> I wrote one, but have I reinvented the wheel again? (Even if I have,
> it was an interesting exercise for me.)
>
> I know some of you CS people won't like what I do with negative ints,
> but I wanted it this way. On other points than that, I'd appreciate
> criticism/suggestions.
>
> ===========================================================
> def computeBin(n):
>      """converts base10 integer n to base2 b as string"""
>      from math import log, floor
>      sign = ''
>      if n == 0:
>          b = '0'
>      else:
>          if n < 0:
>              sign = "-"
>              n = -n
>          e = int(floor(log(n,2)))
>          b = '1'
>
>          for x in range(e):
>              r = n % 2**e
>              if r >= 2**(e-1):
>                  b += '1'
>              else:
>                  b += '0'
>              e -= 1
>      return sign + b
>
> def printResult(n,b):
>      print "%d is %s" % (n, b)
>
> def confirmResult(n,b):
>      print "Confirming using int():"
>      print "int(%s,2) is %s" % (b, int(b,2))
>
> if __name__ == '__main__':
>      n = 1234567890
>      b = computeBin(n)
>      printResult(n,b)
>      confirmResult(n,b)
> ==============================================
>
> Dick Moores
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From deliberatus at verizon.net  Wed Feb 21 06:17:21 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 21 Feb 2007 00:17:21 -0500
Subject: [Tutor] list problem
Message-ID: <45DBD5E1.7030804@verizon.net>

ok, getting back to python and wikiness, I have a problem, this software 
of mine seems to exibit different behavior under the latest edition of 
python (2.5) than under the version used when I first wrote it (2.3).

It loads the page file, but returns it as a list (which is correcft) of 
one element, the entire file is in one cell. Prior, it returned each 
line as an element in the list. this is causing me some processing 
problems, and I am not a happy camper.

I am still getting out the WD-40 and loosening up rusty hinges and 
joints oin my python processing prefrontals, it's been quite a while. I 
cna post the current program to a website if it would help, or send it 
to you off list directly.

The idea is to use MiniWiki in one's windoze laptop as a wiki/notebook. 
Wikinehesa is optimied for freebsd/linux and works fine as is.

Discussion on or off list is saught. Constructive criticism will be 
graciously received and thanked.


From rabidpoobear at gmail.com  Wed Feb 21 06:29:03 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 20 Feb 2007 23:29:03 -0600
Subject: [Tutor] list problem
In-Reply-To: <45DBD5E1.7030804@verizon.net>
References: <45DBD5E1.7030804@verizon.net>
Message-ID: <45DBD89F.60102@gmail.com>

Kirk Bailey wrote:
> ok, getting back to python and wikiness, I have a problem, this software 
> of mine seems to exibit different behavior under the latest edition of 
> python (2.5) than under the version used when I first wrote it (2.3).
>
> It loads the page file, but returns it as a list (which is correcft) of 
> one element, the entire file is in one cell. Prior, it returned each 
> line as an element in the list. this is causing me some processing 
> problems, and I am not a happy camper.
>
> I am still getting out the WD-40 and loosening up rusty hinges and 
> joints oin my python processing prefrontals, it's been quite a while. I 
> cna post the current program to a website if it would help, or send it 
> to you off list directly.
>
> The idea is to use MiniWiki in one's windoze laptop as a wiki/notebook. 
> Wikinehesa is optimied for freebsd/linux and works fine as is.
>
> Discussion on or off list is saught. Constructive criticism will be 
> graciously received and thanked.
>
>   
If you could give us a snippet of input data,
as well as the function and the 10 or so lines preceding and following 
it, that returns a single-element list,
we could probably help.  Or better yet, write a new function that's very 
simple that just displays the behavior you don't want.
It sounds like you have a lot of code, though, and since you know where 
the problem is occurring it's easier if you give us an excerpt,
the cliffs notes version, if you will, than for one of us to read 
through your code.
-Luke

From rikard.bosnjakovic at gmail.com  Wed Feb 21 06:29:36 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 21 Feb 2007 06:29:36 +0100
Subject: [Tutor] list problem
In-Reply-To: <45DBD5E1.7030804@verizon.net>
References: <45DBD5E1.7030804@verizon.net>
Message-ID: <d9e88eaf0702202129n2741edc5l7c2eac9c7ecc046a@mail.gmail.com>

On 2/21/07, Kirk Bailey <deliberatus at verizon.net> wrote:

[...]
> Discussion on or off list is saught. Constructive criticism will be
> graciously received and thanked.

Without links, pointers, code or anything grippable I find it
difficult to comment or discuss anything, since i haven't got the
faintest idea or your setup, environments, applications, and the like.

How about giving it another go, feeding us with more info?

-- 
- Rikard.

From rabidpoobear at gmail.com  Wed Feb 21 06:48:04 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 20 Feb 2007 23:48:04 -0600
Subject: [Tutor] list problem
In-Reply-To: <45DBDBEE.4020607@verizon.net>
References: <45DBD5E1.7030804@verizon.net> <45DBD89F.60102@gmail.com>
	<45DBDBEE.4020607@verizon.net>
Message-ID: <45DBDD14.3010808@gmail.com>

Kirk:
Please reply to this message, not the other one I sent,
and please reply on-list in the future, using the 'reply-all' button 
rather than 'reply.'
Otherwise the message just goes to me instead of to everyone, which is 
the default on this list.
This copy of your e-mail is forwarded to the list, so use a 'reply-all' 
on it so everyone can see your reply.
-Luke


Original e-mail:

Kirk Bailey wrote:
> ok, here comes some code:
>
> f1=open(pagename,'r')
> page=f1.readlines()
> f1.close()
>
> at the end of which, the data is in page, which is a list. But 
> something strange is going on here. all the data is in a single cell! 
> it's a one cell list! Say what?
>
> Later on, when we try to itenerate the list and do things line by 
> line, it takes the entire thing at one swallow, and this creates some 
> trouble.
>
> Here's is a link to the entire program.
> http://www.tinylist.org/MW.txt
> this is the reader engine for a wiki to be used in a windows environment.
>
>
>
> Luke Paireepinart wrote:
>> Kirk Bailey wrote:
>>> ok, getting back to python and wikiness, I have a problem, this 
>>> software of mine seems to exibit different behavior under the latest 
>>> edition of python (2.5) than under the version used when I first 
>>> wrote it (2.3).
>>>
>>> It loads the page file, but returns it as a list (which is correcft) 
>>> of one element, the entire file is in one cell. Prior, it returned 
>>> each line as an element in the list. this is causing me some 
>>> processing problems, and I am not a happy camper.
>>>
>>> I am still getting out the WD-40 and loosening up rusty hinges and 
>>> joints oin my python processing prefrontals, it's been quite a 
>>> while. I cna post the current program to a website if it would help, 
>>> or send it to you off list directly.
>>>
>>> The idea is to use MiniWiki in one's windoze laptop as a 
>>> wiki/notebook. Wikinehesa is optimied for freebsd/linux and works 
>>> fine as is.
>>>
>>> Discussion on or off list is saught. Constructive criticism will be 
>>> graciously received and thanked.
>>>
>>>   
>> If you could give us a snippet of input data,
>> as well as the function and the 10 or so lines preceding and 
>> following it, that returns a single-element list,
>> we could probably help.  Or better yet, write a new function that's 
>> very simple that just displays the behavior you don't want.
>> It sounds like you have a lot of code, though, and since you know 
>> where the problem is occurring it's easier if you give us an excerpt,
>> the cliffs notes version, if you will, than for one of us to read 
>> through your code.
>> -Luke
>>
>>
>


From rdm at rcblue.com  Wed Feb 21 08:18:04 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 20 Feb 2007 23:18:04 -0800
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <2E1A0C48-5927-40EA-B54A-FF45F009B55A@wisc.edu>
References: <20070221044827.3E1931E4002@bag.python.org>
	<2E1A0C48-5927-40EA-B54A-FF45F009B55A@wisc.edu>
Message-ID: <20070221071810.E63FC1E4002@bag.python.org>

Well, I can't compare mine with yours (where is it?), but using the 
template in timeit.py:

template = """
def inner(_it, _timer):
     from decToBin import computeBin
     _t0 = _timer()
     for _i in _it:
         computeBin(12345678901234567890)
     _t1 = _timer()
     return _t1 - _t0
"""
I get these results:

for computeBin(12345678901234567890)
1000 loops, best of 3: 448 usec per loop

for computeBin(1234567890)
10000 loops, best of 3: 59.7 usec per loop

for computeBin(12345)
10000 loops, best of 3: 35.2 usec per loop

Dick Moores

At 09:04 PM 2/20/2007, David Perlman wrote:
>I suspect the function I sent out earlier, using octal conversion and
>a lookup table, will be faster.  But it would be very interesting to
>see some simple benchmarks.
>
>On Feb 20, 2007, at 10:47 PM, Dick Moores wrote:
>
> > I was surprised to be unable to find a function in Python for
> > converting ints from base10 to base2. Is there one?
> >
> > I wrote one, but have I reinvented the wheel again? (Even if I have,
> > it was an interesting exercise for me.)
> >
> > I know some of you CS people won't like what I do with negative ints,
> > but I wanted it this way. On other points than that, I'd appreciate
> > criticism/suggestions.
> >
> > ===========================================================
> > def computeBin(n):
> >      """converts base10 integer n to base2 b as string"""
> >      from math import log, floor
> >      sign = ''
> >      if n == 0:
> >          b = '0'
> >      else:
> >          if n < 0:
> >              sign = "-"
> >              n = -n
> >          e = int(floor(log(n,2)))
> >          b = '1'
> >
> >          for x in range(e):
> >              r = n % 2**e
> >              if r >= 2**(e-1):
> >                  b += '1'
> >              else:
> >                  b += '0'
> >              e -= 1
> >      return sign + b
> >
> > def printResult(n,b):
> >      print "%d is %s" % (n, b)
> >
> > def confirmResult(n,b):
> >      print "Confirming using int():"
> >      print "int(%s,2) is %s" % (b, int(b,2))
> >
> > if __name__ == '__main__':
> >      n = 1234567890
> >      b = computeBin(n)
> >      printResult(n,b)
> >      confirmResult(n,b)
> > ==============================================
> >
> > Dick Moores
> >
>
>--
>-dave----------------------------------------------------------------
>After all, it is not *that* inexpressible.
>-H.H. The Dalai Lama



From john at fouhy.net  Wed Feb 21 09:21:26 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 21 Feb 2007 21:21:26 +1300
Subject: [Tutor] list problem
In-Reply-To: <45DBDD14.3010808@gmail.com>
References: <45DBD5E1.7030804@verizon.net> <45DBD89F.60102@gmail.com>
	<45DBDBEE.4020607@verizon.net> <45DBDD14.3010808@gmail.com>
Message-ID: <5e58f2e40702210021p79bf648r627a59aaaccc60bb@mail.gmail.com>

> Kirk Bailey wrote:
> > ok, here comes some code:
> >
> > f1=open(pagename,'r')
> > page=f1.readlines()
> > f1.close()
> >
> > at the end of which, the data is in page, which is a list. But
> > something strange is going on here. all the data is in a single cell!
> > it's a one cell list! Say what?

Have you tried looking at pagename in a text editor?  If readlines()
is returning only one line, then you should be able to spot that in
the file.

-- 
John.

From klappnase at freenet.de  Wed Feb 21 11:18:33 2007
From: klappnase at freenet.de (Michael Lange)
Date: Wed, 21 Feb 2007 11:18:33 +0100
Subject: [Tutor] list problem
In-Reply-To: <5e58f2e40702210021p79bf648r627a59aaaccc60bb@mail.gmail.com>
References: <45DBD5E1.7030804@verizon.net> <45DBD89F.60102@gmail.com>
	<45DBDBEE.4020607@verizon.net> <45DBDD14.3010808@gmail.com>
	<5e58f2e40702210021p79bf648r627a59aaaccc60bb@mail.gmail.com>
Message-ID: <20070221111833.2cca7e01.klappnase@freenet.de>

On Wed, 21 Feb 2007 21:21:26 +1300
"John Fouhy" <john at fouhy.net> wrote:

> > Kirk Bailey wrote:
> > > ok, here comes some code:
> > >
> > > f1=open(pagename,'r')
> > > page=f1.readlines()
> > > f1.close()
> > >
> > > at the end of which, the data is in page, which is a list. But
> > > something strange is going on here. all the data is in a single cell!
> > > it's a one cell list! Say what?
> 
> Have you tried looking at pagename in a text editor?  If readlines()
> is returning only one line, then you should be able to spot that in
> the file.
> 

Just a guess: if the behavior changed in between Python-2.3 and 2.5 ,
maybe it is an issue with line endings, LF vs. CR-LF ?

Michael

From dperlman at wisc.edu  Wed Feb 21 14:00:33 2007
From: dperlman at wisc.edu (David Perlman)
Date: Wed, 21 Feb 2007 07:00:33 -0600
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <0JDS006L3XM6B3B0@smtp9.wiscmail.wisc.edu>
References: <20070221044827.3E1931E4002@bag.python.org>
	<2E1A0C48-5927-40EA-B54A-FF45F009B55A@wisc.edu>
	<0JDS006L3XM6B3B0@smtp9.wiscmail.wisc.edu>
Message-ID: <E9156D01-8BA9-4344-A0FD-109666295152@wisc.edu>

d'oh, I fell for the "reply-all" trick.  :)

Here's the code in question:

Apparently there are built in functions hex() and oct() to generate  
hexadecimal and octal digit strings of numbers, but there's no  
corresponding bin().  Kind of a bizarre oversight, if you ask me.

Searching on the internet, I found this:

def bin(integer, returnType=str):
	bin =  
{'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110',' 
7':'111'}
	if returnType == int:
		return int(''.join([bin[i] for i in oct(integer)]))
	elif returnType == long:
		return long(''.join([bin[i] for i in oct(integer)]),10)
	else:
		return (''.join([bin[i] for i in oct(integer)])).lstrip("0")

Just define this in the program you are writing and use bin as you
would use oct or hex, making sure to specify int or long as the return
type if you don't want a str.

On Feb 21, 2007, at 1:18 AM, Dick Moores wrote:

> Well, I can't compare mine with yours (where is it?), but using the  
> template in timeit.py:
>
> template = """
> def inner(_it, _timer):
>     from decToBin import computeBin
>     _t0 = _timer()
>     for _i in _it:
>         computeBin(12345678901234567890)
>     _t1 = _timer()
>     return _t1 - _t0
> """
> I get these results:
>
> for computeBin(12345678901234567890)
> 1000 loops, best of 3: 448 usec per loop
>
> for computeBin(1234567890)
> 10000 loops, best of 3: 59.7 usec per loop
>
> for computeBin(12345)
> 10000 loops, best of 3: 35.2 usec per loop
>
> Dick Moores
>
> At 09:04 PM 2/20/2007, David Perlman wrote:
>> I suspect the function I sent out earlier, using octal conversion and
>> a lookup table, will be faster.  But it would be very interesting to
>> see some simple benchmarks.
>>
>> On Feb 20, 2007, at 10:47 PM, Dick Moores wrote:
>>
>> > I was surprised to be unable to find a function in Python for
>> > converting ints from base10 to base2. Is there one?
>> >
>> > I wrote one, but have I reinvented the wheel again? (Even if I  
>> have,
>> > it was an interesting exercise for me.)
>> >
>> > I know some of you CS people won't like what I do with negative  
>> ints,
>> > but I wanted it this way. On other points than that, I'd appreciate
>> > criticism/suggestions.
>> >
>> > ===========================================================
>> > def computeBin(n):
>> >      """converts base10 integer n to base2 b as string"""
>> >      from math import log, floor
>> >      sign = ''
>> >      if n == 0:
>> >          b = '0'
>> >      else:
>> >          if n < 0:
>> >              sign = "-"
>> >              n = -n
>> >          e = int(floor(log(n,2)))
>> >          b = '1'
>> >
>> >          for x in range(e):
>> >              r = n % 2**e
>> >              if r >= 2**(e-1):
>> >                  b += '1'
>> >              else:
>> >                  b += '0'
>> >              e -= 1
>> >      return sign + b
>> >
>> > def printResult(n,b):
>> >      print "%d is %s" % (n, b)
>> >
>> > def confirmResult(n,b):
>> >      print "Confirming using int():"
>> >      print "int(%s,2) is %s" % (b, int(b,2))
>> >
>> > if __name__ == '__main__':
>> >      n = 1234567890
>> >      b = computeBin(n)
>> >      printResult(n,b)
>> >      confirmResult(n,b)
>> > ==============================================
>> >
>> > Dick Moores
>> >
>>
>> --
>> -dave----------------------------------------------------------------
>> After all, it is not *that* inexpressible.
>> -H.H. The Dalai Lama
>
>

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From kent37 at tds.net  Wed Feb 21 14:05:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 08:05:54 -0500
Subject: [Tutor] how to read one bit of a byte
In-Reply-To: <45DB72FA.5040602@gmail.com>
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>
	<45DB72FA.5040602@gmail.com>
Message-ID: <45DC43B2.9050604@tds.net>

Luke Paireepinart wrote:
> shawn bright wrote:
>> lo there all,
>>
>> i am reading a binary file with open('myfile', 'rb')
>>
>> then i do a read(1) to read one byte. cool so far.
>>
>> but how do i read the individual bits of a byte
>>
>> i mean if i have a = read(1)
>>
>> how do i know what the msb of a is ?
>>
>> i need to know because i have to see if the msb is set and i also need 
>> to know the value of the next bit.
> Well, you know the value of the MSB is...
> 1 2 4 8 16 32 64 128
> so if you divide the value by 128, and get a 1 and not a 0, then it's set.
> People commonly write functions to make binary lists from values.

This is also a good application of bitwise operations.

a & 128 will be 128 if the high bit in a is set, 0 if it is not.

Kent


From kent37 at tds.net  Wed Feb 21 14:11:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 08:11:13 -0500
Subject: [Tutor] summer_v04.py
In-Reply-To: <d9e88eaf0702201939k2e3afcedh66394f4c6515265f@mail.gmail.com>
References: <946814.6943.qm@web51602.mail.yahoo.com>	<5e58f2e40702201855w620a2edesa14144653e405627@mail.gmail.com>
	<d9e88eaf0702201939k2e3afcedh66394f4c6515265f@mail.gmail.com>
Message-ID: <45DC44F1.8030303@tds.net>

Rikard Bosnjakovic wrote:
> On 2/21/07, John Fouhy <john at fouhy.net> wrote:
> 
>> (because you are using a generator expression, and they were only
>> introduced in 2.4)
> 
> List comprehensions were implemented in v2.0. The OP probably does not
> use an older version, but as far as I can see, his syntax error line
> uses parenthesis - not brackets - hence the error.

Without the brackets it is a generator expression, as John correctly 
notes. Generator expressions were introduced in Python 2.4:
http://www.python.org/doc/2.4.4/whatsnew/node4.html

Kent


From kent37 at tds.net  Wed Feb 21 14:14:14 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 08:14:14 -0500
Subject: [Tutor] summer_v04.py
In-Reply-To: <946814.6943.qm@web51602.mail.yahoo.com>
References: <946814.6943.qm@web51602.mail.yahoo.com>
Message-ID: <45DC45A6.6080404@tds.net>

Christopher Spears wrote:
> I've been working on a version of a script I found in
> "Programming Python".  The helpful users of this forum
> gave me some advice to make the code less wordy.  Here
> is the code:
> 
> #!/usr/bin/python
> import string
> 
> def find_longest_line(fileName):
> 	line_list = [line.split() for line in open(fileName,
> 'r').readlines()]
> 	numCols = max(len(cols) for cols in line_list)
> 	#print numCols
> 	return numCols
> 
> def summer(fileName):
> 	length_longest_col = find_longest_line(fileName)
> 	sums = [0] * length_longest_col
> 	for line in line_list:
> 		cols = string.split(line)
> 		for i in range(len(cols)):
> 			sums[i] = sums[i] + float(cols[i])
> 	return sums
> 			
> if __name__ == '__main__':
> 	import sys
> 	print summer(sys.argv[1])
> 	#print find_longest_line(sys.argv[1])
> 	
> The code opens a file called table.txt:
> 1       5       10      2       1.0
> 2       10      20      4       2.0     3
> 3       15      30      8       3       2       1
> 4       20      40      16      4.0
> 
> Then the script adds the columns in the file together.
> 
> However, when I run the script, I get a syntax error:

When you fix the syntax error, which others have shown how to do, you 
will get a NameError in summer() because the name line_list is private 
to find_longest_line(). The simplest way to fix this would be to combine 
find_longest_line() and summer() or to read the file lines in summer() 
and pass line_list, instead of the file name, to find_longest_line().

Kent


From kent37 at tds.net  Wed Feb 21 14:23:00 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 08:23:00 -0500
Subject: [Tutor] list problem
In-Reply-To: <45DBDD14.3010808@gmail.com>
References: <45DBD5E1.7030804@verizon.net>
	<45DBD89F.60102@gmail.com>	<45DBDBEE.4020607@verizon.net>
	<45DBDD14.3010808@gmail.com>
Message-ID: <45DC47B4.1040904@tds.net>

> Kirk Bailey wrote:
>> ok, here comes some code:
>>
>> f1=open(pagename,'r')
>> page=f1.readlines()
>> f1.close()
>>
>> at the end of which, the data is in page, which is a list. But 
>> something strange is going on here. all the data is in a single cell! 
>> it's a one cell list! Say what?

It sounds like for some reason the newer Python is not recognizing the 
line endings in the file. I'm not sure why that would be; are you 
running both versions on the same OS? That could cause different 
behaviour since the default line ending is different on Windows and 
Linux, for example.

Try opening the file with universal line endings:
f1 = open(pagename, 'Ur')

Kent

>>
>> Later on, when we try to itenerate the list and do things line by 
>> line, it takes the entire thing at one swallow, and this creates some 
>> trouble.
>>
>> Here's is a link to the entire program.
>> http://www.tinylist.org/MW.txt
>> this is the reader engine for a wiki to be used in a windows environment.


From nephish at gmail.com  Wed Feb 21 16:18:28 2007
From: nephish at gmail.com (shawn bright)
Date: Wed, 21 Feb 2007 09:18:28 -0600
Subject: [Tutor] how to read one bit of a byte
In-Reply-To: <45DC43B2.9050604@tds.net>
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>
	<45DB72FA.5040602@gmail.com> <45DC43B2.9050604@tds.net>
Message-ID: <384c93600702210718x40afa2cfy5eff79aaab9f879e@mail.gmail.com>

even better, thanks much for this.
shawn

On 2/21/07, Kent Johnson <kent37 at tds.net> wrote:
> Luke Paireepinart wrote:
> > shawn bright wrote:
> >> lo there all,
> >>
> >> i am reading a binary file with open('myfile', 'rb')
> >>
> >> then i do a read(1) to read one byte. cool so far.
> >>
> >> but how do i read the individual bits of a byte
> >>
> >> i mean if i have a = read(1)
> >>
> >> how do i know what the msb of a is ?
> >>
> >> i need to know because i have to see if the msb is set and i also need
> >> to know the value of the next bit.
> > Well, you know the value of the MSB is...
> > 1 2 4 8 16 32 64 128
> > so if you divide the value by 128, and get a 1 and not a 0, then it's set.
> > People commonly write functions to make binary lists from values.
>
> This is also a good application of bitwise operations.
>
> a & 128 will be 128 if the high bit in a is set, 0 if it is not.
>
> Kent
>
>

From rabidpoobear at gmail.com  Wed Feb 21 17:29:53 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 21 Feb 2007 10:29:53 -0600
Subject: [Tutor] [Fwd: Re:  list problem]
Message-ID: <45DC7381.6050907@gmail.com>

Please stop sending me private messages.
And as I said before,
include the file as an attachment.
It does us no good to see the text.
We need to see the line endings.
And your (or my) e-mail program may mess with these.
-Luke
-------------- next part --------------
An embedded message was scrubbed...
From: Kirk Z Bailey <deliberatus at verizon.net>
Subject: Re: [Tutor] list problem
Date: Wed, 21 Feb 2007 11:04:09 -0500
Size: 3042
Url: http://mail.python.org/pipermail/tutor/attachments/20070221/a8fd6d1f/attachment.mht 

From atpridgen at mail.utexas.edu  Wed Feb 21 19:02:02 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Wed, 21 Feb 2007 12:02:02 -0600
Subject: [Tutor] Question about local scopes (namespaces)
Message-ID: <f989e6210702211002q50b9c338x6f05604fdff5d5c6@mail.gmail.com>

Sorry for the long email, and thanks in advance.

In the below example, is the list foo supposed to retain the value
after the function, Bar(), returns?

Is the list foo supposed to reinitialized on each call to Bar(),
meaning len(foo) == 0, and when Bar() returns len(foo) (when Bar() is
called w/out parameters)?

In the example, Bar() is called multiple times, and for the first
three times, I expect foo to initialized as an empty list.  When I
call Bar() and make the assignment however, it turns out that foo is
not reinitialized and it acts like a statically type variable in C or
Java (e.g. retaining its value from each call and subsequent
execution).  I would have expected only one instance of the string in
f after it is assigned the name of foo, however there are four.

My understanding of the code below is as follows:
--If Bar is called without any parameters, then foo is initialized as
an empty list, always.
--If Bar is called with a list parameter, then the name foo is aliased
to that object.
--In the last two cases, if Bar() returns a value to an assignment,
the list will be aliased to that variable name as well
--When Bar() returns, if there is nothing aliased to the list foo,
then the list is destroyed

Is the my understanding correct?  Thank you again for taking the time
to review my question.

--Adam


def Bar(foo=[]):
   foo.append("newb got a keyboard\n")
   return foo

if __name__ == "__main__":
   Bar()
   Bar()
   Bar()
   f = Bar()
   print f

Results:
C:\workspace\ProvingGrounds\src\Bill>python Bug.py
['newb got a keyboard\n', 'newb got a keyboard\n', 'newb got a
keyboard\n', 'newb got a keyboard\n']
-------------- next part --------------
A non-text attachment was scrubbed...
Name: example.py
Type: text/x-python
Size: 160 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070221/79cdd609/attachment-0001.py 

From kent37 at tds.net  Wed Feb 21 20:06:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 14:06:50 -0500
Subject: [Tutor] Question about local scopes (namespaces)
In-Reply-To: <f989e6210702211002q50b9c338x6f05604fdff5d5c6@mail.gmail.com>
References: <f989e6210702211002q50b9c338x6f05604fdff5d5c6@mail.gmail.com>
Message-ID: <45DC984A.5040205@tds.net>

Adam Pridgen wrote:
> Sorry for the long email, and thanks in advance.
> 
> In the below example, is the list foo supposed to retain the value
> after the function, Bar(), returns?

Yes

> Is the list foo supposed to reinitialized on each call to Bar(),
> meaning len(foo) == 0, and when Bar() returns len(foo) (when Bar() is
> called w/out parameters)?

No. See
http://www.effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

Kent


From nephish at gmail.com  Wed Feb 21 20:36:25 2007
From: nephish at gmail.com (shawn bright)
Date: Wed, 21 Feb 2007 13:36:25 -0600
Subject: [Tutor] stumped again adding bytes
Message-ID: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>

Hey all, thanks for the help yesterday on finding out if an msb is set or not.

i am now kinda stumped with discovering the value of two bytes together.

ok, if i have two bytes that together make a number, how do i find that number?
i know that i do not add them.

like byte_a = 39
byte_b = 138

together, they make 2599

in hex they look like this
byte_a = 0x27
byte_b = 0x8A

together = 0x0A27

i am making the integers with ord(a) and ord(b)

how do i put them together ?

thanks

From rabidpoobear at gmail.com  Wed Feb 21 21:18:55 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 21 Feb 2007 14:18:55 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
Message-ID: <45DCA92F.4070700@gmail.com>

shawn bright wrote:
> Hey all, thanks for the help yesterday on finding out if an msb is set or not.
>
> i am now kinda stumped with discovering the value of two bytes together.
>
> ok, if i have two bytes that together make a number, how do i find that number?
> i know that i do not add them.
>
> like byte_a = 39
> byte_b = 138
>
> together, they make 2599
>
> in hex they look like this
> byte_a = 0x27
> byte_b = 0x8A
>
> together = 0x0A27
>
> i am making the integers with ord(a) and ord(b)
>
> how do i put them together ?
>   
 >>> int("0x0A27",16)
2599

Hope that helps :)
-Luke
> thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From nephish at gmail.com  Wed Feb 21 21:25:02 2007
From: nephish at gmail.com (shawn bright)
Date: Wed, 21 Feb 2007 14:25:02 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <45DCA92F.4070700@gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
	<45DCA92F.4070700@gmail.com>
Message-ID: <384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>

oh, sorry, i meant how to get the 0x0A27 out of two bytes
a = 0x27 and b = 0x8A

actually, in my script, i am not using the hex values at all, i have
these because they are examples in the documentation of a machine i am
talking to. i am actually using ord(a) and ord(b) to get digital
values of the numbers

so, i guess a better question is how to get 2599 from the ord(a) and
ord(b), how do i put the two bytes together to make one number?

thanks for your help


On 2/21/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> shawn bright wrote:
> > Hey all, thanks for the help yesterday on finding out if an msb is set or not.
> >
> > i am now kinda stumped with discovering the value of two bytes together.
> >
> > ok, if i have two bytes that together make a number, how do i find that number?
> > i know that i do not add them.
> >
> > like byte_a = 39
> > byte_b = 138
> >
> > together, they make 2599
> >
> > in hex they look like this
> > byte_a = 0x27
> > byte_b = 0x8A
> >
> > together = 0x0A27
> >
> > i am making the integers with ord(a) and ord(b)
> >
> > how do i put them together ?
> >
>  >>> int("0x0A27",16)
> 2599
>
> Hope that helps :)
> -Luke
> > thanks
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>

From kent37 at tds.net  Wed Feb 21 21:34:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 15:34:44 -0500
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
Message-ID: <45DCACE4.20703@tds.net>

shawn bright wrote:
> Hey all, thanks for the help yesterday on finding out if an msb is set or not.
> 
> i am now kinda stumped with discovering the value of two bytes together.
> 
> i am making the integers with ord(a) and ord(b)
> 
> how do i put them together ?

If this is related to your earlier posts about reading a binary file, 
you should look at the struct module, rather than turning each byte into 
an integer and assembling them yourself.

You might also look into Construct which is a higher-level way of doing 
similar jobs.
http://construct.wikispaces.com/

Kent


From rabidpoobear at gmail.com  Wed Feb 21 21:37:36 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 21 Feb 2007 14:37:36 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>	
	<45DCA92F.4070700@gmail.com>
	<384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
Message-ID: <45DCAD90.2010101@gmail.com>

shawn bright wrote:
> oh, sorry, i meant how to get the 0x0A27 out of two bytes
> a = 0x27 and b = 0x8A
I don't see what the number 0x0A27 has to do with bytes 0x27 and 0x8A, 
but I'll assume you meant
0x0A for b.
>
> actually, in my script, i am not using the hex values at all, i have
> these because they are examples in the documentation of a machine i am
> talking to. i am actually using ord(a) and ord(b) to get digital
> values of the numbers
>
> so, i guess a better question is how to get 2599 from the ord(a) and
> ord(b), how do i put the two bytes together to make one number?
Well, if you have the bytes originally, instead of ording them, hex them.
so... given these bytes
bytelist = [chr(0x27),chr(0x8A)]
hexlist = []
for item in bytelist:
 hexlist.append(hex(item)[2:].zfill(2))

print int('0x' + ''.join(hexlist) , 16)

A less roundabout way to do this:

given the number
0x0A,
this is stored in the system the same as the number 10.
 >>> 0x0A
10
As you can see.
So having the ord values is okay, because they're the same values as the 
hex of the bytes, just represented in a different base.
Okay, now we'll assume that a byte is 8 bits.
Because of this, we know that the number
0xFFEE
is the same as
(0xFF << 8) + 0xEE
In other words, the higher byte is shifted over by 8 bits, and the other 
value is not shifted.
This idea could easily be expanded to encompass byte strings of any length.
Oh, and in the case of your example values,
 >>> (0x0A << 8) + 0x27
2599

Note that the + operator has higher (or the same?) precedence than the 
binary shift left.
This means that the value 0x0A will be shifted by 8+0x27 times if the 
parenthesis are missing.

Other equivalent operations:
 >>> 0x0A * 256 + 0x27
2599
 >>> 0x0A * 2**8 + 0x27
2599

But like Kent said, you probably should use struct or something like that.
Just in case you're interested, I'm sending this e-mail as well.
HTH,
-Luke
>>
>


From kent37 at tds.net  Wed Feb 21 21:47:00 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 15:47:00 -0500
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>	<45DCA92F.4070700@gmail.com>
	<384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
Message-ID: <45DCAFC4.1060406@tds.net>

shawn bright wrote:
> oh, sorry, i meant how to get the 0x0A27 out of two bytes
> a = 0x27 and b = 0x8A

Why is the correct result not 0x8A27 ?

Maybe this is what you want:
 >>> a=0x27
 >>> b=0x8a
 >>> (b & 0x7f) * 256 + a
2599

Kent


From alan.gauld at btinternet.com  Wed Feb 21 21:51:23 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Feb 2007 20:51:23 -0000
Subject: [Tutor] Struct the solution for Hex translation
References: <743FCAF0-DC27-487C-A79E-5CE98AE55D27@wisc.edu>
	<20070220062917.3EF56E4C1@mail.accesstel.co.za>
Message-ID: <eribck$ck3$1@sea.gmane.org>

"Johan Geldenhuys" <johan at accesstel.co.za> wrote 

> On the struct module, How can I het the binary 1's 
> and 0's of the Hex value? Let say I want to get the 
> 8 bit value of '\xe2', can I use struct to convert
> that into binary code 

No, struct converts your data into a string of bytes and 
provides a way to view a string representation of those 
bytes.

But you can use bitmasks to get at the individual bits. 
(See my Using the OS topic for a box on bitwise operators 
and use of bitmasks.)

Basically you want to bitwise AND the data with a mask 
containing just a one in the 8th position
(since 1& 0 = 0 and 1& 1 = 1)

Thus 10000000 = 80 hex. So:

>>> for n in range(125,130):
...    print n,':',n&0x80
...
125 : 0
126 : 0
127 : 0
128 : 128     <--- the one is set so the & returns the mask
129 : 128
>>>

> so that I get 8 binary bits as a string?

See the bin() function in the sidebar in my topic for a function to
display a number in its binary form.

-- 
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 Feb 21 21:53:42 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Feb 2007 20:53:42 -0000
Subject: [Tutor] It lives...
References: <45DB17C3.1060301@verizon.net>
Message-ID: <eribgu$d35$1@sea.gmane.org>

Hi Kirk,

We remember you :-)

"Kirk Z Bailey" <deliberatus at verizon.net> wrote

> And this is good, because the new edition of python does not like my
> windows wiki very well. Seems when it reads the page in, it creates 
> the
> data in a list- with everything in one cell, not one line per cell.
> Hmmm.... it did not used to do this... bitrot?

Maybe, but we need some code?
We're still not telepathic.

Alan G. 



From alan.gauld at btinternet.com  Wed Feb 21 21:57:17 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Feb 2007 20:57:17 -0000
Subject: [Tutor] how to read one bit of a byte
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>
Message-ID: <eribnm$dt2$1@sea.gmane.org>


"shawn bright" <nephish at gmail.com> wrote 

> but how do i read the individual bits of a byte
> how do i know what the msb of a is ?

See my reply to Johan in the thread Struct the solution...

Basically you can use a bitwise and with a mask 
containing only the bit you are interested in. Johan 
wanted the 8th bit so the mask was 10000000 = 0x80

Thus

bit8 = 0x80

if data & bit8: print 'bit 8 is 1'
else: print 'bit 8 is 0'

See my Using the OS topic sidebar for more info on bitmasks.

HTH,


-- 
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 Feb 21 22:02:10 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Feb 2007 21:02:10 -0000
Subject: [Tutor] Function for converting ints from base10 to base2?
References: <20070221044827.3E1931E4002@bag.python.org>
Message-ID: <eric0r$f68$1@sea.gmane.org>

"Dick Moores" <rdm at rcblue.com> wrote

>I was surprised to be unable to find a function in Python for
> converting ints from base10 to base2. Is there one?

The sidebar in my Using the OS topicv includes a function
to do this. It uses a simpler algorithm:

def bin(n):
   digits = {'0':'000','1':'001','2':'010','3':'011',
             '4':'100','5':'101','6':'110','7':'111'}
   octStr = "%o" % n # convert to octal string
   binStr = ''
   # convert octal digit to its binary equivalent
   for c in octStr: binStr += digits[c]
   return binStr> I wrote one, but have I reinvented the wheel again? 
(Even if I have,
> it was an interesting exercise for me.)

There are several versions of this using various techniques on
the net.

> I know some of you CS people won't like what I do with negative 
> ints,

And I'm not sure how mine handles negative ints - badly I suspect!


-- 
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 Feb 21 21:59:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Feb 2007 20:59:18 -0000
Subject: [Tutor] how to read one bit of a byte
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com><45DB72FA.5040602@gmail.com>
	<45DC43B2.9050604@tds.net>
Message-ID: <eribre$eb0$1@sea.gmane.org>


"Kent Johnson" <kent37 at tds.net> wrote 
> This is also a good application of bitwise operations.
> 
> a & 128 will be 128 if the high bit in a is set, 0 if it is not.

Only for an 8 bit integer! Most integers nowadays are 
32 bit so you need to use 0x80000000 to get the msb!

Alan G.




From nephish at gmail.com  Wed Feb 21 22:34:43 2007
From: nephish at gmail.com (shawn bright)
Date: Wed, 21 Feb 2007 15:34:43 -0600
Subject: [Tutor] how to read one bit of a byte
In-Reply-To: <eribre$eb0$1@sea.gmane.org>
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com>
	<45DB72FA.5040602@gmail.com> <45DC43B2.9050604@tds.net>
	<eribre$eb0$1@sea.gmane.org>
Message-ID: <384c93600702211334o1345da5dr5f90f4a8d3da8c3f@mail.gmail.com>

Hey thanks for all the help guys, i am at least pulling some values
that make sense.
i feel more like i am on my way.

thanks again
shawn

On 2/21/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Kent Johnson" <kent37 at tds.net> wrote
> > This is also a good application of bitwise operations.
> >
> > a & 128 will be 128 if the high bit in a is set, 0 if it is not.
>
> Only for an 8 bit integer! Most integers nowadays are
> 32 bit so you need to use 0x80000000 to get the msb!
>
> Alan G.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Wed Feb 21 22:50:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Feb 2007 16:50:35 -0500
Subject: [Tutor] how to read one bit of a byte
In-Reply-To: <eribre$eb0$1@sea.gmane.org>
References: <384c93600702201402v2b171743ncb3e25288f1a34b1@mail.gmail.com><45DB72FA.5040602@gmail.com>	<45DC43B2.9050604@tds.net>
	<eribre$eb0$1@sea.gmane.org>
Message-ID: <45DCBEAB.4010609@tds.net>

Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote 
>   
>> This is also a good application of bitwise operations.
>>
>> a & 128 will be 128 if the high bit in a is set, 0 if it is not.
>>     
>
> Only for an 8 bit integer! Most integers nowadays are 
> 32 bit so you need to use 0x80000000 to get the msb!
Right, but if you read the thread it is about byte values read from a 
file so presumably he is talking about 8-bit integers.

Kent

From alan.gauld at btinternet.com  Thu Feb 22 00:59:42 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Wed, 21 Feb 2007 23:59:42 +0000 (GMT)
Subject: [Tutor] how to read one bit of a byte
Message-ID: <385111.89504.qm@web86103.mail.ird.yahoo.com>


>>> a & 128 will be 128 if the high bit in a is set, 0 if it is not.
>>>     
>>
>> Only for an 8 bit integer! Most integers nowadays are 
>> 32 bit so you need to use 0x80000000 to get the msb!
> Right, but if you read the thread it is about byte values read from a 
> file so presumably he is talking about 8-bit integers.

Good point.

:-)

Alan G.





		
___________________________________________________________ 
What kind of emailer are you? Find out today - get a free analysis of your email personality. Take the quiz at the Yahoo! Mail Championship. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From bgailer at alum.rpi.edu  Thu Feb 22 01:57:56 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 21 Feb 2007 16:57:56 -0800
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <E9156D01-8BA9-4344-A0FD-109666295152@wisc.edu>
References: <20070221044827.3E1931E4002@bag.python.org>	<2E1A0C48-5927-40EA-B54A-FF45F009B55A@wisc.edu>	<0JDS006L3XM6B3B0@smtp9.wiscmail.wisc.edu>
	<E9156D01-8BA9-4344-A0FD-109666295152@wisc.edu>
Message-ID: <45DCEA94.304@alum.rpi.edu>

David Perlman wrote:
> d'oh, I fell for the "reply-all" trick.  :)
>
> Here's the code in question:
>
> Apparently there are built in functions hex() and oct() to generate  
> hexadecimal and octal digit strings of numbers, but there's no  
> corresponding bin().  Kind of a bizarre oversight, if you ask me.
>
> Searching on the internet, I found this:
>
> def bin(integer, returnType=str):
> 	bin =  
> {'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110',' 
> 7':'111'}
> 	if returnType == int:
> 		return int(''.join([bin[i] for i in oct(integer)]))
> 	elif returnType == long:
> 		return long(''.join([bin[i] for i in oct(integer)]),10)
> 	else:
> 		return (''.join([bin[i] for i in oct(integer)])).lstrip("0")
>
> Just define this in the program you are writing and use bin as you
> would use oct or hex, making sure to specify int or long as the return
> type if you don't want a str.
Here's a similar function, converting characters to their ascii values 
as strings of 0 & 1. Perhaps some parts of this might be useful to 
optimize the above.

def str_to_binary(s,
   bin=('0000','0001','0010','0011','0100','0101',
   '0110','0111','1000','1001','1010','1011','1100',
   '1101','1110','1111')):
  return " ".join( [bin[x]+bin[y] for x,y in [divmod(ord(c),16) for c in 
s]])

Note that by making bin a parameter it gets created one time when the 
def is executed. And indexing a list is faster than keying a dict.

-- 
Bob Gailer
510-978-4454


From carroll at tjc.com  Thu Feb 22 02:17:27 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 21 Feb 2007 17:17:27 -0800 (PST)
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <20070221044827.3E1931E4002@bag.python.org>
Message-ID: <Pine.LNX.4.44.0702211707580.12994-100000@violet.rahul.net>

On Tue, 20 Feb 2007, Dick Moores wrote:

> I was surprised to be unable to find a function in Python for 
> converting ints from base10 to base2. Is there one?
> 
> I wrote one, but have I reinvented the wheel again? (Even if I have, 
> it was an interesting exercise for me.)

I like the approach of mapping hex or octal digits posted by Alan and Bob,
but, not thinking of that, this would be my straightforward approach:

def computeBin(n):
     """converts base10 integer n to base2 b as string"""
     if n == 0: return '0'
     sign = ['','-'][n<0]
     num = abs(n)
     seq = []
     while (num != 0):
         (num, bit) = divmod(num, 2)
         seq.append(str(bit))
     seq.append(sign)
     return ''.join(reversed(seq))

if __name__ == "__main__":
    x = 1234567890
    assert x == int(computeBin(x),2)
    x = -1234567890
    assert x == int(computeBin(x),2)



From rdm at rcblue.com  Thu Feb 22 03:08:34 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 21 Feb 2007 18:08:34 -0800
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <Pine.LNX.4.44.0702211707580.12994-100000@violet.rahul.net>
References: <20070221044827.3E1931E4002@bag.python.org>
	<Pine.LNX.4.44.0702211707580.12994-100000@violet.rahul.net>
Message-ID: <20070222021248.97FAA1E4002@bag.python.org>

At 05:17 PM 2/21/2007, Terry Carroll wrote:
>On Tue, 20 Feb 2007, Dick Moores wrote:
>
> > I was surprised to be unable to find a function in Python for
> > converting ints from base10 to base2. Is there one?
> >
> > I wrote one, but have I reinvented the wheel again? (Even if I have,
> > it was an interesting exercise for me.)
>
>I like the approach of mapping hex or octal digits posted by Alan and Bob,
>but, not thinking of that, this would be my straightforward approach:
>
>def computeBin(n):
>      """converts base10 integer n to base2 b as string"""
>      if n == 0: return '0'
>      sign = ['','-'][n<0]
>      num = abs(n)
>      seq = []
>      while (num != 0):
>          (num, bit) = divmod(num, 2)
>          seq.append(str(bit))
>      seq.append(sign)
>      return ''.join(reversed(seq))
>
>if __name__ == "__main__":
>     x = 1234567890
>     assert x == int(computeBin(x),2)
>     x = -1234567890
>     assert x == int(computeBin(x),2)

Thanks!

But there's syntax(?) there I've never seen before. "['','-'][n<0]". 
I see it works:

 >>> n = -6
 >>> ['','-'][n<0]
'-'
 >>> n = 98
 >>> ['','-'][n<0]
''

What's this called? I'd like to look it up.

Dick


From john at fouhy.net  Thu Feb 22 03:33:17 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 22 Feb 2007 15:33:17 +1300
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <20070222021248.97FAA1E4002@bag.python.org>
References: <20070221044827.3E1931E4002@bag.python.org>
	<Pine.LNX.4.44.0702211707580.12994-100000@violet.rahul.net>
	<20070222021248.97FAA1E4002@bag.python.org>
Message-ID: <5e58f2e40702211833j4eb56395w761162ce353cf3f4@mail.gmail.com>

On 22/02/07, Dick Moores <rdm at rcblue.com> wrote:
> But there's syntax(?) there I've never seen before. "['','-'][n<0]".
> I see it works:
>
>  >>> n = -6
>  >>> ['','-'][n<0]
> '-'
>  >>> n = 98
>  >>> ['','-'][n<0]
> ''
>
> What's this called? I'd like to look it up.

It's taking advantage of the fact that booleans (True, False) are integers.

>>> 1 == True
True
>>> 0 == False
True
>>> ['zero', 'one'][True]
'one'

It's more compact, but less clear (IMO), so I'm not a big fan.

Hmm, and it may not be faster either:

Morpork:~ repton$ python -m timeit -s 'n=13' 'x=["", "-"][n<0]'
1000000 loops, best of 3: 0.6 usec per loop
Morpork:~ repton$ python -m timeit -s 'n=13' 'if n < 0:' ' x="-"'
'else:' ' x=""'
1000000 loops, best of 3: 0.251 usec per loop

-- 
John.

From carroll at tjc.com  Thu Feb 22 03:34:12 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 21 Feb 2007 18:34:12 -0800 (PST)
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <20070222021248.97FAA1E4002@bag.python.org>
Message-ID: <Pine.LNX.4.44.0702211819080.12994-100000@violet.rahul.net>

On Wed, 21 Feb 2007, Dick Moores wrote:

> But there's syntax(?) there I've never seen before. "['','-'][n<0]". 
> I see it works:
> 
>  >>> n = -6
>  >>> ['','-'][n<0]
> '-'
>  >>> n = 98
>  >>> ['','-'][n<0]
> ''
> 
> What's this called? I'd like to look it up.

It's nothing special; it's just a lookup in a list.

First, there's a list of strings; the two strings are an empty string ''
and a minus sign '-'.  That's this part: ['','-']

If n is less than zero, I want to pick up the minus sign; otherwise, I 
want to pick up the empty string.

The expression n<0 evaluates to the boolean True for the first case, and
False otherwise.  When using a boolean as an index in a list, True is
treated as 1;  False is treated as 0.  This is the only arguably tricky
part, if you've never played with booleans;  it's documented at
http://docs.python.org/ref/types.html: "Boolean values [False and True]
behave like the values 0 and 1, respectively, in almost all contexts...".

That's this part: [n<0]

So:

sign = ['','-'][n<0]

is more or less the equivalent of:

signlist = ['','-']
if n < 0:
  sign = signlist[1]
else:
  sign = signlist[0]


From malaclypse2 at gmail.com  Thu Feb 22 03:44:21 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Wed, 21 Feb 2007 21:44:21 -0500
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <16651e80702211843n7b823240je97b68b75419734b@mail.gmail.com>
References: <20070221044827.3E1931E4002@bag.python.org>
	<Pine.LNX.4.44.0702211707580.12994-100000@violet.rahul.net>
	<20070222021248.97FAA1E4002@bag.python.org>
	<16651e80702211843n7b823240je97b68b75419734b@mail.gmail.com>
Message-ID: <16651e80702211844r46379eb3pfcee83cc7150455a@mail.gmail.com>

On 2/21/07, Dick Moores <rdm at rcblue.com> wrote:
> But there's syntax(?) there I've never seen before. "['','-'][n<0]".
> I see it works:
>
>  >>> n = -6
>  >>> ['','-'][n<0]
> '-'
>  >>> n = 98
>  >>> ['','-'][n<0]
> ''
>
> What's this called? I'd like to look it up.

['', '-'] is a list with two elements: an empty string, and the string '-'.
[n<0] is an index into the list.

For example:
>>> a = ['First Element', 'Second Element']
>>> a[False]
'First Element'
>>> a[True]
'Second Element'

This works because int(True) is 1 and int(False) is 0.  Personally, I
find using boolean values to index a list to be hard to read.  If I
ever came back to looking at the code again, I'd rather have written
something like this:

sign = ''
if (n < 0): sign = '-'

It's an extra line of code, but it's a lot less cryptic to me.

--
Jerry

From carroll at tjc.com  Thu Feb 22 03:45:58 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 21 Feb 2007 18:45:58 -0800 (PST)
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <5e58f2e40702211833j4eb56395w761162ce353cf3f4@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0702211836400.12994-100000@violet.rahul.net>

Taking your points out of order....

On Thu, 22 Feb 2007, John Fouhy wrote:

> Hmm, and it may not be faster either:

That doesn't surprise me.  It must have all the logic of the if-else 
construct, and additionally must build a list.

> It's more compact, but less clear (IMO), so I'm not a big fan.

I used it primarily because it mirrored my thinking; I don't know what
that says about me!  That's how I've often implemented the trinary 
operator.  I would have used 

   sign = '-' if n<0 else ''

But I'm still on Python 2.4.  I guess

   sign = (n<0) and '-' or ''

is the pre-2.5 idiom, but I find that even less clear.



From pine508 at hotmail.com  Thu Feb 22 04:01:01 2007
From: pine508 at hotmail.com (Chae M)
Date: Wed, 21 Feb 2007 22:01:01 -0500
Subject: [Tutor] storing text in databases
Message-ID: <BAY18-F83A065046ED595FBA23C3E08F0@phx.gbl>

Is it a reasonable idea to store text (a few hundred words each
record) in a database?  I'm learning to use the SQLite database
that comes with Python, and it seems like a good idea in terms
of being able to search for notes, etc.  My specific questions:

- Can formatting of text be stored or is it always only raw text?
- What is the upper limit on the size of a stored document?  I.e.,
  would this also work for big documents (10-100 pages?)
- Is this a good idea/can it work?

TIA,
CM

_________________________________________________________________
With tax season right around the corner, make sure to follow these few 
simple tips. 
http://articles.moneycentral.msn.com/Taxes/PreparationTips/PreparationTips.aspx?icid=HMFebtagline


From broek at cc.umanitoba.ca  Thu Feb 22 03:40:00 2007
From: broek at cc.umanitoba.ca (Brian van den Broek)
Date: Wed, 21 Feb 2007 20:40:00 -0600
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <20070222021248.97FAA1E4002@bag.python.org>
References: <20070221044827.3E1931E4002@bag.python.org>	<Pine.LNX.4.44.0702211707580.12994-100000@violet.rahul.net>
	<20070222021248.97FAA1E4002@bag.python.org>
Message-ID: <45DD0280.3090301@cc.umanitoba.ca>

Dick Moores said unto the world upon 02/21/2007 08:08 PM:
> At 05:17 PM 2/21/2007, Terry Carroll wrote:

<snip>

>> I like the approach of mapping hex or octal digits posted by Alan and Bob,
>> but, not thinking of that, this would be my straightforward approach:
>>
>> def computeBin(n):
>>      """converts base10 integer n to base2 b as string"""
>>      if n == 0: return '0'
>>      sign = ['','-'][n<0]

<snip>

> 
> Thanks!
> 
> But there's syntax(?) there I've never seen before. "['','-'][n<0]". 
> I see it works:
> 
>  >>> n = -6
>  >>> ['','-'][n<0]
> '-'
>  >>> n = 98
>  >>> ['','-'][n<0]
> ''
> 
> What's this called? I'd like to look it up.


Hi Dick and all,

I don't know that it has a name other than `trickery!' ;-)

But, if you're scratching your head over it:

Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> 1==True
True
 >>> 0==False
True
 >>>

Best,

Brian vdB

From deliberatus at verizon.net  Thu Feb 22 06:01:15 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Thu, 22 Feb 2007 00:01:15 -0500
Subject: [Tutor] small personal server
Message-ID: <45DD239B.6010905@verizon.net>

I recall how much stirr the python web server program created when I 
copied it from a book and posted it to the list. Well, if you want 
something composed in C++ for placing in your notebook or desktop, try this:
	http://smallsrv.com/index.htm

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rdm at rcblue.com  Thu Feb 22 06:30:49 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 21 Feb 2007 21:30:49 -0800
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <Pine.LNX.4.44.0702211836400.12994-100000@violet.rahul.net>
References: <5e58f2e40702211833j4eb56395w761162ce353cf3f4@mail.gmail.com>
	<Pine.LNX.4.44.0702211836400.12994-100000@violet.rahul.net>
Message-ID: <20070222053122.4AA701E4016@bag.python.org>

At 06:45 PM 2/21/2007, Terry Carroll wrote:

I'm glad to have learned your cool Boolean trick ( sign = 
['','-'][n<0] ), but I think instead I'll try to make

>    sign = '-' if n<0 else ''

a habit.

My thanks to everyone for the feedback about my function, and with my 
question about  sign = ['','-'][n<0]  .

Dick Moores



From johan at accesstel.co.za  Thu Feb 22 06:54:30 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 22 Feb 2007 07:54:30 +0200
Subject: [Tutor] Explanation of this lambda
Message-ID: <20070222054816.7231718989@mail.accesstel.co.za>

Hi all,
 
I found this function that converts a integer into a 8 bit binary string. 
 
Would somebody care to explain what is happening in this process? 
 
def intToBin(self, x, count=8):
        """
        Parameters: `x`: integer
        
        Returns a 8 bit binary string of x
        """
        return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))

        
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/694 - Release Date: 2007/02/20
01:44 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070222/f0416ace/attachment.htm 

From rdm at rcblue.com  Thu Feb 22 07:25:04 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 21 Feb 2007 22:25:04 -0800
Subject: [Tutor] Function for converting ints from base10 to base2?
In-Reply-To: <20070222053122.4AA701E4016@bag.python.org>
References: <5e58f2e40702211833j4eb56395w761162ce353cf3f4@mail.gmail.com>
	<Pine.LNX.4.44.0702211836400.12994-100000@violet.rahul.net>
	<20070222053122.4AA701E4016@bag.python.org>
Message-ID: <20070222062549.58AD91E4002@bag.python.org>

At 09:30 PM 2/21/2007, Dick Moores wrote:
>At 06:45 PM 2/21/2007, Terry Carroll wrote:
>
>I'm glad to have learned your cool Boolean trick ( sign =
>['','-'][n<0] ), but I think instead I'll try to make
>
> >    sign = '-' if n<0 else ''
>
>a habit.

Here's some timing info:

retiming my computeBin() (the same function I first asked about--I 
just realized that running other apps, such as Firefox, while using 
timeit.py can give wildly differing results, so I've done these with 
a lot fewer running than before):

for n of 12345678901234567890
1000 loops, best of 3: 364 usec per loop

for n of 1234567890
10000 loops, best of 3: 52 usec per loop

for n of 12345
10000 loops, best of 3: 29 usec per loop



for Terry Carroll's computeBin() using   sign = ['','-'][n<0]

for n of 12345678901234567890
10000 loops, best of 3: 161 usec per loop

for n of 1234567890
10000 loops, best of 3: 76 usec per loop

for n of 12345
10000 loops, best of 3: 38 usec per loop



for Terry Carroll's computeBin() using   sign = '-' if n<0 else ''

for n of 12345678901234567890
10000 loops, best of 3: 149 usec per loop

for n of 1234567890
10000 loops, best of 3: 82 usec per loop

for n of 12345
10000 loops, best of 3: 39 usec per loop

Dick Moores



From bgailer at alum.rpi.edu  Thu Feb 22 08:12:39 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 21 Feb 2007 23:12:39 -0800
Subject: [Tutor] storing text in databases
In-Reply-To: <BAY18-F83A065046ED595FBA23C3E08F0@phx.gbl>
References: <BAY18-F83A065046ED595FBA23C3E08F0@phx.gbl>
Message-ID: <45DD4267.3010006@alum.rpi.edu>

Chae M wrote:
> Is it a reasonable idea to store text (a few hundred words each
> record) in a database?  I'm learning to use the SQLite database
> that comes with Python, and it seems like a good idea in terms
> of being able to search for notes, etc.  My specific questions:
>
> - Can formatting of text be stored or is it always only raw text?
>   
Any system for storing / transmitting text uses "raw text". Formatting 
has to do with how the text is "rendered" when going to some display 
device (printer, video, ???).

Therefore "formatted" text is "raw" text that includes formatting 
instructions (also "raw" text).

HTML is one example of "formatted" text (the rendering is done by a web 
browser). RTF, XML, MS Word are others. There are *many* formatting schemes.

Does that address that issue?
> - What is the upper limit on the size of a stored document?  I.e.,
>   would this also work for big documents (10-100 pages?)
>   
AFAIK there is no limit. However there often comes times where it is 
"better" to store large documents as separate files and keep the 
filenames in the database. If you do not need to run queries against the 
document contents, consider that approach. If you need to query contents 
consider building indexes of keywords rather than asking a database to 
find rows where document like "?dollar?" (or is is % ?)
> - Is this a good idea/can it work?
>   
Depends.

WIR

-- 
Bob Gailer
510-978-4454


From bgailer at alum.rpi.edu  Thu Feb 22 08:46:35 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 21 Feb 2007 23:46:35 -0800
Subject: [Tutor] Explanation of this lambda
In-Reply-To: <20070222054816.7231718989@mail.accesstel.co.za>
References: <20070222054816.7231718989@mail.accesstel.co.za>
Message-ID: <45DD4A5B.7040405@alum.rpi.edu>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070221/6ed5f34e/attachment.htm 

From bgailer at alum.rpi.edu  Thu Feb 22 08:52:32 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 21 Feb 2007 23:52:32 -0800
Subject: [Tutor] Explanation of this lambda CORRECTION
In-Reply-To: <45DD4A5B.7040405@alum.rpi.edu>
References: <20070222054816.7231718989@mail.accesstel.co.za>
	<45DD4A5B.7040405@alum.rpi.edu>
Message-ID: <45DD4BC0.5070308@alum.rpi.edu>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070221/f4673e76/attachment.html 

From alan.gauld at btinternet.com  Thu Feb 22 10:46:21 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 22 Feb 2007 09:46:21 -0000
Subject: [Tutor] Explanation of this lambda
References: <20070222054816.7231718989@mail.accesstel.co.za>
Message-ID: <erjopn$pu5$1@sea.gmane.org>


"Johan Geldenhuys" <johan at accesstel.co.za> wrote

> Would somebody care to explain what is happening in this process?
>
> def intToBin(self, x, count=8):
>        return "".join(map(lambda y:str((x>>y)&1), 
> range(count-1, -1, -1)))

"".join()   turns a list into a string
map() returns a list where each item is the result
of applying the lambda to the range()

lamda y: .....  is a function to be applied

str() converts to a string

x>>y   shifts the bits of x right by y places  010 -> 001

& 1 bitwise ands with 1 which returns 1 if the last bit is one.

put the bits together and it should be clear.

HTH,


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



From alan.gauld at btinternet.com  Thu Feb 22 10:58:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 22 Feb 2007 09:58:40 -0000
Subject: [Tutor] storing text in databases
References: <BAY18-F83A065046ED595FBA23C3E08F0@phx.gbl>
Message-ID: <erjpgq$sad$1@sea.gmane.org>

"Chae M" <pine508 at hotmail.com> wrote
> Is it a reasonable idea to store text (a few hundred words each
> record) in a database?

That depends on what you want to do with it.
If you only wanmt to store the data and maybe do some searches
for words etc then no, a simply folder fiull of text files will be 
more
useful. (grep rules!)

But if you want to store and access information about the
text - say the author, date changed, etc or if you want to
dynamically generate longer texts from the smaller parts
then a data base could be reasonable. But databases are
generally more useful the more structured the data. Storing
freetext in a database without accompanying structured
data is not usually a big help.

> I'm learning to use the SQLite database

Try my Database topic in my tutor. It describes some theory,
some SQL and some Python. All based on SQLite

> that comes with Python, and it seems like a good idea in terms
> of being able to search for notes, etc.

A general text tool like grep might be more effective.

> - Can formatting of text be stored or is it always only raw text?

Formatting is a display thing and how it is implemented varies
a lot. HTML text has the formatting embedded. Some
wordprocessors put the formatting information at the start
or end of the file. Others use a separate file (not so common
nowadays). Many programs use non text values for formatting
codes and other programs might choke on them.

In essence the database will store the bytes you give it.
Whether you can display the formatted result when you extract
the data is another matter.

> - What is the upper limit on the size of a stored document?

It varies by database. Some limit text fields to 2000 characters,
others its much bigger (32KB or 64KB usd to be common on DOS)
Most will siupport a BLOB field that will hold more or less
anything, but you can't then search the content.

>  would this also work for big documents (10-100 pages?)
> - Is this a good idea/can it work?

The bigger the size of the data the less powerful the searches
you will be able to do and the longer they will take. Its usually
better to store the document in a file and use the database for
the meta-data and the filename.

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



From johan at accesstel.co.za  Thu Feb 22 11:43:38 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 22 Feb 2007 12:43:38 +0200
Subject: [Tutor] Explanation of this lambda
In-Reply-To: <erjopn$pu5$1@sea.gmane.org>
Message-ID: <20070222103724.D4E42168C6@mail.accesstel.co.za>

Thanks, Alan.

That makes it a lot easier to understand. I'll play around with other
examples to see what it is doing.

Johan 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Alan Gauld
Sent: 22 February 2007 11:46 AM
To: tutor at python.org
Subject: Re: [Tutor] Explanation of this lambda


"Johan Geldenhuys" <johan at accesstel.co.za> wrote

> Would somebody care to explain what is happening in this process?
>
> def intToBin(self, x, count=8):
>        return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, 
> -1)))

"".join()   turns a list into a string
map() returns a list where each item is the result of applying the lambda to
the range()

lamda y: .....  is a function to be applied

str() converts to a string

x>>y   shifts the bits of x right by y places  010 -> 001

& 1 bitwise ands with 1 which returns 1 if the last bit is one.

put the bits together and it should be clear.

HTH,


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


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

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/696 - Release Date: 2007/02/21
03:19 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/696 - Release Date: 2007/02/21
03:19 PM
 


From pine508 at hotmail.com  Thu Feb 22 16:49:13 2007
From: pine508 at hotmail.com (Che M)
Date: Thu, 22 Feb 2007 10:49:13 -0500
Subject: [Tutor] storing text in databases
Message-ID: <BAY18-F125E03E66D46DBE31A70CE08F0@phx.gbl>

Thank you Bob and Alan.  That helps alot.  I will store text as
files and index them somehow in the database (and yes Alan's
section on SQL on his site is a great resource for this).  -Che

_________________________________________________________________
The average US Credit Score is 675. The cost to see yours: $0 by Experian. 
http://www.freecreditreport.com/pm/default.aspx?sc=660600&bcd=EMAILFOOTERAVERAGE


From mabystry at verizon.net  Thu Feb 22 17:35:42 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 22 Feb 2007 11:35:42 -0500
Subject: [Tutor] Add metadata to a dir of files.
Message-ID: <45DDC65E.9090408@verizon.net>

Ok. I'm not sure what programming language I want to try this in...since I'm not sure how to write 
this in any language (thought I'd give python a try.

Here's my problem: I have a directory full of about 2,000 pdf files. I want to be able to add the 
same comment to the "Category" field of each file (in the document properties of the file). So I am 
looking to batch process pdf files (or any filetype, i guess) to add some metadata.

My needs are very similar to tagging mp3 files.

Since I'm still new to python I don't even know how to get started. Can someone provide sample code 
that maybe I could expand upon or point to a link somewhere so I can read up on the subject?

I would appreciate it.

Thank-you,

Mark

From mail at timgolden.me.uk  Thu Feb 22 18:28:44 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 22 Feb 2007 17:28:44 +0000
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDC65E.9090408@verizon.net>
References: <45DDC65E.9090408@verizon.net>
Message-ID: <45DDD2CC.6040203@timgolden.me.uk>

> Here's my problem: I have a directory full of about 2,000 pdf files. I want to be able to add the 
> same comment to the "Category" field of each file (in the document properties of the file). So I am 
> looking to batch process pdf files (or any filetype, i guess) to add some metadata.

I'm assuming here that we're talking about the PDF's
own metadata rather than, say, the additional stuff
which Windows allows in Alternate Data Streams? If
so, then a combination of PyPDF:

   http://pybrary.net/pyPdf/

and the builtin os, glob, os.path modules:

   http://docs.python.org/lib/module-os.html
   http://docs.python.org/lib/module-os.path.html
   http://docs.python.org/lib/module-glob.html

might suit the case.

TJG

From etrade.griffiths at dsl.pipex.com  Thu Feb 22 18:39:20 2007
From: etrade.griffiths at dsl.pipex.com (etrade.griffiths at dsl.pipex.com)
Date: Thu, 22 Feb 2007 17:39:20 +0000
Subject: [Tutor] How many loops does "break" jump out of?
Message-ID: <1172165960.45ddd5489c0e3@netmail.pipex.net>

Am trying to convert a C program with a GOTO in it to Python and was wondering 
how many loops a Python "break" jumps out of.  Here is the C pseudo code

if (test_1) {
    for (;;) {
        if (test_2) {
            do_stuff();
        } else if (test_2) {
            for (ip=m1+m2+1;ip<=m;ip++) {
                if (test_3) {
                    do_more_stuff();
                    if (test_4)
                        goto one;
                }
            }
            for (i=m1+1;i<=m1+m2;i++)
                do_even_more_stuff();
                
            do_yet_more_stuff();
        }
        
        do_final_stuff();
        
one:    continue_program();

Python version 1 - assumes break jumps out of outer enclosing loop

if (test_1):
    while 1:
        if (test_2):
            do_stuff()
        elif (test_2):
            for ip in range(m1+m2+1, m):
                if (test_3):
                    do_more_stuff()
                    if (test_4):
                        break
            for i in range(m1+1, m1+m2):
                do_even_more_stuff()
                
            do_yet_more_stuff()
        }
        
        do_final_stuff()
        
    continue_program()    # one (break jumps out of while loop to here)
    
Python version 2 - assumes break jumps out of inner loop only.

if (test_1):
    while 1:
        if (test_2):
            do_stuff()
        elif (test_2):
            for ip in range(m1+m2+1, m):
                if (test_3):
                    do_more_stuff()
                    if (test_4):
                        quit_loop = true
                        break    # jump out of for loop

            if quit_loop:
                break:           # jump out of if test

            for i in range(m1+1, m1+m2):
                do_even_more_stuff()
                
            do_yet_more_stuff()
        }
        
        # break jumps out of if loop to here
        
        if quit_loop:
            break    # jump out of while loop
            
        do_final_stuff()
        
    continue_program()    # one    
   
Python version 3 - assumes break jumps out of for loop only.

if (test_1):
    while 1:
        if (test_2):
            do_stuff()
        elif (test_2):
            for ip in range(m1+m2+1, m):
                if (test_3):
                    do_more_stuff()
                    if (test_4):
                        quit_loop = true
                        break    # jump out of for loop

            for i in range(m1+1, m1+m2):
                do_even_more_stuff()
                
            do_yet_more_stuff()
        }
        
        # break jumps out of for loop to here
        
        if quit_loop:
            break    # jump out of while loop
            
        do_final_stuff()
        
    continue_program()    # one    

Unfortunately, can't test the Python script against the C program 'cos I don't 
have a C compiler.  All commments gratefully received

From mabystry at verizon.net  Thu Feb 22 19:01:40 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 22 Feb 2007 13:01:40 -0500
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDD2CC.6040203@timgolden.me.uk>
References: <45DDC65E.9090408@verizon.net> <45DDD2CC.6040203@timgolden.me.uk>
Message-ID: <45DDDA84.9080500@verizon.net>

Actually no. I want to change the Windows metadata. This is the same metadata that is on all files. 
It isn't PDF specific. (I wonder if Linux is the same)

Basically, I can select 100's of file in a dir, right-click, properties, summary, and add something 
to the Category field. This obviously affects all files giving them all the same attribute. I can 
continue doing it this way but I thought perhaps a script would be best. Maybe it isn't, I don't know.

Anyway, thank-you for the links.

Mark

Tim Golden wrote the following on 2/22/2007 12:28 PM:
>> Here's my problem: I have a directory full of about 2,000 pdf files. I want to be able to add the 
>> same comment to the "Category" field of each file (in the document properties of the file). So I am 
>> looking to batch process pdf files (or any filetype, i guess) to add some metadata.
> 
> I'm assuming here that we're talking about the PDF's
> own metadata rather than, say, the additional stuff
> which Windows allows in Alternate Data Streams? If
> so, then a combination of PyPDF:
> 
>    http://pybrary.net/pyPdf/
> 
> and the builtin os, glob, os.path modules:
> 
>    http://docs.python.org/lib/module-os.html
>    http://docs.python.org/lib/module-os.path.html
>    http://docs.python.org/lib/module-glob.html
> 
> might suit the case.
> 
> TJG
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From mabystry at verizon.net  Thu Feb 22 19:30:50 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 22 Feb 2007 13:30:50 -0500
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDDA84.9080500@verizon.net>
References: <45DDC65E.9090408@verizon.net> <45DDD2CC.6040203@timgolden.me.uk>
	<45DDDA84.9080500@verizon.net>
Message-ID: <45DDE15A.7070805@verizon.net>

I think I'm getting close but with the wrong programming language...

filename: test.vbs
code:
Set objFile = CreateObject("DSOFile.OleDocumentProperties")
objFile.Open("C:\test.txt")
Wscript.Echo "Category: " & objFile.SummaryProperties.Category

With the help of dsofile.dll the above reads the "Category" attribute of test.txt.


Mark Bystry wrote the following on 2/22/2007 1:01 PM:
> Actually no. I want to change the Windows metadata. This is the same metadata that is on all files. 
> It isn't PDF specific. (I wonder if Linux is the same)
> 
> Basically, I can select 100's of file in a dir, right-click, properties, summary, and add something 
> to the Category field. This obviously affects all files giving them all the same attribute. I can 
> continue doing it this way but I thought perhaps a script would be best. Maybe it isn't, I don't know.
> 
> Anyway, thank-you for the links.
> 
> Mark
> 

From mabystry at verizon.net  Thu Feb 22 19:39:31 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 22 Feb 2007 13:39:31 -0500
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDE15A.7070805@verizon.net>
References: <45DDC65E.9090408@verizon.net> <45DDD2CC.6040203@timgolden.me.uk>
	<45DDDA84.9080500@verizon.net> <45DDE15A.7070805@verizon.net>
Message-ID: <45DDE363.5070007@verizon.net>

getting even closer. figure out how to write to a file but still in vbscript.

dsofile_write.vbs
code:
Set objFile = CreateObject("DSOFile.OleDocumentProperties")
objFile.Open("D:\test.txt")
objFile.SummaryProperties.Category = "CAT54"
objFile.Save

Mark

Mark Bystry wrote the following on 2/22/2007 1:30 PM:
> I think I'm getting close but with the wrong programming language...
> 
> filename: test.vbs
> code:
> Set objFile = CreateObject("DSOFile.OleDocumentProperties")
> objFile.Open("C:\test.txt")
> Wscript.Echo "Category: " & objFile.SummaryProperties.Category
> 
> With the help of dsofile.dll the above reads the "Category" attribute of test.txt.

From singh01 at gmail.com  Thu Feb 22 20:14:14 2007
From: singh01 at gmail.com (Nagendra Singh)
Date: Thu, 22 Feb 2007 14:14:14 -0500
Subject: [Tutor] Running an exe from Python
Message-ID: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>

Hi,

I am trying to learn Python and have no prior programming experience. My
problem is that I am trying to call an .exe through Python,  the exe gives
certain information about a file when I simply type it at the command
prompt, something like  C:> getinfo C:\Singh\abc.bcd and it displays the
information about abc.bcd in the command window. I am trying to do the same
thing through Python ( i downloaded it from activestate)

Here is what I tried :

import os
file1 = r 'C:\Program Files\Tools1\bin\getinfo.exe' 'C:\Singh\abc.bcd'
os.system(file1)

What it does is that opens and closes the command window really fast and
displays a value of 1 in the interpreter. How can I get python to display
the results in the interactive window or what is the right way to do this.

thanks in advance,

Singh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070222/511e5d46/attachment.htm 

From Andrew.Liimatta at hsc.utah.edu  Thu Feb 22 19:56:19 2007
From: Andrew.Liimatta at hsc.utah.edu (Andrew Liimatta)
Date: Thu, 22 Feb 2007 11:56:19 -0700
Subject: [Tutor] DICOM Header
Message-ID: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>


Hello,


I am having a hard time figuring something out.

I have Files that are written in DICOM format.  I want to be able to pull out select elements from the header of these files

I have a dictionary file that contains enteries like this.

dicomdict = {
# meta tags
(0x0002,0x0001):('OB', "FileMetaInformationVersion",             '1', ''),
(0x0002,0x0002):('UI', "MediaStorageSOPClassUID",                '1', ''),
(0x0002,0x0003):('UI', "MediaStorageSOPInstanceUID",             '1', ''),
(0x0002,0x0010):('UI', "TransferSyntaxUID",                      '1', ''),
(0x0002,0x0012):('UI', "ImplementationClassUID",                 '1', ''),
(0x0002,0x0013):('SH', "ImplementationVersionName",              '1', ''),
(0x0002,0x0016):('AE', "SourceApplicationEntityTitle",           '1', ''),
(0x0002,0x0100):('UI', "PrivateInformationCreatorUID",           '1', ''),
(0x0002,0x0102):('OB', "PrivateInformation",                     '1', ''),
}

I do understand how to use the dictionary file to help parse out the element that I want from the DICOM file.
For example how do I only grab the SourceApplicationEntityTitle from the DICOM header.

Any help would be appreciated.


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

From wescpy at gmail.com  Thu Feb 22 20:32:32 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 22 Feb 2007 11:32:32 -0800
Subject: [Tutor] DICOM Header
In-Reply-To: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>
References: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>
Message-ID: <78b3a9580702221132y1d958779gfdcda8c961ffadd@mail.gmail.com>

>  I have Files that are written in DICOM format.  I want to be able to pull
> out select elements from the header of these files

for those who aren't in the industry, DICOM files are a digital
imaging format typically used by the medical industry.  it contains an
embedded JPG and lots of patient/medical metadata, and also includes a
networking protocol for exchanging such data across processes:

http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine


>  I have a dictionary file that contains enteries like this.
>
>  dicomdict = {
>  # meta tags
>  (0x0002,0x0001):('OB', "FileMetaInformationVersion",
>       '1', ''),
>  (0x0002,0x0002):('UI', "MediaStorageSOPClassUID",
>       '1', ''),
>  (0x0002,0x0003):('UI', "MediaStorageSOPInstanceUID",
>       '1', ''),
>  (0x0002,0x0010):('UI', "TransferSyntaxUID",
>       '1', ''),
>  (0x0002,0x0012):('UI', "ImplementationClassUID",
>       '1', ''),
>  (0x0002,0x0013):('SH', "ImplementationVersionName",
>       '1', ''),
>  (0x0002,0x0016):('AE', "SourceApplicationEntityTitle",
>       '1', ''),
>  (0x0002,0x0100):('UI', "PrivateInformationCreatorUID",
>       '1', ''),
>  (0x0002,0x0102):('OB', "PrivateInformation",
>       '1', ''),
>  }
>
>  I do understand how to use the dictionary file to help parse out the
> element that I want from the DICOM file.
>  For example how do I only grab the SourceApplicationEntityTitle from the
> DICOM header.

a few questions to help us understand the problem better:

how are you opening the file?
how are you parsing the file, and what kind of data structure is
holding all the data?
where is this dictionary defined?

once we know this info, i'm sure we can help out more.

thanks,
-- 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 atpridgen at mail.utexas.edu  Thu Feb 22 20:35:54 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Thu, 22 Feb 2007 13:35:54 -0600
Subject: [Tutor] what instance type is a function object?
Message-ID: <f989e6210702221135p14385007re462b2692883e618@mail.gmail.com>

Thanks in advance for your help.
I am trying to pickle a class, but I want to exclude function objects
for obvious reasons.  How do I determine if a python object is a
function, specifically when using isinstance()?  I am not sure what a
type or instance a Python 'function' originates from.

The below code throws an exception, because function is not a type.
Presently I am attempting to do the following:

def __getstate__(
   ret_val = {}
   for key in self.__dict__:
      if not isinstance(self.__dict__[key], function): pass
      # do assignment here

Thanks again, Adam

From sconce at in-spec-inc.com  Thu Feb 22 21:07:34 2007
From: sconce at in-spec-inc.com (Bill Sconce)
Date: Thu, 22 Feb 2007 15:07:34 -0500
Subject: [Tutor] DICOM Header
In-Reply-To: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>
References: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>
Message-ID: <20070222150734.019d5ba3@laura>

On Thu, 22 Feb 2007 11:56:19 -0700
"Andrew Liimatta" <Andrew.Liimatta at hsc.utah.edu> wrote:

> 
> Hello,
> 
> 
> I am having a hard time figuring something out.
> 
> I have Files that are written in DICOM format.  I want to be able
> to pull out select elements from the header of these files
> 
> I have a dictionary file that contains enteries like this.
> 
> dicomdict = {
> # meta tags
> (0x0002,0x0001):('OB', "FileMetaInformationVersion",             '1', ''),
> (0x0002,0x0002):('UI', "MediaStorageSOPClassUID",                '1', ''),
> (0x0002,0x0003):('UI', "MediaStorageSOPInstanceUID",             '1', ''),
> (0x0002,0x0010):('UI', "TransferSyntaxUID",                      '1', ''),
> (0x0002,0x0012):('UI', "ImplementationClassUID",                 '1', ''),
> (0x0002,0x0013):('SH', "ImplementationVersionName",              '1', ''),
> (0x0002,0x0016):('AE', "SourceApplicationEntityTitle",           '1', ''),
> (0x0002,0x0100):('UI', "PrivateInformationCreatorUID",           '1', ''),
> (0x0002,0x0102):('OB', "PrivateInformation",                     '1', ''),
> }
> 
> I do understand how to use the dictionary file to help parse out the
> element that I want from the DICOM file.  For example how do I only grab
> the SourceApplicationEntityTitle from the DICOM header.
> 
> Any help would be appreciated.


I'd like to help.  (I have an interest in DICOM files myself, for a
client's needs.)

Unfortunately, I do NOT yet have knowledge of how a DICOM file is
made.  (This is an "opportunity".)  So first we should ask a couple
of questions -- for everyone's benefit, since the method of attack
on your problem has merit beyond DICOM files.

1. Is the dictionary file which you have part of the DICOM file?

2. Or is the dictionary file which you have part of the description
   of what you wish to EXTRACT from the DICOM file?

I could start with a suggested solution, since I think your status
is "2." (and that you mean "do NOT understand how to use the dictionary")
but I might be wrong, so it's better to nail down your requirement first.
Feel free to write me directly if it's going to get into a lot of DICOM
details.

-Bill



From mail at timgolden.me.uk  Thu Feb 22 21:16:21 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 22 Feb 2007 20:16:21 +0000
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDE363.5070007@verizon.net>
References: <45DDC65E.9090408@verizon.net>
	<45DDD2CC.6040203@timgolden.me.uk>	<45DDDA84.9080500@verizon.net>
	<45DDE15A.7070805@verizon.net> <45DDE363.5070007@verizon.net>
Message-ID: <45DDFA15.8000703@timgolden.me.uk>

Mark Bystry wrote:
> getting even closer. figure out how to write to a file but still in vbscript.
> 
> dsofile_write.vbs
> code:
> Set objFile = CreateObject("DSOFile.OleDocumentProperties")
> objFile.Open("D:\test.txt")
> objFile.SummaryProperties.Category = "CAT54"
> objFile.Save

In Python, that's spelt:

<code>
import win32com.client
props = win32com.client.Dispatch ("DSOFile.OleDocumentProperties")
props.Open (r"c:\temp\test.txt")
props.SummaryProperties.Category = "CAT54"
props.Save ()

</code>

but when I tried doing it, I got a COM error on the line
where the Category is written. It worked ok with Subject
instead. Wouldn't have thought this was down to Python,
but I've not got much to go on!

TJG

From hugonz-lists at h-lab.net  Thu Feb 22 21:18:31 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Thu, 22 Feb 2007 14:18:31 -0600
Subject: [Tutor] Running an exe from Python
In-Reply-To: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
Message-ID: <45DDFA97.2010706@h-lab.net>

Hi,

Take a lok=ok at the module named subprocess. You can catch the output 
of invoked programs with this.


There is also a module called "commands" but it its not available in 
windows.


Hugo


From rfquerin at gmail.com  Thu Feb 22 21:33:07 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Thu, 22 Feb 2007 15:33:07 -0500
Subject: [Tutor] Running an exe from Python
In-Reply-To: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
Message-ID: <7d81675b0702221233g62aadc20va2f39bddd19fd406@mail.gmail.com>

On 2/22/07, Nagendra Singh <singh01 at gmail.com> wrote:
>
>
> What it does is that opens and closes the command window really fast and
> displays a value of 1 in the interpreter. How can I get python to display
> the results in the interactive window or what is the right way to do this.
>
>
I assume you're using the PythonWin editor that comes from ActiveState. I
tend to use the editor to create and edit the scripts, but I open a separate
command line window (or terminal) for testing and running the scripts. This
way, the output is right there and remains visible. If you run the script
from within the PythonWin editor it will generate the output and then
immediately close the output window and you miss seeing it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070222/91db9417/attachment.htm 

From mabystry at verizon.net  Thu Feb 22 21:37:12 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Thu, 22 Feb 2007 15:37:12 -0500
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDFA15.8000703@timgolden.me.uk>
References: <45DDC65E.9090408@verizon.net> <45DDD2CC.6040203@timgolden.me.uk>
	<45DDDA84.9080500@verizon.net> <45DDE15A.7070805@verizon.net>
	<45DDE363.5070007@verizon.net> <45DDFA15.8000703@timgolden.me.uk>
Message-ID: <45DDFEF8.8040907@verizon.net>

Well that's awesome. Thanks for the code. Unfortunately I cannot get it to run. After I installed 
the win32 extensions for python...I get this error when trying to run.

Traceback (most recent call last):
   File "C:\test.py", line 4, in <module>
     props.SummaryProperties.Category = "CAT69"
   File "C:\Program Files\Python25\Lib\site-packages\win32com\client\dynamic.py", line 534, in 
__setattr__
     self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024891), None)

code:
import win32com.client
props = win32com.client.Dispatch ("DSOFile.OleDocumentProperties")
props.Open (r"C:\test.txt")
props.SummaryProperties.Category = "CAT69"
props.Save ()


Maybe this is the same com error that you're getting

Mark


Tim Golden wrote the following on 2/22/2007 3:16 PM:
> Mark Bystry wrote:
>> getting even closer. figure out how to write to a file but still in vbscript.
>>
>> dsofile_write.vbs
>> code:
>> Set objFile = CreateObject("DSOFile.OleDocumentProperties")
>> objFile.Open("D:\test.txt")
>> objFile.SummaryProperties.Category = "CAT54"
>> objFile.Save
> 
> In Python, that's spelt:
> 
> <code>
> import win32com.client
> props = win32com.client.Dispatch ("DSOFile.OleDocumentProperties")
> props.Open (r"c:\temp\test.txt")
> props.SummaryProperties.Category = "CAT54"
> props.Save ()
> 
> </code>
> 
> but when I tried doing it, I got a COM error on the line
> where the Category is written. It worked ok with Subject
> instead. Wouldn't have thought this was down to Python,
> but I've not got much to go on!
> 
> TJG
> 

From lnhaig at gmail.com  Thu Feb 22 21:49:41 2007
From: lnhaig at gmail.com (Lance Haig)
Date: Thu, 22 Feb 2007 20:49:41 +0000
Subject: [Tutor] how to determine where a module or function is called from
Message-ID: <45DE01E5.5050104@gmail.com>

I am debugging a script that was written by someone else and I was 
wondering if there is a way to determine where a function or module is 
imported from

Thanks

Lance

From Andrew.Liimatta at hsc.utah.edu  Thu Feb 22 21:51:35 2007
From: Andrew.Liimatta at hsc.utah.edu (Andrew Liimatta)
Date: Thu, 22 Feb 2007 13:51:35 -0700
Subject: [Tutor] DICOM Header
References: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>
	<20070222150734.019d5ba3@laura>
Message-ID: <C38780AA415B144BB8F4384B82B606F31F1441@UHCX4.xds.umail.utah.edu>

I have a directory that is filled with DICOM files that I obtained by using the Offis DICOM tool kit.

The dictionary file I have is not included in the DICOM file. I have a flat file that has all of the DICOM fields defined as a python dictionary. In my initial post I 
included only the first section.
 
dicomdict = {
# meta tags
(0x0002,0x0001):('OB', "FileMetaInformationVersion",             '1', ''),
(0x0002,0x0002):('UI', "MediaStorageSOPClassUID",                '1', ''),
(0x0002,0x0003):('UI', "MediaStorageSOPInstanceUID",             '1', ''),
(0x0002,0x0010):('UI', "TransferSyntaxUID",                      '1', ''),
(0x0002,0x0012):('UI', "ImplementationClassUID",                 '1', ''),
(0x0002,0x0013):('SH', "ImplementationVersionName",              '1', ''),
(0x0002,0x0016):('AE', "SourceApplicationEntityTitle",           '1', ''),
(0x0002,0x0100):('UI', "PrivateInformationCreatorUID",           '1', ''),
(0x0002,0x0102):('OB', "PrivateInformation",                     '1', ''),
# directory tags
(0x0004,0x1130):('CS', "FileSetID",                              '1', ''),
(0x0004,0x1141):('CS', "FileSetDescriptorFileID",                '1-8', ''),
(0x0004,0x1142):('CS', "SpecificCharacterSetOfFileSetDescriptorFile", '1', ''),
(0x0004,0x1200):('UL', "OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity", '1', ''),
(0x0004,0x1202):('UL', "OffsetOfTheLastDirectoryRecordOfTheRootDirectoryEntity", '1', ''),
(0x0004,0x1212):('US', "FileSetConsistencyFlag",                 '1', ''),
(0x0004,0x1220):('SQ', "DirectoryRecordSequence",                '1', ''),
(0x0004,0x1400):('UL', "OffsetOfTheNextDirectoryRecord",         '1', ''),
(0x0004,0x1410):('US', "RecordInUseFlag",                        '1', ''),
(0x0004,0x1420):('UL', "OffsetOfReferencedLowerLevelDirectoryEntity", '1', ''),
(0x0004,0x1430):('CS', "DirectoryRecordType",                    '1', ''),
(0x0004,0x1432):('UI', "PrivateRecordUID",                       '1', ''),
(0x0004,0x1500):('CS', "ReferencedFileID",                       '1-8', ''),
(0x0004,0x1504):('UL', "MRDRDirectoryRecordOffset",              '1', ''),
(0x0004,0x1510):('UI', "ReferencedSOPClassUIDInFile",            '1', ''),
(0x0004,0x1511):('UI', "ReferencedSOPInstanceUIDInFile",         '1', ''),
(0x0004,0x1512):('UI', "ReferencedTransferSyntaxUIDInFile",      '1', ''),
(0x0004,0x1600):('UL', "NumberOfReferences",                     '1', ''),
# data tags

......
......

.....}

Correct I have no idea how to use the dictionaries to help me complete my task.


Currently I have the following

#!/usr/bin/python
##################################################
import os,linecache     # import the os and linecache module
import string 
# First thing is to look at a directory and list
# out its contents. 
# open a config file to determine the directory, only use a 
# specific line in this case line #7.
dir = linecache.getline('./config',7)
# os.listdir(pathname) will list the pathname.
files = os.listdir(dir[:-1]) # remove the \n from the end of dir.
for file in files:
        dfile = dir[:-1]+file
        print dfile
        dicom_file = open(dfile, "rb")
        elem = dicom_file.readlines()
        print elem
dicom_file.close() # close DICOM Files

I can open each DICOM file but it reads everything from beginning to end which is not very efficient.  I only want to pop out the elements that I am interested in.
Hope this makes a little more sense.

Andrew

-----Original Message-----
From: tutor-bounces at python.org on behalf of Bill Sconce
Sent: Thu 2/22/2007 1:07 PM
To: tutor at python.org
Subject: Re: [Tutor] DICOM Header
 
On Thu, 22 Feb 2007 11:56:19 -0700
"Andrew Liimatta" <Andrew.Liimatta at hsc.utah.edu> wrote:

> 
> Hello,
> 
> 
> I am having a hard time figuring something out.
> 
> I have Files that are written in DICOM format.  I want to be able
> to pull out select elements from the header of these files
> 
> I have a dictionary file that contains enteries like this.
> 
> dicomdict = {
> # meta tags
> (0x0002,0x0001):('OB', "FileMetaInformationVersion",             '1', ''),
> (0x0002,0x0002):('UI', "MediaStorageSOPClassUID",                '1', ''),
> (0x0002,0x0003):('UI', "MediaStorageSOPInstanceUID",             '1', ''),
> (0x0002,0x0010):('UI', "TransferSyntaxUID",                      '1', ''),
> (0x0002,0x0012):('UI', "ImplementationClassUID",                 '1', ''),
> (0x0002,0x0013):('SH', "ImplementationVersionName",              '1', ''),
> (0x0002,0x0016):('AE', "SourceApplicationEntityTitle",           '1', ''),
> (0x0002,0x0100):('UI', "PrivateInformationCreatorUID",           '1', ''),
> (0x0002,0x0102):('OB', "PrivateInformation",                     '1', ''),
> }
> 
> I do understand how to use the dictionary file to help parse out the
> element that I want from the DICOM file.  For example how do I only grab
> the SourceApplicationEntityTitle from the DICOM header.
> 
> Any help would be appreciated.


I'd like to help.  (I have an interest in DICOM files myself, for a
client's needs.)

Unfortunately, I do NOT yet have knowledge of how a DICOM file is
made.  (This is an "opportunity".)  So first we should ask a couple
of questions -- for everyone's benefit, since the method of attack
on your problem has merit beyond DICOM files.

1. Is the dictionary file which you have part of the DICOM file?

2. Or is the dictionary file which you have part of the description
   of what you wish to EXTRACT from the DICOM file?

I could start with a suggested solution, since I think your status
is "2." (and that you mean "do NOT understand how to use the dictionary")
but I might be wrong, so it's better to nail down your requirement first.
Feel free to write me directly if it's going to get into a lot of DICOM
details.

-Bill


_______________________________________________
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/20070222/bb9dec78/attachment.html 

From mail at timgolden.me.uk  Thu Feb 22 22:01:38 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 22 Feb 2007 21:01:38 +0000
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDFEF8.8040907@verizon.net>
References: <45DDC65E.9090408@verizon.net>
	<45DDD2CC.6040203@timgolden.me.uk>	<45DDDA84.9080500@verizon.net>
	<45DDE15A.7070805@verizon.net>	<45DDE363.5070007@verizon.net>
	<45DDFA15.8000703@timgolden.me.uk> <45DDFEF8.8040907@verizon.net>
Message-ID: <45DE04B2.7030207@timgolden.me.uk>

Mark Bystry wrote:
> Well that's awesome. Thanks for the code. Unfortunately I cannot get it to run. After I installed 
> the win32 extensions for python...I get this error when trying to run.
> 
> Traceback (most recent call last):
>    File "C:\test.py", line 4, in <module>
>      props.SummaryProperties.Category = "CAT69"
>    File "C:\Program Files\Python25\Lib\site-packages\win32com\client\dynamic.py", line 534, in 
> __setattr__
>      self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
> com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024891), None)
> 
> code:
> import win32com.client
> props = win32com.client.Dispatch ("DSOFile.OleDocumentProperties")
> props.Open (r"C:\test.txt")
> props.SummaryProperties.Category = "CAT69"
> props.Save ()
> 
> 
> Maybe this is the same com error that you're getting

Slightly bizarrely, it works fine for me on a different
computer (my laptop). Both are Win2K. The only help I
could find on the error code suggested a permission issue,
which isn't likely. That said, I have experienced a few
funnies with the Python script writing the new Category
open in one window, and trying to use Explorer to update
the Summary info in another.

Might be worth making sure nothing else is blocking, and
giving it another go. I'll try it on a random collection
of files to see if it runs...

TJG

From mail at timgolden.me.uk  Thu Feb 22 22:06:33 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 22 Feb 2007 21:06:33 +0000
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DE04B2.7030207@timgolden.me.uk>
References: <45DDC65E.9090408@verizon.net>	<45DDD2CC.6040203@timgolden.me.uk>	<45DDDA84.9080500@verizon.net>	<45DDE15A.7070805@verizon.net>	<45DDE363.5070007@verizon.net>	<45DDFA15.8000703@timgolden.me.uk>
	<45DDFEF8.8040907@verizon.net> <45DE04B2.7030207@timgolden.me.uk>
Message-ID: <45DE05D9.9040404@timgolden.me.uk>

Tim Golden wrote:
> Slightly bizarrely, it works fine for me on a different
> computer (my laptop). Both are Win2K. The only help I
> could find on the error code suggested a permission issue,
> which isn't likely. That said, I have experienced a few
> funnies with the Python script writing the new Category
> open in one window, and trying to use Explorer to update
> the Summary info in another.
> 
> Might be worth making sure nothing else is blocking, and
> giving it another go. I'll try it on a random collection
> of files to see if it runs...

No joy. It's falling over again with another eight-byte
twos-complement error code. Frankly, if your VBS version
runs, use it! (Especially if this is just one of those
one-off things).

TJG

From alan.gauld at btinternet.com  Thu Feb 22 23:00:12 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 22 Feb 2007 22:00:12 -0000
Subject: [Tutor] How many loops does "break" jump out of?
References: <1172165960.45ddd5489c0e3@netmail.pipex.net>
Message-ID: <erl3pd$ug8$1@sea.gmane.org>

<etrade.griffiths at dsl.pipex.com> wrote 

> Am trying to convert a C program with a GOTO in it 
> to Python and was wondering how many loops a 
> Python "break" jumps out of.  

Just the immediately enclosing loop.
You can fake higher level breaks by setting 
a global variable and immediately after the 
exit from the inner loop check the value and 
if necessary break again.

brk_level = 0   # 1= all levels, 0 = just one

while 1:
    while 1:
        if test():
            brk_level = 1
            break
    if brk_level > 0: break
    doMore()

But its nearly always possibly to just restructure the 
code to avoid the need for such tricks.

Alan G.


From alan.gauld at btinternet.com  Thu Feb 22 23:02:06 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 22 Feb 2007 22:02:06 -0000
Subject: [Tutor] how to determine where a module or function is called
	from
References: <45DE01E5.5050104@gmail.com>
Message-ID: <erl3sv$v5g$1@sea.gmane.org>

"Lance Haig" <lnhaig at gmail.com> wrote

>I am debugging a script that was written by someone else and I was
> wondering if there is a way to determine where a function or module 
> is
> imported from

>>> import time
>>> print time
<module 'time' from '/usr/lib/python2.4/lib-dynload/time.dll'>
>>> time.__file__
'/usr/lib/python2.4/lib-dynload/time.dll'
>>>

HTH,


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



From kent37 at tds.net  Thu Feb 22 23:09:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Feb 2007 17:09:44 -0500
Subject: [Tutor] what instance type is a function object?
In-Reply-To: <f989e6210702221135p14385007re462b2692883e618@mail.gmail.com>
References: <f989e6210702221135p14385007re462b2692883e618@mail.gmail.com>
Message-ID: <45DE14A8.8020200@tds.net>

Adam Pridgen wrote:
> Thanks in advance for your help.
> I am trying to pickle a class, but I want to exclude function objects
> for obvious reasons.  How do I determine if a python object is a
> function, specifically when using isinstance()?  I am not sure what a
> type or instance a Python 'function' originates from.

You can either use type(f) where f is some function or import types and 
use types.FunctionType.

You could also use the builtin function callable() but that will be true 
for any callable (e.g. an instance of a class that has a __call__() 
method) not just for functions.

Kent

> 
> The below code throws an exception, because function is not a type.
> Presently I am attempting to do the following:
> 
> def __getstate__(
>    ret_val = {}
>    for key in self.__dict__:
>       if not isinstance(self.__dict__[key], function): pass
>       # do assignment here
> 
> Thanks again, Adam
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From alan.gauld at btinternet.com  Thu Feb 22 23:10:20 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 22 Feb 2007 22:10:20 -0000
Subject: [Tutor] Add metadata to a dir of files.
References: <45DDC65E.9090408@verizon.net>
	<45DDD2CC.6040203@timgolden.me.uk><45DDDA84.9080500@verizon.net>
	<45DDE15A.7070805@verizon.net><45DDE363.5070007@verizon.net>
	<45DDFA15.8000703@timgolden.me.uk> <45DDFEF8.8040907@verizon.net>
Message-ID: <erl4cd$28q$1@sea.gmane.org>


"Mark Bystry" <mabystry at verizon.net> wrote

> Well that's awesome. Thanks for the code. Unfortunately
> I cannot get it to run. After I installed the win32 extensions
> for python...

ISTR that before uing Windows scripting you have to enable it.
There is a script in the library and a readme file tells you what to 
do.
Although that might only be to allow yuou ton write Python code
in wsh files...

But frankly I'd not get hung up on the language.
If VBScript works for your task use it!

VBScript (and to a lesser dgree JScript) is the natural
scripting language for COM, there is nothing to be ashamed
of in using it.

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



From kent37 at tds.net  Thu Feb 22 23:14:33 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Feb 2007 17:14:33 -0500
Subject: [Tutor] how to determine where a module or function is called
 from
In-Reply-To: <45DE01E5.5050104@gmail.com>
References: <45DE01E5.5050104@gmail.com>
Message-ID: <45DE15C9.9030604@tds.net>

Lance Haig wrote:
> I am debugging a script that was written by someone else and I was 
> wondering if there is a way to determine where a function or module is 
> imported from

You can use the __file__ attribute of a module:
In [9]: csv.__file__
Out[9]: 
'/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/csv.pyc'

For a function use the __module__ attribute to get the module:
In [10]: csv.reader.__module__
Out[10]: '_csv'

This is a string so you have to do a little more work to get the file:

In [12]: import sys
In [13]: sys.modules[csv.reader.__module__].__file__
Out[13]: 
'/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/lib-dynload/_csv.so'

Kent

From lnhaig at gmail.com  Thu Feb 22 23:32:08 2007
From: lnhaig at gmail.com (Lance Haig)
Date: Thu, 22 Feb 2007 22:32:08 +0000
Subject: [Tutor] how to determine where a module or function is called
 from
In-Reply-To: <45DE15C9.9030604@tds.net>
References: <45DE01E5.5050104@gmail.com> <45DE15C9.9030604@tds.net>
Message-ID: <45DE19E8.8000001@gmail.com>

Hi Kent,

Thank you

I was able to find it in the end.

<blushes>

It was at the bottom of the file I was editing

</blushes>

Lance

Kent Johnson wrote:
> Lance Haig wrote:
>> I am debugging a script that was written by someone else and I was 
>> wondering if there is a way to determine where a function or module 
>> is imported from
>
> You can use the __file__ attribute of a module:
> In [9]: csv.__file__
> Out[9]: 
> '/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/csv.pyc'
>
> For a function use the __module__ attribute to get the module:
> In [10]: csv.reader.__module__
> Out[10]: '_csv'
>
> This is a string so you have to do a little more work to get the file:
>
> In [12]: import sys
> In [13]: sys.modules[csv.reader.__module__].__file__
> Out[13]: 
> '/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/lib-dynload/_csv.so' 
>
>
> Kent
>


From bgailer at alum.rpi.edu  Fri Feb 23 03:57:04 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 22 Feb 2007 18:57:04 -0800
Subject: [Tutor] How many loops does "break" jump out of?
In-Reply-To: <1172165960.45ddd5489c0e3@netmail.pipex.net>
References: <1172165960.45ddd5489c0e3@netmail.pipex.net>
Message-ID: <45DE5800.1090202@alum.rpi.edu>

etrade.griffiths at dsl.pipex.com wrote:
> Am trying to convert a C program with a GOTO in it to Python and was wondering 
> how many loops a Python "break" jumps out of.  Here is the C pseudo code
>
> if (test_1) {
>     for (;;) {
>         if (test_2) {
>             do_stuff();
>         } else if (test_2) {
>             for (ip=m1+m2+1;ip<=m;ip++) {
>                 if (test_3) {
>                     do_more_stuff();
>                     if (test_4)
>                         goto one;
>                 }
>             }
>             for (i=m1+1;i<=m1+m2;i++)
>                 do_even_more_stuff();
>                 
>             do_yet_more_stuff();
>         }
>         
>         do_final_stuff();
>         
> one:    continue_program();
I'd put this code in a function, replace the goto one with return, and 
put a call to the function in place of the code.

def tests():
  if test_1:
    etc etc
        if test_4: return

Some may take issue with that. You can, as Alan says, restructure the 
code, or use intermediate variables.

-- 
Bob Gailer
510-978-4454


From deliberatus at verizon.net  Fri Feb 23 04:55:24 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Thu, 22 Feb 2007 22:55:24 -0500
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DDC65E.9090408@verizon.net>
References: <45DDC65E.9090408@verizon.net>
Message-ID: <45DE65AC.2000204@verizon.net>



Mark Bystry wrote:
> Ok. I'm not sure what programming language I want to try this in...since I'm not sure how to write 
> this in any language (thought I'd give python a try.
> 
> Here's my problem: I have a directory full of about 2,000 pdf files. I want to be able to add the 
> same comment to the "Category" field of each file (in the document properties of the file). So I am 
> looking to batch process pdf files (or any filetype, i guess) to add some metadata.
Just as a shot in the dark, try this as a first guess at proceeding:

filelist=glob.glob('*.pdf')
# filelist is a list variable; each *.pdf file name is an item in the
# list variable.
#now we will walk the list, doing the same trhing to every item.
for file in filelist:	# do the same stuff to every file listed
	dosomething
	dosomethingelse

See if thie helps getting something started. I know nothing about how to 
insert data into an existing pdf file, can you advise?

> 
> My needs are very similar to tagging mp3 files.
> 
> Since I'm still new to python I don't even know how to get started. Can someone provide sample code 
> that maybe I could expand upon or point to a link somewhere so I can read up on the subject?
> 
> I would appreciate it.
> 
> Thank-you,
> 
> Mark
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rikard.bosnjakovic at gmail.com  Fri Feb 23 06:38:51 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 23 Feb 2007 06:38:51 +0100
Subject: [Tutor] Running an exe from Python
In-Reply-To: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
Message-ID: <d9e88eaf0702222138s51c3abdfs113ce9c4952aca81@mail.gmail.com>

On 2/22/07, Nagendra Singh <singh01 at gmail.com> wrote:

> How can I get python to display
> the results in the interactive window or what is the right way to do this.

Use os.popen:

http://docs.python.org/lib/os-newstreams.html#os-newstreams


-- 
- Rikard.

From alan.gauld at btinternet.com  Fri Feb 23 10:43:42 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Feb 2007 09:43:42 -0000
Subject: [Tutor] Running an exe from Python
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
	<d9e88eaf0702222138s51c3abdfs113ce9c4952aca81@mail.gmail.com>
Message-ID: <ermd0f$taq$1@sea.gmane.org>


"Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote

>> How can I get python to display
>> the results in the interactive window or what is the right way to 
>> do this.
>
> Use os.popen:

As Rikard, Richard and Hugo have pointed out there are
numerous ways to do this in Python.

The officially sanctioned way nowadays is to use the subprocess
module. It supercedes all tthe previous methods being both more
powerful, more flexible and fairly easy to use.

All the techniques are discussed in my Using the OS topic in
my tutorial.

HTH,

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



From kmaheshw at science.uva.nl  Fri Feb 23 12:15:16 2007
From: kmaheshw at science.uva.nl (Ketan Maheshwari)
Date: Fri, 23 Feb 2007 12:15:16 +0100
Subject: [Tutor] Managing XML in Python
Message-ID: <45DECCC4.1080600@science.uva.nl>

Hi:
    I have to manage XML files through python. The activities include, 
create, update and retrieve information from the XML files.

    I would be thankful for pointers to tutorials, APIs and suggestions.

Regards
Ketan

From mabystry at verizon.net  Fri Feb 23 12:24:49 2007
From: mabystry at verizon.net (Mark Bystry)
Date: Fri, 23 Feb 2007 06:24:49 -0500
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DE05D9.9040404@timgolden.me.uk>
References: <45DDC65E.9090408@verizon.net>	<45DDD2CC.6040203@timgolden.me.uk>
	<45DDDA84.9080500@verizon.net>	<45DDE15A.7070805@verizon.net>
	<45DDE363.5070007@verizon.net>	<45DDFA15.8000703@timgolden.me.uk>
	<45DDFEF8.8040907@verizon.net> <45DE04B2.7030207@timgolden.me.uk>
	<45DE05D9.9040404@timgolden.me.uk>
Message-ID: <45DECF01.3040704@verizon.net>

Ok, Tim. I believe you're right. If the vbscript is working then I'll continue to use it and expand 
on it. I'll only be using this on my WinXP box anyway. I just didn't want to offend anyone in this 
mailing list with vbscript code. I'm really trying to learn some python basics but I'm no programmer.

Thanks everyone for your help.

Mark.

Tim Golden wrote the following on 2/22/2007 4:06 PM:
> Tim Golden wrote:
>> Slightly bizarrely, it works fine for me on a different
>> computer (my laptop). Both are Win2K. The only help I
>> could find on the error code suggested a permission issue,
>> which isn't likely. That said, I have experienced a few
>> funnies with the Python script writing the new Category
>> open in one window, and trying to use Explorer to update
>> the Summary info in another.
>>
>> Might be worth making sure nothing else is blocking, and
>> giving it another go. I'll try it on a random collection
>> of files to see if it runs...
> 
> No joy. It's falling over again with another eight-byte
> twos-complement error code. Frankly, if your VBS version
> runs, use it! (Especially if this is just one of those
> one-off things).
> 
> TJG
> 

From mail at timgolden.me.uk  Fri Feb 23 12:47:01 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 23 Feb 2007 11:47:01 +0000
Subject: [Tutor] Add metadata to a dir of files.
In-Reply-To: <45DECF01.3040704@verizon.net>
References: <45DDC65E.9090408@verizon.net>	<45DDD2CC.6040203@timgolden.me.uk>	<45DDDA84.9080500@verizon.net>	<45DDE15A.7070805@verizon.net>	<45DDE363.5070007@verizon.net>	<45DDFA15.8000703@timgolden.me.uk>	<45DDFEF8.8040907@verizon.net>
	<45DE04B2.7030207@timgolden.me.uk>	<45DE05D9.9040404@timgolden.me.uk>
	<45DECF01.3040704@verizon.net>
Message-ID: <45DED435.9060103@timgolden.me.uk>

Mark Bystry wrote:
> Ok, Tim. I believe you're right. If the vbscript is working then I'll continue to use it and expand 
> on it. I'll only be using this on my WinXP box anyway. I just didn't want to offend anyone in this 
> mailing list with vbscript code. I'm really trying to learn some python basics but I'm no programmer.

Don't worry; you won't offend many (or any) people here. We're
really quite friendly, are we're not such bigots as to believe
that Only Python solutions are acceptable. The only danger is
in not finding someone who can help. I assume there are VBS
forums somewhere. (Or should that be fora? :)

Good luck with it, and feel free to come back if you still need
help.

TJG

From nswitanek at stanford.edu  Fri Feb 23 09:39:44 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Fri, 23 Feb 2007 00:39:44 -0800
Subject: [Tutor] index swap?
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF203224CAC@gsb-exchmb02.stanford.edu>

Hi,

 

I'm trying to subset a large dataset (too many rows for Excel, currently
too ragged for Access), and I am mystified by the behavior of a
seemingly simple script I've written. Please help me understand what I'm
overlooking.

 

data = file(inpath).readlines()

data = [line.rstrip() for line in data]

data = [line.split('\t') for line in data]

 

# I wish to select the elements of a list by using a list of indices:

indices = [0, 1, 28, 29]   # for example

 

dataOut = []

for row in data:

    rowOut = []

    for i in indices:

        rowOut.append(row[i])

    dataOut.append(rowOut)

 

 

The problem is that while the first list in the list of lists 'dataOut',
i.e. my header row, has taken the headers with the appropriate indices
from the index list, all other rows swap the elements with indices 28
and 29. If I include just one of the two indices 28 or 29, the problem
remains: save for the header list, I get element 29 where I want 28, and
element 29 when I want element 28. This swapping doesn't occur for any
other indices that I've tested. 

 

Running the same code interactively doesn't seem to result in the index
swap. I'm sure I'm overlooking something basic, and I'd be grateful for
your help pointing it out.

 

 

Many thanks in advance,

Nick

 

 

 

 

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070223/53414223/attachment.htm 

From kent37 at tds.net  Fri Feb 23 13:13:10 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Feb 2007 07:13:10 -0500
Subject: [Tutor] Managing XML in Python
In-Reply-To: <45DECCC4.1080600@science.uva.nl>
References: <45DECCC4.1080600@science.uva.nl>
Message-ID: <45DEDA56.4080700@tds.net>

Ketan Maheshwari wrote:
> Hi:
>     I have to manage XML files through python. The activities include, 
> create, update and retrieve information from the XML files.
> 
>     I would be thankful for pointers to tutorials, APIs and suggestions.

Take a look at the ElementTree module. In Python 2.5 it is built in:
http://docs.python.org/lib/module-xml.etree.ElementTree.html

For older Pythons, and for more extensive docs, see
http://effbot.org/zone/element.htm

Kent

From kent37 at tds.net  Fri Feb 23 13:29:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Feb 2007 07:29:04 -0500
Subject: [Tutor] index swap?
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF203224CAC@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF203224CAC@gsb-exchmb02.stanford.edu>
Message-ID: <45DEDE10.1020304@tds.net>

Switanek, Nick wrote:
> Hi,
> 
>  
> 
> I?m trying to subset a large dataset (too many rows for Excel, currently 
> too ragged for Access), and I am mystified by the behavior of a 
> seemingly simple script I?ve written. Please help me understand what I?m 
> overlooking.
> 
> data = file(inpath).readlines()
> data = [line.rstrip() for line in data]
> data = [line.split('\t') for line in data]

This could be written more simply using a single list comprehension:
data = [ line.rstrip().split('\t') for line in open(inpath) ]

> # I wish to select the elements of a list by using a list of indices:
> 
> indices = [0, 1, 28, 29]   # for example 
> dataOut = []
> 
> for row in data:
>     rowOut = []
>     for i in indices:
>         rowOut.append(row[i])
>     dataOut.append(rowOut)

Again I would write this with nested list comps:
dataOut = [ [ row[i] for i in indices ] for row in data ]

> The problem is that while the first list in the list of lists ?dataOut?, 
> i.e. my header row, has taken the headers with the appropriate indices 
> from the index list, all other rows swap the elements with indices 28 
> and 29. If I include just one of the two indices 28 or 29, the problem 
> remains: save for the header list, I get element 29 where I want 28, and 
> element 29 when I want element 28. This swapping doesn?t occur for any 
> other indices that I?ve tested.

Are you sure the headers and data are in the order you think they are? I 
suspect that your data is not what you think it is. What do you get if 
you try
for row in data[:3]:
   print repr(row)
   print row[28]
   print row[29]
   print

Kent

From deliberatus at verizon.net  Fri Feb 23 15:03:41 2007
From: deliberatus at verizon.net (Kirk Z. Bailey)
Date: Fri, 23 Feb 2007 08:03:41 -0600 (CST)
Subject: [Tutor] miniwiki 1.3 BETA bugs
Message-ID: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>

ok, let's post this again. last time went into purgatory instead of the list. hmmm....

I am working on updating miniwiki. the current beta code has rendering problems with wikiwords and external sites under some circumstances. Here is a link to the latest code:

    http://www.tinylist.org/MW.txt








Blessed Be!
       - Kirk Bailey
         Largo FL USA

        
 kniht  
+-----+ http://www.mylemonadestand.biz/ - play the lemonade game!
| BOX | http://www.tinylist-org/ Freedom software
+-----+ In HER Service- http://www.pinellasintergroupsociety.org/
 think  http://www.seaxtradusa.org/ - The Seax Wica Trad in the USA!


From rabidpoobear at gmail.com  Fri Feb 23 16:04:07 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Feb 2007 09:04:07 -0600
Subject: [Tutor] miniwiki 1.3 BETA bugs
In-Reply-To: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>
References: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>
Message-ID: <45DF0267.9030405@gmail.com>

Kirk Z. Bailey wrote:
> ok, let's post this again. last time went into purgatory instead of the list. hmmm....
>
> I am working on updating miniwiki. the current beta code has rendering problems with wikiwords and external sites under some circumstances. 
What circumstances are these, exactly?
That's pretty vague.
And what are the rendering problems?
> Here is a link to the latest code:
>
>     http://www.tinylist.org/MW.txt
>
>
>
>
>
>
>
>
> Blessed Be!
>        - Kirk Bailey
>          Largo FL USA
>
>         
>  kniht  
> +-----+ http://www.mylemonadestand.biz/ - play the lemonade game!
> | BOX | http://www.tinylist-org/ Freedom software
> +-----+ In HER Service- http://www.pinellasintergroupsociety.org/
>  think  http://www.seaxtradusa.org/ - The Seax Wica Trad in the USA!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From sconce at in-spec-inc.com  Fri Feb 23 17:52:10 2007
From: sconce at in-spec-inc.com (Bill Sconce)
Date: Fri, 23 Feb 2007 11:52:10 -0500
Subject: [Tutor] DICOM Header
In-Reply-To: <C38780AA415B144BB8F4384B82B606F31F1441@UHCX4.xds.umail.utah.edu>
References: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>
	<20070222150734.019d5ba3@laura>
	<C38780AA415B144BB8F4384B82B606F31F1441@UHCX4.xds.umail.utah.edu>
Message-ID: <20070223115210.0fbdcc34@laura>

On Thu, 22 Feb 2007 13:51:35 -0700
"Andrew Liimatta" <Andrew.Liimatta at hsc.utah.edu> wrote:

> I have a directory that is filled with DICOM files that I obtained
> by using the Offis DICOM tool kit.

Ah.  The light dawns.  I should offer to communicate with you off-list,
and report back here after we've solved the problem.  I have DICOM files
here, and it sounds like an interesting and useful thing to be able to
do (inspect DICOM files with Python).  The next step is to talk more
specifically about what it is you want to do, which will likely require
more discussion about DICOM than we should burden the list with.

Let's say I were able to send you a snippet of code that returns a
list containing the values of SourceApplicationEntityTitle fields
(say) for each DICOM file in your directory.  Am I on the right track?

Feel free to write back to me off-list.

-Bill




> The dictionary file I have is not included in the DICOM file. I have
> a flat file that has all of the DICOM fields defined as a python
> dictionary.  [...] 

From python-tutor at ccoker.net  Fri Feb 23 18:12:02 2007
From: python-tutor at ccoker.net (Chuck Coker)
Date: Fri, 23 Feb 2007 09:12:02 -0800
Subject: [Tutor] How many loops does "break" jump out of?
In-Reply-To: <45DE5800.1090202@alum.rpi.edu>
References: <1172165960.45ddd5489c0e3@netmail.pipex.net>
	<45DE5800.1090202@alum.rpi.edu>
Message-ID: <45DF2062.2050504@ccoker.net>

Bob,

Watch your code blocks to make sure you don't change your logic
inadvertently. The code starting with "if (test_2)" and continuing to
the end of the snippet is inside the perpetual for loop which is inside
the "if (test_1)" condition.

Chuck



Bob Gailer wrote:

> etrade.griffiths at dsl.pipex.com wrote:
>
>> Am trying to convert a C program with a GOTO in it to Python and was 
>> wondering
>> how many loops a Python "break" jumps out of. Here is the C pseudo code
>>
>> if (test_1) {
>> for (;;) {
>> if (test_2) {
>> do_stuff();
>> } else if (test_2) {
>> for (ip=m1+m2+1;ip<=m;ip++) {
>> if (test_3) {
>> do_more_stuff();
>> if (test_4)
>> goto one;
>> }
>> }
>> for (i=m1+1;i<=m1+m2;i++)
>> do_even_more_stuff();
>>
>> do_yet_more_stuff();
>> }
>>
>> do_final_stuff();
>>
>> one: continue_program();
>
> I'd put this code in a function, replace the goto one with return, and
> put a call to the function in place of the code.
>
> def tests():
> if test_1:
> etc etc
> if test_4: return
>
> Some may take issue with that. You can, as Alan says, restructure the
> code, or use intermediate variables.

-- 
======================================================================
Chuck Coker, Software Developer                python-tutor at ccoker.net
Tyrell Software Corporation                      http://www.tyrell.com
Office: +1 949 458 1911 x 203                    Cell: +1 714 326 5939
======================================================================


From arildna at stud.ntnu.no  Fri Feb 23 18:30:40 2007
From: arildna at stud.ntnu.no (=?ISO-8859-1?Q? Arild_B._N=E6ss ?=)
Date: Fri, 23 Feb 2007 18:30:40 +0100
Subject: [Tutor] dictionaries and memory handling
Message-ID: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>

Hi,

I'm working on a python script for a task in statistical language  
processing. Briefly put it all boils down to counting different  
things in very large text files, doing simple computations on these  
counts and storing the results. I have been using python's dictionary  
type as my basic data structure of storing the counts. This has been  
a nice and simple solution, but turns out to be a bad idea in the  
long run, since the dictionaries become _very_ large, and create  
MemoryErrors when I try to run my script on texts of a certain size.

It seems that an SQL database would probably be the way to go, but I  
am a bit concerned about speed issues (even though running time is  
not all that crucial here). In any case it would probably take me a  
while to get a database up and running and I need to hand in some  
preliminary results pretty soon, so for now I think I'll postpone the  
SQL and try to tweak my current script to be able to run it on  
slightly longer texts than it can handle now.

So, enough beating around the bush, my questions are:

- Will the dictionaries take up less memory if I use numbers rather  
than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory  
than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so:  
Slightly less, or substantially less memory?

- What are common methods to monitor the memory usage of a script?  
Can I add a snippet to the code that prints out how many MBs of  
memory a certain dictionary takes up at that particular time?

regards,
Arild N?ss

From bill at celestial.net  Fri Feb 23 18:50:37 2007
From: bill at celestial.net (Bill Campbell)
Date: Fri, 23 Feb 2007 09:50:37 -0800
Subject: [Tutor] dictionaries and memory handling
In-Reply-To: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
References: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
Message-ID: <20070223175037.GA16549@ayn.mi.celestial.com>

On Fri, Feb 23, 2007, =?ISO-8859-1?Q? Arild_B._N=E6ss ?= wrote:
>Hi,
>
>I'm working on a python script for a task in statistical language  
>processing. Briefly put it all boils down to counting different  
>things in very large text files, doing simple computations on these  
>counts and storing the results. I have been using python's dictionary  
>type as my basic data structure of storing the counts. This has been  
>a nice and simple solution, but turns out to be a bad idea in the  
>long run, since the dictionaries become _very_ large, and create  
>MemoryErrors when I try to run my script on texts of a certain size.
>
>It seems that an SQL database would probably be the way to go, but I  
>am a bit concerned about speed issues (even though running time is  
>not all that crucial here). In any case it would probably take me a  
>while to get a database up and running and I need to hand in some  
>preliminary results pretty soon, so for now I think I'll postpone the  
>SQL and try to tweak my current script to be able to run it on  
>slightly longer texts than it can handle now.

You would probably be better off using one of the hash databases,
Berkeley, gdbm, etc. (see the anydbm documentation).  These can
be treated exactly like dictionaries in python, and are probably
orders of magnitude faster than using an SQL database.

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

``Rightful liberty is unobstructed action according to our will within
limits drawn around us by the equal rights of others. I do not add 'within
the limits of the law' because law is often but the tyrant's will, and
always so when it violates the rights of the individual.''
    -Thomas Jefferson

From chainsawtiney at gmail.com  Fri Feb 23 19:07:48 2007
From: chainsawtiney at gmail.com (Chung-hong Chan)
Date: Sat, 24 Feb 2007 02:07:48 +0800
Subject: [Tutor] Programming the behavior of a set of domino
Message-ID: <30d7ea360702231007u1ec54a9dlfa1bfbe4fc7631c8@mail.gmail.com>

Hello,

I am a newbie in computer programming and I am also not a native
English Speaker. I love to play domino and I would like to program a
simple domino game in python. Also a good opportunity for me to learn
some computer programming.
I need some help in my code which programming the behaviors of a set of domino.
Here is the code, generally a modification of the code from the deck
of card example in How to Think like a Computer Scientist.

#!/usr/bin/python
class domino:
	def __init__(self,a_end,b_end):
		self.a_end=a_end
		self.b_end=b_end
	def __str__(self):
		return ("["+str(self.a_end)+","+str(self.b_end)+"]")
	def __cmp__(self,other):
		if self.a_end==other.b_end and self.b_end==other.a_end:
			return 0
		return 1

class deck:
	def __init__(self,set_type):
		self.dominoes = []
		self.set_type = set_type
		for a_end in range(self.set_type+1):
			for b_end in range(self.set_type+1):
				self.dominoes.append(domino(a_end,b_end))
	def print_deck(self):
		for domino in self.dominoes:
			print domino
	def deck_len(self):
		print len(self.dominoes)


newdomino = deck(12)
newdomino.print_deck()
newdomino.deck_len()

if domino(1,2)==domino(2,2):
	print "yes"
else:
	print "no"

each piece of domino have a_end and b_end. domino (1,2) and
domino(2,1) is the same and thus one of them should be removed. Now,
deck(12) will return 169 dominoes while the expected number of
dominoes is 91. Even I wrote a __cmp__ method for domino, list
membership (i.e. x in list) is not working because they are not a
exact duplicates.
Can anyone shed me some light to solve this problem?
Thank You.

Regards,
CH


-- 
"The scientists of today think deeply instead of clearly. One must be
sane to think clearly, but one can think deeply and be quite insane."
Nikola Tesla
http://www.macgrass.com

From alan.gauld at btinternet.com  Fri Feb 23 19:40:15 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Feb 2007 18:40:15 -0000
Subject: [Tutor] dictionaries and memory handling
References: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
	<20070223175037.GA16549@ayn.mi.celestial.com>
Message-ID: <ernceg$4qq$1@sea.gmane.org>

"Bill Campbell" <bill at celestial.net> wrote

>>It seems that an SQL database would probably be the way to go, but I
>>am a bit concerned about speed issues (even though running time is
> ...
> You would probably be better off using one of the hash databases,
> Berkeley, gdbm, etc. (see the anydbm documentation).  These can
> be treated exactly like dictionaries in python, and are probably
> orders of magnitude faster than using an SQL database.

I'm glad Bill suggested this because I'd forgotten about them 
entirely!
But while they wont literally be "orders of magnitude" faster - the
disk I/O subsystem is usually the main limiter here -  they will be
several factors faster, in fact many SQL databases use the dbm
database under the hood.

It's years since I used dbm, I must have a play - just for old
times sake! :-)

Alan G. 



From bill at celestial.net  Fri Feb 23 21:08:07 2007
From: bill at celestial.net (Bill Campbell)
Date: Fri, 23 Feb 2007 12:08:07 -0800
Subject: [Tutor] dictionaries and memory handling
In-Reply-To: <ernceg$4qq$1@sea.gmane.org>
References: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
	<20070223175037.GA16549@ayn.mi.celestial.com>
	<ernceg$4qq$1@sea.gmane.org>
Message-ID: <20070223200807.GB25301@ayn.mi.celestial.com>

On Fri, Feb 23, 2007, Alan Gauld wrote:
>"Bill Campbell" <bill at celestial.net> wrote
>
>>>It seems that an SQL database would probably be the way to go, but I
>>>am a bit concerned about speed issues (even though running time is
>> ...
>> You would probably be better off using one of the hash databases,
>> Berkeley, gdbm, etc. (see the anydbm documentation).  These can
>> be treated exactly like dictionaries in python, and are probably
>> orders of magnitude faster than using an SQL database.
>
>I'm glad Bill suggested this because I'd forgotten about them 
>entirely!
>But while they wont literally be "orders of magnitude" faster - the
>disk I/O subsystem is usually the main limiter here -  they will be
>several factors faster, in fact many SQL databases use the dbm
>database under the hood.

While the disk subsystem is going to be a factor, the overhead
communicating with the SQL server, parsing the queries, etc. will be far
greater than calculating location of the record using the hashed key.

FWIW: I've found that the size of Berkeley DB btree files can be
significantly less than the Berkeley hash files.

I would really like to see somebody come up with a good alternative to the
Berkeley DB stuff from sleepcat.  The source code is the most godawfull
mess if #ifn*defs I've ever seen, with frequent API even in minor release
levels.  Take a look at the bdb source in python or perl if you want to see
what I'm talking about.

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

``the purpose of government is to reign in the rights of the people''
    -Bill Clinton during an interview on MTV in 1993

From atpridgen at mail.utexas.edu  Fri Feb 23 21:15:04 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Fri, 23 Feb 2007 14:15:04 -0600
Subject: [Tutor] Dictionaries of Tuples of Strings
Message-ID: <f989e6210702231215l7322c610hfdd45136cfc87383@mail.gmail.com>

Hello,

When I have a tuple with a single string in a dictionary entry and
try to iterate over the tuple and it breaks the string into individual
characters.  Is this supposed to be happening?

This problem is a little tricky to explain so I have included the
output and the corresponding example code.  In the example I have a
dictionary with tuples of strings as the values.  If I have more than
one tuple, I am ok and the value is not broken into individual
characters (look at the "type="in the code below.  If I have only one
string in the tuple value, then the string is broken into individual
characters.  Thanks again,

Adam.

Output:

name="years_of_newbness" type="xs:hexbinary"
name="years_of_newbness" type="xs:integer"

name="newb" type="x"
name="newb" type="s"
name="newb" type=":"
name="newb" type="t"
name="newb" type="r"
name="newb" type="i"
name="newb" type="n"
name="newb" type="g"

Example.py:

import sets

def Foo (elements=None):
    e_types = set()
    str = ""
    for k in elements:
        e_types.clear()
        for j in TYPES_PYTHON_TO_XML[k[1]]:# <-- Problem arises here
            # a tuple with a single string in dictionary is broken apart
            if j in e_types: continue
            str += CreateXMLElement(k[0], j)+"\n"
            e_types.add(j)
    print str

def CreateXMLComplex(name, elements):
    return XML_COMPLEX_STMNT%(name, elements)

def CreateXMLElement(name, type):
    return XML_ELEMENT_STMNT%(name, type)

XML_ELEMENT_STMNT = "name=\"%s\" type=\"%s\" "

TYPES_PYTHON_TO_XML = {
           'int':('xs:hexbinary','xs:integer'),
           'str':("xs:string")
           }
Foo([("years_of_newbness", "int")]) # <-- Works, more than one element
in the tuple
Foo([('newb', 'str')])# <-- Fails, only one element in the tuple
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Example.py
Type: text/x-python
Size: 893 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070223/94e43070/attachment.py 

From bds at waywood.co.uk  Fri Feb 23 21:44:12 2007
From: bds at waywood.co.uk (Barnaby Scott)
Date: Fri, 23 Feb 2007 20:44:12 +0000
Subject: [Tutor] miniwiki 1.3 BETA bugs
In-Reply-To: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>
References: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>
Message-ID: <45DF521C.2080509@waywood.co.uk>

Kirk Z. Bailey wrote:
> ok, let's post this again. last time went into purgatory instead of the list. hmmm....
> 
> I am working on updating miniwiki. the current beta code has rendering problems with wikiwords and external sites under some circumstances. Here is a link to the latest code:
> 
>     http://www.tinylist.org/MW.txt
> 
> 
> 
> 
> 
> 
> 
> 
> Blessed Be!
>        - Kirk Bailey
>          Largo FL USA
> 
>         
>  kniht  
> +-----+ http://www.mylemonadestand.biz/ - play the lemonade game!
> | BOX | http://www.tinylist-org/ Freedom software
> +-----+ In HER Service- http://www.pinellasintergroupsociety.org/
>  think  http://www.seaxtradusa.org/ - The Seax Wica Trad in the USA!
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


No idea if it has anything to do with your problem, but it struck me 
that the iswikiword() function (and processword() which seems to be a 
helper for it) could be replaced with one line, and it would be reliable!

def iswikiword(word):
         return bool(re.match('^([A-Z][a-z]+){2,}$', word))

Of course you need to import re, but that seems a small price to pay!

HTH

Barnaby Scott

From nephish at gmail.com  Fri Feb 23 22:02:56 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 23 Feb 2007 15:02:56 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <45DCAD90.2010101@gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
	<45DCA92F.4070700@gmail.com>
	<384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
	<45DCAD90.2010101@gmail.com>
Message-ID: <384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com>

ok, i am good with what you have explained here,
now i am on a similar problem.

the data i need is in a condensed format. in other words, they are
sending 2 values in three bytes.

so if i have 3 values say a = 53, b = 13, and c = 31

so value 1 is the first byte ( a ) and the first 4 bits of the second byte (b)
value 2 is the last 4 bits of byte (b) and byte (c)

so i believe i do shifting here. as in i do a
(a << 4) * 32 + b

but i am not getting what i think that i should be, and i think it's
because i am not getting rid of the bytes that i am not using.

i have looked at the struct module, but can't figgure out how to do
this type of thing with it.

thanks

shawn


On 2/21/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> shawn bright wrote:
> > oh, sorry, i meant how to get the 0x0A27 out of two bytes
> > a = 0x27 and b = 0x8A
> I don't see what the number 0x0A27 has to do with bytes 0x27 and 0x8A,
> but I'll assume you meant
> 0x0A for b.
> >
> > actually, in my script, i am not using the hex values at all, i have
> > these because they are examples in the documentation of a machine i am
> > talking to. i am actually using ord(a) and ord(b) to get digital
> > values of the numbers
> >
> > so, i guess a better question is how to get 2599 from the ord(a) and
> > ord(b), how do i put the two bytes together to make one number?
> Well, if you have the bytes originally, instead of ording them, hex them.
> so... given these bytes
> bytelist = [chr(0x27),chr(0x8A)]
> hexlist = []
> for item in bytelist:
>  hexlist.append(hex(item)[2:].zfill(2))
>
> print int('0x' + ''.join(hexlist) , 16)
>
> A less roundabout way to do this:
>
> given the number
> 0x0A,
> this is stored in the system the same as the number 10.
>  >>> 0x0A
> 10
> As you can see.
> So having the ord values is okay, because they're the same values as the
> hex of the bytes, just represented in a different base.
> Okay, now we'll assume that a byte is 8 bits.
> Because of this, we know that the number
> 0xFFEE
> is the same as
> (0xFF << 8) + 0xEE
> In other words, the higher byte is shifted over by 8 bits, and the other
> value is not shifted.
> This idea could easily be expanded to encompass byte strings of any length.
> Oh, and in the case of your example values,
>  >>> (0x0A << 8) + 0x27
> 2599
>
> Note that the + operator has higher (or the same?) precedence than the
> binary shift left.
> This means that the value 0x0A will be shifted by 8+0x27 times if the
> parenthesis are missing.
>
> Other equivalent operations:
>  >>> 0x0A * 256 + 0x27
> 2599
>  >>> 0x0A * 2**8 + 0x27
> 2599
>
> But like Kent said, you probably should use struct or something like that.
> Just in case you're interested, I'm sending this e-mail as well.
> HTH,
> -Luke
> >>
> >
>
>

From rabidpoobear at gmail.com  Fri Feb 23 22:06:17 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Feb 2007 15:06:17 -0600
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <f989e6210702231215l7322c610hfdd45136cfc87383@mail.gmail.com>
References: <f989e6210702231215l7322c610hfdd45136cfc87383@mail.gmail.com>
Message-ID: <45DF5749.6020903@gmail.com>

Adam Pridgen wrote:
> Hello,
>
> When I have a tuple with a single string in a dictionary entry and
> try to iterate over the tuple and it breaks the string into individual
> characters.  Is this supposed to be happening?
>
> This problem is a little tricky to explain so I have included the
> output and the corresponding example code.  In the example I have a
> dictionary with tuples of strings as the values.  If I have more than
> one tuple, I am ok and the value is not broken into individual
> characters (look at the "type="in the code below.  If I have only one
> string in the tuple value, then the string is broken into individual
> characters.  

That's because you can't make tuples of single values.
Parenthesis are ways of controlling order of operation.
They don't create tuples unless there's more than one value.
Example:
 >>> x = (((((((((('hello'))))))))))
 >>> type(x)
<type 'str'>
 >>> x = [[[[[[[[[['hello']]]]]]]]]]
 >>> type(x)
<type 'list'>

Think of it like this:
a TUple needs TWO elements or more.
Solution:
use lists.  They can contain single elements.

When you write
 >>> x = ('somestring')
you might think it's creating a single-value tuple, but it's not.
Consider this:
y = 5
z = 23
x = (y * (z + y) / y ** 3)

In this case you wouldn't expect these parenthesis to build tuples, 
would you?

Hope that helps somewhat,
-Luke


From rabidpoobear at gmail.com  Fri Feb 23 22:18:08 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Feb 2007 15:18:08 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>	
	<45DCA92F.4070700@gmail.com>	
	<384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>	
	<45DCAD90.2010101@gmail.com>
	<384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com>
Message-ID: <45DF5A10.5030905@gmail.com>

shawn bright wrote:
> ok, i am good with what you have explained here,
> now i am on a similar problem.
>
> the data i need is in a condensed format. in other words, they are
> sending 2 values in three bytes.
>
> so if i have 3 values say a = 53, b = 13, and c = 31
>
> so value 1 is the first byte ( a ) and the first 4 bits of the second 
> byte (b)
> value 2 is the last 4 bits of byte (b) and byte (c)
Please try not to interchange your terms, it makes your questions confusing.
'so if i have 3 values say a = 53, b = 13, and c = 31'
Should be 'so if I have 3 bytes'
because immediately after, you talk about your extracted data as 'values.'
It's not too big of a deal, but it was confusing at first.
>
> so i believe i do shifting here. as in i do a
> (a << 4) * 32 + b
You need to read an article on bit manipulation.
I'll give you a summary of what you're trying to do.
given the byte
x = 1 1 0 0 0 1 1 0
If you want to extract just the four most significant bits, [1 1 0 0],
you shift the number TO THE RIGHT by 4.
x >> 4
will result in 4 shifts like so:
1 1 0 0 0 1 1 0 -> 1 1 0 0 0 1 1
1 1 0 0 0 1 1 -> 1 1 0 0 0 1
1 1 0 0 0 1 -> 1 1 0 0 0
1 1 0 0 0 -> 1 1 0 0
Which results in the number 0x0C or 12.
Now, since these are the MSB, you could shift back 4 places
x << 4
1 1 0 0 -> 1 1 0 0 0
1 1 0 0 0 -> 1 1 0 0 0 0
1 1 0 0 0 0 -> 1 1 0 0 0 0 0
1 1 0 0 0 0 0 -> 1 1 0 0 0 0 0 0

but I don't know if you want to do that or not.
and if you wanted to do that, you could just use a bitmask from the 
beginning.  see the next part.

Now as for the least significant bits:
recall that

1 1 0 0 0 1 0 0 & 0 0 0 0 1 1 1 1
will yeild
0 0 0 0 + whatever the last 4 bits are in the first item.

Hope that helps.
It's better if you take the time to really understand what is happening 
in all these cases, so you won't have to experiment with trial and error.
-Luke

From mail at timgolden.me.uk  Fri Feb 23 22:24:29 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 23 Feb 2007 21:24:29 +0000
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <45DF5749.6020903@gmail.com>
References: <f989e6210702231215l7322c610hfdd45136cfc87383@mail.gmail.com>
	<45DF5749.6020903@gmail.com>
Message-ID: <45DF5B8D.7060205@timgolden.me.uk>

Luke Paireepinart wrote:

> That's because you can't make tuples of single values.
> Parenthesis are ways of controlling order of operation.
> They don't create tuples unless there's more than one value.

> Think of it like this:
> a TUple needs TWO elements or more.
> Solution:
> use lists.  They can contain single elements.

Don't know where you got that one from:

<code>
t = (1,)
type (t)

</code>

In fact, in a certain way, it's the comma which makes the tuple.
Brackets are only needed in some circs to disambiguate (eg in
parameter lists to functions)

<code>
t = 1,
type (t)
</code>

TJG

From sconce at in-spec-inc.com  Fri Feb 23 22:26:18 2007
From: sconce at in-spec-inc.com (Bill Sconce)
Date: Fri, 23 Feb 2007 16:26:18 -0500
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <f989e6210702231215l7322c610hfdd45136cfc87383@mail.gmail.com>
References: <f989e6210702231215l7322c610hfdd45136cfc87383@mail.gmail.com>
Message-ID: <20070223162618.2530e300@laura>

Don't feel bad.  Everyone who works with Python bumps into this.
And more than once...

The preceding reply is correct.  But perhaps this is more specific:

> TYPES_PYTHON_TO_XML = {
>            'int':('xs:hexbinary','xs:integer'),
>            'str':("xs:string")
>            }


The problem is here:
>            'str':("xs:string")
This is semantically identical to:
>            'str':"xs:string"



Problem corrected:
>            'str':("xs:string",)
                               ^
                             comma
                             
It helps to think,
   tuples are made by commas
   parentheses (only) enclose expressions
It's not true that
   parentheses indicate tuples
(They don't.  Not unless there are "commas in there".)


HTH,

Bill

From rabidpoobear at gmail.com  Fri Feb 23 22:26:30 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Feb 2007 15:26:30 -0600
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <45DF5B8D.7060205@timgolden.me.uk>
References: <f989e6210702231215l7322c610hfdd45136cfc87383@mail.gmail.com>
	<45DF5749.6020903@gmail.com> <45DF5B8D.7060205@timgolden.me.uk>
Message-ID: <45DF5C06.5090103@gmail.com>

Tim Golden wrote:
> Luke Paireepinart wrote:
>
>> That's because you can't make tuples of single values.
>> Parenthesis are ways of controlling order of operation.
>> They don't create tuples unless there's more than one value.
>
>> Think of it like this:
>> a TUple needs TWO elements or more.
>> Solution:
>> use lists.  They can contain single elements.
>
> Don't know where you got that one from:
>
> <code>
> t = (1,)
> type (t)
>
> </code>
>
> In fact, in a certain way, it's the comma which makes the tuple.
> Brackets are only needed in some circs to disambiguate (eg in
> parameter lists to functions)
Ah yes , I forgot about that.  I've seen that before and wondered why 
there was that extra comma.
Oops.
I guess the difference, then, is whether your data collections need to 
be mutable or not.
>


From carroll at tjc.com  Fri Feb 23 22:41:57 2007
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 23 Feb 2007 13:41:57 -0800 (PST)
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <45DF5749.6020903@gmail.com>
Message-ID: <Pine.LNX.4.44.0702231334290.25020-100000@violet.rahul.net>

On Fri, 23 Feb 2007, Luke Paireepinart wrote:

> That's because you can't make tuples of single values.
> Think of it like this:
> a TUple needs TWO elements or more.

No, a tuple can also be of one element, or even none.  You can create a
single-element tuple either directly through the use of a trailing comma,
or via the tuple() method:

>>> t = "x",         # but this looks like a syntax error or a continued line
>>> t = ("x",)       # I think this is a little clearer, but still ugly
>>> t = tuple("x")   # my preference


You can also create an empty tuple, but I think only through the tuple() 
method:

>>> t = ,
SyntaxError: invalid syntax
>>> t = (,)
SyntaxError: invalid syntax
>>> t=tuple()
 
Any other way to create an empty tuple? 


From carroll at tjc.com  Fri Feb 23 22:44:54 2007
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 23 Feb 2007 13:44:54 -0800 (PST)
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <20070223162618.2530e300@laura>
Message-ID: <Pine.LNX.4.44.0702231343490.25020-100000@violet.rahul.net>

On Fri, 23 Feb 2007, Bill Sconce wrote:

> It's not true that
>    parentheses indicate tuples
> (They don't.  Not unless there are "commas in there".)

Except in one case, the empty tuple:

 t = ()


From nephish at gmail.com  Fri Feb 23 22:45:16 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 23 Feb 2007 15:45:16 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <45DF5A10.5030905@gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
	<45DCA92F.4070700@gmail.com>
	<384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
	<45DCAD90.2010101@gmail.com>
	<384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com>
	<45DF5A10.5030905@gmail.com>
Message-ID: <384c93600702231345y7954e480q7fe4b353a326e6e5@mail.gmail.com>

Thanks for your help, Luke.
i am trying to get a grasp on how all this works, which is the msb, lsb, etc..

if i use i bitmask of 240 it will mask the most significant 4 bits
so that only the most significant 4 bits remain..
like 53 & 240 = 48 ( because only the 32 and 16 are set)
and if i use 15 it should mask the least significant bits, right ?

now if i am using the first half of the 2nd byte, and making the first
byte the most significant.
i would shift the first byte to the Left by 4
byte1 << 4  then add ( byte2 & 240 )

so for the next number that i want that will consist of the 2nd half
of the 2nd byte as the most significant , i would take the second byte
with my bitmask then shift it right by 4 then add the third byte to
that .... am i getting this right
like x = ((byte2 & 240) << 4) + byte 3

i think ?

shawn


On 2/23/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> shawn bright wrote:
> > ok, i am good with what you have explained here,
> > now i am on a similar problem.
> >
> > the data i need is in a condensed format. in other words, they are
> > sending 2 values in three bytes.
> >
> > so if i have 3 values say a = 53, b = 13, and c = 31
> >
> > so value 1 is the first byte ( a ) and the first 4 bits of the second
> > byte (b)
> > value 2 is the last 4 bits of byte (b) and byte (c)
> Please try not to interchange your terms, it makes your questions confusing.
> 'so if i have 3 values say a = 53, b = 13, and c = 31'
> Should be 'so if I have 3 bytes'
> because immediately after, you talk about your extracted data as 'values.'
> It's not too big of a deal, but it was confusing at first.
> >
> > so i believe i do shifting here. as in i do a
> > (a << 4) * 32 + b
> You need to read an article on bit manipulation.
> I'll give you a summary of what you're trying to do.
> given the byte
> x = 1 1 0 0 0 1 1 0
> If you want to extract just the four most significant bits, [1 1 0 0],
> you shift the number TO THE RIGHT by 4.
> x >> 4
> will result in 4 shifts like so:
> 1 1 0 0 0 1 1 0 -> 1 1 0 0 0 1 1
> 1 1 0 0 0 1 1 -> 1 1 0 0 0 1
> 1 1 0 0 0 1 -> 1 1 0 0 0
> 1 1 0 0 0 -> 1 1 0 0
> Which results in the number 0x0C or 12.
> Now, since these are the MSB, you could shift back 4 places
> x << 4
> 1 1 0 0 -> 1 1 0 0 0
> 1 1 0 0 0 -> 1 1 0 0 0 0
> 1 1 0 0 0 0 -> 1 1 0 0 0 0 0
> 1 1 0 0 0 0 0 -> 1 1 0 0 0 0 0 0
>
> but I don't know if you want to do that or not.
> and if you wanted to do that, you could just use a bitmask from the
> beginning.  see the next part.
>
> Now as for the least significant bits:
> recall that
>
> 1 1 0 0 0 1 0 0 & 0 0 0 0 1 1 1 1
> will yeild
> 0 0 0 0 + whatever the last 4 bits are in the first item.
>
> Hope that helps.
> It's better if you take the time to really understand what is happening
> in all these cases, so you won't have to experiment with trial and error.
> -Luke
>

From carroll at tjc.com  Fri Feb 23 22:45:54 2007
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 23 Feb 2007 13:45:54 -0800 (PST)
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <Pine.LNX.4.44.0702231334290.25020-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0702231344580.25020-100000@violet.rahul.net>

On Fri, 23 Feb 2007, Terry Carroll wrote:

> You can also create an empty tuple, but I think only through the tuple() 
> method:
> >>> t=tuple()
>  
> Any other way to create an empty tuple? 

Answering my own question:

>>> t=()
>>> type(t)
<type 'tuple'>


From nephish at gmail.com  Fri Feb 23 22:47:23 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 23 Feb 2007 15:47:23 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <384c93600702231345y7954e480q7fe4b353a326e6e5@mail.gmail.com>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
	<45DCA92F.4070700@gmail.com>
	<384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
	<45DCAD90.2010101@gmail.com>
	<384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com>
	<45DF5A10.5030905@gmail.com>
	<384c93600702231345y7954e480q7fe4b353a326e6e5@mail.gmail.com>
Message-ID: <384c93600702231347x27ccf771l238990fd7c68ed38@mail.gmail.com>

whoops, meant this to the list, sorry Luke.

On 2/23/07, shawn bright <nephish at gmail.com> wrote:
> Thanks for your help, Luke.
> i am trying to get a grasp on how all this works, which is the msb, lsb, etc..
>
> if i use i bitmask of 240 it will mask the most significant 4 bits
> so that only the most significant 4 bits remain..
> like 53 & 240 = 48 ( because only the 32 and 16 are set)
> and if i use 15 it should mask the least significant bits, right ?
>
> now if i am using the first half of the 2nd byte, and making the first
> byte the most significant.
> i would shift the first byte to the Left by 4
> byte1 << 4  then add ( byte2 & 240 )
>
> so for the next number that i want that will consist of the 2nd half
> of the 2nd byte as the most significant , i would take the second byte
> with my bitmask then shift it right by 4 then add the third byte to
> that .... am i getting this right
> like x = ((byte2 & 240) << 4) + byte 3
>
> i think ?
>
> shawn
>
>
> On 2/23/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> > shawn bright wrote:
> > > ok, i am good with what you have explained here,
> > > now i am on a similar problem.
> > >
> > > the data i need is in a condensed format. in other words, they are
> > > sending 2 values in three bytes.
> > >
> > > so if i have 3 values say a = 53, b = 13, and c = 31
> > >
> > > so value 1 is the first byte ( a ) and the first 4 bits of the second
> > > byte (b)
> > > value 2 is the last 4 bits of byte (b) and byte (c)
> > Please try not to interchange your terms, it makes your questions confusing.
> > 'so if i have 3 values say a = 53, b = 13, and c = 31'
> > Should be 'so if I have 3 bytes'
> > because immediately after, you talk about your extracted data as 'values.'
> > It's not too big of a deal, but it was confusing at first.
> > >
> > > so i believe i do shifting here. as in i do a
> > > (a << 4) * 32 + b
> > You need to read an article on bit manipulation.
> > I'll give you a summary of what you're trying to do.
> > given the byte
> > x = 1 1 0 0 0 1 1 0
> > If you want to extract just the four most significant bits, [1 1 0 0],
> > you shift the number TO THE RIGHT by 4.
> > x >> 4
> > will result in 4 shifts like so:
> > 1 1 0 0 0 1 1 0 -> 1 1 0 0 0 1 1
> > 1 1 0 0 0 1 1 -> 1 1 0 0 0 1
> > 1 1 0 0 0 1 -> 1 1 0 0 0
> > 1 1 0 0 0 -> 1 1 0 0
> > Which results in the number 0x0C or 12.
> > Now, since these are the MSB, you could shift back 4 places
> > x << 4
> > 1 1 0 0 -> 1 1 0 0 0
> > 1 1 0 0 0 -> 1 1 0 0 0 0
> > 1 1 0 0 0 0 -> 1 1 0 0 0 0 0
> > 1 1 0 0 0 0 0 -> 1 1 0 0 0 0 0 0
> >
> > but I don't know if you want to do that or not.
> > and if you wanted to do that, you could just use a bitmask from the
> > beginning.  see the next part.
> >
> > Now as for the least significant bits:
> > recall that
> >
> > 1 1 0 0 0 1 0 0 & 0 0 0 0 1 1 1 1
> > will yeild
> > 0 0 0 0 + whatever the last 4 bits are in the first item.
> >
> > Hope that helps.
> > It's better if you take the time to really understand what is happening
> > in all these cases, so you won't have to experiment with trial and error.
> > -Luke
> >
>

From rabidpoobear at gmail.com  Fri Feb 23 22:49:33 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Feb 2007 15:49:33 -0600
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <Pine.LNX.4.44.0702231334290.25020-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0702231334290.25020-100000@violet.rahul.net>
Message-ID: <45DF616D.7070902@gmail.com>

Terry Carroll wrote:
> On Fri, 23 Feb 2007, Luke Paireepinart wrote:
>
>   
>> That's because you can't make tuples of single values.
>> Think of it like this:
>> a TUple needs TWO elements or more.
>>     
>
> No, a tuple can also be of one element, or even none.  You can create a
> single-element tuple either directly through the use of a trailing comma,
> or via the tuple() method:
>
>   
>>>> t = "x",         # but this looks like a syntax error or a continued line
>>>> t = ("x",)       # I think this is a little clearer, but still ugly
>>>> t = tuple("x")   # my preference
>>>>         
>
>   
 >>> x = tuple("hello")
 >>> x
('h', 'e', 'l', 'l', 'o')

It apparently doesn't work that way with iterables.
I think the 'way you'd expect it to work' using your preference is to create
('hello')
but if you're doing intergers or single-character strings, it shouldn't 
matter either way.


From bgailer at alum.rpi.edu  Fri Feb 23 23:13:07 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 23 Feb 2007 14:13:07 -0800
Subject: [Tutor] Programming the behavior of a set of domino
In-Reply-To: <30d7ea360702231007u1ec54a9dlfa1bfbe4fc7631c8@mail.gmail.com>
References: <30d7ea360702231007u1ec54a9dlfa1bfbe4fc7631c8@mail.gmail.com>
Message-ID: <45DF66F3.6000302@alum.rpi.edu>

Chung-hong Chan wrote:
> Hello,
>
> I am a newbie in computer programming and I am also not a native
> English Speaker. I love to play domino and I would like to program a
> simple domino game in python. Also a good opportunity for me to learn
> some computer programming.
> I need some help in my code which programming the behaviors of a set of domino.
> Here is the code, generally a modification of the code from the deck
> of card example in How to Think like a Computer Scientist.
>
> #!/usr/bin/python
> class domino:
>   
It is a convention in Python to capiatlize class names (e.g. class Domino)
> 	def __init__(self,a_end,b_end):
> 		self.a_end=a_end
> 		self.b_end=b_end
> 	def __str__(self):
> 		return ("["+str(self.a_end)+","+str(self.b_end)+"]")
> 	def __cmp__(self,other):
> 		if self.a_end==other.b_end and self.b_end==other.a_end:
> 			return 0
> 		return 1
>
> class deck:
> 	def __init__(self,set_type):
> 		self.dominoes = []
> 		self.set_type = set_type
> 		for a_end in range(self.set_type+1):
> 			for b_end in range(self.set_type+1):
> 				self.dominoes.append(domino(a_end,b_end))
> 	def print_deck(self):
> 		for domino in self.dominoes:
> 			print domino
> 	def deck_len(self):
> 		print len(self.dominoes)
>
>
> newdomino = deck(12)
> newdomino.print_deck()
> newdomino.deck_len()
>
> if domino(1,2)==domino(2,2):
> 	print "yes"
> else:
> 	print "no"
>
> each piece of domino have a_end and b_end. domino (1,2) and
> domino(2,1) is the same and thus one of them should be removed. Now,
> deck(12) will return 169 dominoes while the expected number of
> dominoes is 91. Even I wrote a __cmp__ method for domino, list
> membership (i.e. x in list) is not working because they are not a
> exact duplicates.
>   
To create only unique dominoes:

		for a_end in range(self.set_type+1):
			for b_end in range(a_end, self.set_type+1):
				self.dominoes.append(domino(a_end,b_end))

> Can anyone shed me some light to solve this problem?

-- 
Bob Gailer
510-978-4454


From sconce at in-spec-inc.com  Fri Feb 23 23:17:48 2007
From: sconce at in-spec-inc.com (Bill Sconce)
Date: Fri, 23 Feb 2007 17:17:48 -0500
Subject: [Tutor] Dictionaries of Tuples of Strings
In-Reply-To: <Pine.LNX.4.44.0702231344580.25020-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0702231334290.25020-100000@violet.rahul.net>
	<Pine.LNX.4.44.0702231344580.25020-100000@violet.rahul.net>
Message-ID: <20070223171748.33d328e5@laura>

On Fri, 23 Feb 2007 13:45:54 -0800 (PST)
Terry Carroll <carroll at tjc.com> wrote:

> > Any other way to create an empty tuple? 
> 
> Answering my own question:
> 
> >>> t=()
> >>> type(t)
> <type 'tuple'>


Giving the lie to my earlier summary (that tuples are
indicated by commas only -- arrgh  :)
______________________________________________________________________
All right, then, let's get it right.  From THE tutorial (in the kit):
    A tuple consists of a number of values separated by commas,
    for instance:
        >>> t = 12345, 54321, 'hello!'
        >>> t[0]
        12345
        >>> t
        (12345, 54321, 'hello!')
    ...As you see, on output tuples are always enclosed in parentheses,
    so that nested tuples are interpreted correctly; they may be input
    with or without surrounding parentheses, although often parentheses
    are necessary anyway (if the tuple is part of a larger expression).
    
    ...A special problem is the construction of tuples containing 0 
    or 1 items: the syntax has some extra quirks to accommodate these.
    Empty tuples are constructed by an empty pair of parentheses; 
    a tuple with one item is constructed by following a value with
    a comma (it is not sufficient to enclose a single value in
    parentheses). Ugly, but effective.
                  ^^^^
            in the original :)

    >>> empty = ()
    >>> singleton = 'hello',    # <-- note trailing comma
    >>> len(empty)
    0
    >>> len(singleton)
    1
    >>> singleton
    ('hello',)
    
 
 
HTH,

-Bill

From alan.gauld at btinternet.com  Sat Feb 24 02:54:11 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Feb 2007 01:54:11 -0000
Subject: [Tutor] stumped again adding bytes
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com><45DCA92F.4070700@gmail.com><384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com><45DCAD90.2010101@gmail.com>
	<384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com>
Message-ID: <ero5s5$620$1@sea.gmane.org>


"shawn bright" <nephish at gmail.com> wrote


> so i believe i do shifting here. as in i do a
> (a << 4) * 32 + b
>

Don't use shifting to extract the bits, use a bitmask
and & its much easier.

If you want to extract the left-most 4 bits use 0xf0
If you want to extract the righ-most bits use 0x0f

1 & 1 = 1
1 & 0 = 0

Or more generically:

1 & A = A

right = data & 0xf0
left = data & 0x0f

As easy as that.

Now if you need to stich the bits together you need to move
one element up by 4 bits which is where shifting comes in.

result = (data << 4) & right

> but i am not getting what i think that i should be, and i think it's
> because i am not getting rid of the bytes that i am not using.

Its easier to extract the bits into a new variable using a mask
as shown.

> i have looked at the struct module, but can't figgure out how to do
> this type of thing with it.

This is not what struct is for, don't try uising it for this. even if
you make it work its not the best tool.

Alan G. 



From alan.gauld at btinternet.com  Sat Feb 24 02:56:25 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Feb 2007 01:56:25 -0000
Subject: [Tutor] stumped again adding bytes
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com><45DCA92F.4070700@gmail.com><384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com><45DCAD90.2010101@gmail.com><384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com><45DF5A10.5030905@gmail.com>
	<384c93600702231345y7954e480q7fe4b353a326e6e5@mail.gmail.com>
Message-ID: <ero60a$6a4$1@sea.gmane.org>


"shawn bright" <nephish at gmail.com> wrote 

> if i use i bitmask of 240 it will mask the most significant 4 bits

When using bitmasks its much easier to think in hex (or octal).
there are exactly 2 hex digits per byte so you only need to think 
about each group of 4 bits and its hex bit pattern. It saves a 
heap of mental calculations!

Alan G.


From digitalxero at gmail.com  Sat Feb 24 11:50:41 2007
From: digitalxero at gmail.com (Dj Gilcrease)
Date: Sat, 24 Feb 2007 02:50:41 -0800
Subject: [Tutor] Embedding Python
Message-ID: <e9764b730702240250n44c9bf7dp9db2e3546d58f224@mail.gmail.com>

I am attempting to embed Python in a C++ app and have a question
before I get too far into it.

Is is possible to to dynamically create an extension module?
eg, I want a module name spam and I have a stuct that contains all my
method names, and a pointer to the proper c++ function to call

### Suto Code ###
typedef struct _COMMAND {
	CHAR Name[64];
	fCommand Function;
	struct _COMMAND* pLast;
	struct _COMMAND* pNext;
} COMMAND, *PCOMMAND;
### End Sudo Code ###

What I would like to do is something like

### Sudo Code ###
class MyClass
{
        MyClass(PCOMMAND pCommand ) {pComd = pCommand;}
	static PyObject* spam_Func(PyObject *self, PyObject *args)
	{
		PCHAR sLine = NULL;
		if (!PyArg_ParseTuple(args, "z", &sLine))
			return NULL;
		pCmd->Function(sLine);
		Py_RETURN_NONE;
	}
        static PCOMMAND pCmd;
};

static PyMethodDef Methods[] = {0}

PCOMMAND pCommand = pCommands;
while(pCommand)
{
        MyClass* cmd = new MyClass(pCommand);
        Methods[pCommand->Name, cmd->spam_Func, METH_VARARGS, ""];
        pCommand = pCommand->pNext;
}

Methods[NULL, NULL, 0, NULL];

PyMODINIT_FUNC initspam(void)
{
    (void) Py_InitModule("spam", Methods);
}
### End Sudo Code ###

Now I know my Sudo code wont work or I wouldnt be asking, but is it
possible to do something like that. The reason I ask is there are
about 150 commands, plus plugins can add and remove commands when they
get loaded or unloaded so I will need to add / remove their commands
from the spam module as well.

From nephish at gmail.com  Sat Feb 24 16:12:55 2007
From: nephish at gmail.com (shawn bright)
Date: Sat, 24 Feb 2007 09:12:55 -0600
Subject: [Tutor] stumped again adding bytes
In-Reply-To: <ero60a$6a4$1@sea.gmane.org>
References: <384c93600702211136q350dae79r973ad52ec4c367db@mail.gmail.com>
	<45DCA92F.4070700@gmail.com>
	<384c93600702211225j7159c3bdgbea97d7a4814007c@mail.gmail.com>
	<45DCAD90.2010101@gmail.com>
	<384c93600702231302m2aefd137g99b1d539d750b92f@mail.gmail.com>
	<45DF5A10.5030905@gmail.com>
	<384c93600702231345y7954e480q7fe4b353a326e6e5@mail.gmail.com>
	<ero60a$6a4$1@sea.gmane.org>
Message-ID: <384c93600702240712j3746bf72mf9c46d42bbd699e@mail.gmail.com>

Hey there, and thanks for all your help here, i started getting some
values that look like what they are supposed to. Funny, i have been
with python for over a year, and just downloaded a hex cheatsheet.

thanks again for all of the help, gents.

shawn

On 2/23/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "shawn bright" <nephish at gmail.com> wrote
>
> > if i use i bitmask of 240 it will mask the most significant 4 bits
>
> When using bitmasks its much easier to think in hex (or octal).
> there are exactly 2 hex digits per byte so you only need to think
> about each group of 4 bits and its hex bit pattern. It saves a
> heap of mental calculations!
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From deliberatus at verizon.net  Sat Feb 24 17:17:40 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sat, 24 Feb 2007 11:17:40 -0500
Subject: [Tutor] geeks like us and the rest of THEM
Message-ID: <45E06524.2090805@verizon.net>

OK, my project is to come up with a wiki which is easy to install and 
use in a windows laptop, to wikify the notebook into a hypernotebook.

ok, it must be EASY to install. And LEGAL.

MiniWiki is in python. I can do it in a self extracting installer as 
there is a nice free pone out there someplace- links please? BUT PYTHON 
IS ANOTHER MATTER. It needs to have python on the notebook, which is not 
the case. It aldso needs a small server in the notebook, and I have one 
in python and another in C++, which alas is not freeware.

The hurdle is it must be a legal and simple and almost droolproof 
solution from soup to nuts.

the beta solution is working in this laptop NOW. Now how do I turn this 
into a turnkey solution for THEM?

We are geeks. But the end result is intended for pointy haired bosses, 
soccer moms with Avon dealerships, and other regular humans. And as 
awlays, we must avoid the dread lawyer vampires.


-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From kent37 at tds.net  Sat Feb 24 17:23:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Feb 2007 11:23:25 -0500
Subject: [Tutor] DICOM Header
In-Reply-To: <20070223115210.0fbdcc34@laura>
References: <C38780AA415B144BB8F4384B82B606F31F143A@UHCX4.xds.umail.utah.edu>	<20070222150734.019d5ba3@laura>	<C38780AA415B144BB8F4384B82B606F31F1441@UHCX4.xds.umail.utah.edu>
	<20070223115210.0fbdcc34@laura>
Message-ID: <45E0667D.6080308@tds.net>

Bill Sconce wrote:
> On Thu, 22 Feb 2007 13:51:35 -0700
> "Andrew Liimatta" <Andrew.Liimatta at hsc.utah.edu> wrote:
> 
>> I have a directory that is filled with DICOM files that I obtained
>> by using the Offis DICOM tool kit.
> 
> Ah.  The light dawns.  I should offer to communicate with you off-list,
> and report back here after we've solved the problem.  I have DICOM files
> here, and it sounds like an interesting and useful thing to be able to
> do (inspect DICOM files with Python). 

Googling 'python dicom' yields a few hits that might be helpful.

Kent

From kent37 at tds.net  Sat Feb 24 17:33:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Feb 2007 11:33:45 -0500
Subject: [Tutor] index swap?
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF203224D73@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF203224D73@gsb-exchmb02.stanford.edu>
Message-ID: <45E068E9.4010605@tds.net>

Switanek, Nick wrote:
> Kent,
> 
> Thank you for the good suggestions. As you suspected, the data were not
> what I thought they were, which is a comforting thought since that's
> more evidence that I can trust python but can't always trust myself (no
> surprise there). I have multiple years of entries for each observation
> and the order of the columns was interchanged midway through. I didn't
> see this at first because the rows are grouped by year, not by
> observation, so looking at the first twenty rows didn't reveal any
> problem.
> 
> Is there a speed advantage to using nested list comps, or stringing
> together multiple string method calls (e.g. str.rstrip().split('\t')),
> as you advise? Or is the main benefit cleaner code? Is there a limit to
> the number of nestings, apart from the potential for confusion in my
> head?

There is probably a speed advantage to the list comps but for me the big 
advantage is ease of use. It takes a little while to get used to the 
syntax and the idea but I find it much more natural because (to me) it 
clearly expresses an idea. I will think, "I need a list of all the lines 
in the file, split by tabs."  The list comp
[ line.split('\t') for line in open('file.txt') ]
expresses this naturally and concisely without introducing anything 
extra. The explicit for loop introduces a lot of mechanism that doesn't 
really have anything to do with the actual concept, it is just the way 
we are used to implementing the concept. The list comp avoids the 
explicit plumbing.

Nested list comps push the readability a bit, in this case it is pretty 
simple.

You can go to extremes to shoehorn something into a list comp but I 
don't see any point to that other than for fun and showing off and 
perhaps a useful optimization.

All IMO of course.

Kent

PS Please reply on-list

From kent37 at tds.net  Sat Feb 24 17:40:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Feb 2007 11:40:56 -0500
Subject: [Tutor] dictionaries and memory handling
In-Reply-To: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
References: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
Message-ID: <45E06A98.60302@tds.net>

  Arild B. N?ss wrote:
> Hi,
> 
> I'm working on a python script for a task in statistical language  
> processing. Briefly put it all boils down to counting different  
> things in very large text files, doing simple computations on these  
> counts and storing the results. I have been using python's dictionary  
> type as my basic data structure of storing the counts. This has been  
> a nice and simple solution, but turns out to be a bad idea in the  
> long run, since the dictionaries become _very_ large, and create  
> MemoryErrors when I try to run my script on texts of a certain size.
> 
> It seems that an SQL database would probably be the way to go, but I  
> am a bit concerned about speed issues (even though running time is  
> not all that crucial here). In any case it would probably take me a  
> while to get a database up and running and I need to hand in some  
> preliminary results pretty soon, so for now I think I'll postpone the  
> SQL and try to tweak my current script to be able to run it on  
> slightly longer texts than it can handle now.
> 
> So, enough beating around the bush, my questions are:
> 
> - Will the dictionaries take up less memory if I use numbers rather  
> than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory  
> than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so:  
> Slightly less, or substantially less memory?

I'm going to guess here. I think the number will take up 4 bytes plus 
the overhead of an object and the string will take about the number of 
bytes in the string plus the same overhead. But I am guessing and there 
are optimizations in the Python interpreter for both strings and ints 
that may affect this.
> 
> - What are common methods to monitor the memory usage of a script?  
> Can I add a snippet to the code that prints out how many MBs of  
> memory a certain dictionary takes up at that particular time?

See various discussions on comp.lang.python:
http://tinyurl.com/ysrocc

Kent
> 
> regards,
> Arild N?ss
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From kent37 at tds.net  Sat Feb 24 17:45:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Feb 2007 11:45:28 -0500
Subject: [Tutor] geeks like us and the rest of THEM
In-Reply-To: <45E06524.2090805@verizon.net>
References: <45E06524.2090805@verizon.net>
Message-ID: <45E06BA8.8020802@tds.net>

Kirk Bailey wrote:
> OK, my project is to come up with a wiki which is easy to install and 
> use in a windows laptop, to wikify the notebook into a hypernotebook.
> 
> ok, it must be EASY to install. And LEGAL.
> 
> MiniWiki is in python. I can do it in a self extracting installer as 
> there is a nice free pone out there someplace- links please? BUT PYTHON 
> IS ANOTHER MATTER. It needs to have python on the notebook, which is not 
> the case. It aldso needs a small server in the notebook, and I have one 
> in python and another in C++, which alas is not freeware.

You can use py2exe to create an executable that includes Python. You can 
create a single file executable or a directory that can be packaged up 
with InnoSetup or another installer maker.

Python has a simple built-in web server - see SimpleHTTPServer and 
CGIHTTPServer modules. Beyond that there are many freely distributed web 
servers available, CherryPy, Karrigell and Snakelets are all pretty small.

Kent
> 
> The hurdle is it must be a legal and simple and almost droolproof 
> solution from soup to nuts.
> 
> the beta solution is working in this laptop NOW. Now how do I turn this 
> into a turnkey solution for THEM?
> 
> We are geeks. But the end result is intended for pointy haired bosses, 
> soccer moms with Avon dealerships, and other regular humans. And as 
> awlays, we must avoid the dread lawyer vampires.
> 
> 


From deliberatus at verizon.net  Sun Feb 25 08:14:10 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sun, 25 Feb 2007 02:14:10 -0500
Subject: [Tutor] geeks like us and the rest of THEM
In-Reply-To: <45E06BA8.8020802@tds.net>
References: <45E06524.2090805@verizon.net> <45E06BA8.8020802@tds.net>
Message-ID: <45E13742.4070208@verizon.net>



Kent Johnson wrote:
> Kirk Bailey wrote:
>> OK, my project is to come up with a wiki which is easy to install and 
>> use in a windows laptop, to wikify the notebook into a hypernotebook.
>>
>> ok, it must be EASY to install. And LEGAL.
>>
>> MiniWiki is in python. I can do it in a self extracting installer as 
>> there is a nice free pone out there someplace- links please? BUT 
>> PYTHON IS ANOTHER MATTER. It needs to have python on the notebook, 
>> which is not the case. It aldso needs a small server in the notebook, 
>> and I have one in python and another in C++, which alas is not freeware.
> 
> You can use py2exe to create an executable that includes Python. You can 
> create a single file executable or a directory that can be packaged up 
> with InnoSetup or another installer maker.
That's part of it. a good installer is another, and I am loo]king at a 
couple.  A solid and drool-proof server is the remaining leg of the 
tripod. So far, none of the servers I have seen are satisfactory on all 
scores- simplicity to install, reliability, economy of cost, (free or 
unlimited license to me for a modest fee) and ease to configure if the 
use\r so wishes. the closest I have yet seen SMALL HTTP SERVER. And it 
is very good.
http://smallsrv.com/

The wiki code is considerably improved and is working 99.5% right, and 
is almost finished. I need to kick it hard with Doc Martins on to insure 
it is completely righteous before putting it to bed and worrying 
exclusively about the server and installer issues.

This has to be baby carriage reliable and simple for the business road 
warrior who has not a geekified bone in their body.


> 
> Python has a simple built-in web server - see SimpleHTTPServer and 
> CGIHTTPServer modules. Beyond that there are many freely distributed web 
> servers available, CherryPy, Karrigell and Snakelets are all pretty small.
> 
> Kent
>>
>> The hurdle is it must be a legal and simple and almost droolproof 
>> solution from soup to nuts.
>>
>> the beta solution is working in this laptop NOW. Now how do I turn 
>> this into a turnkey solution for THEM?
>>
>> We are geeks. But the end result is intended for pointy haired bosses, 
>> soccer moms with Avon dealerships, and other regular humans. And as 
>> awlays, we must avoid the dread lawyer vampires.
>>
>>
> 
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From alan.gauld at btinternet.com  Sun Feb 25 10:14:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Feb 2007 09:14:35 -0000
Subject: [Tutor] geeks like us and the rest of THEM
References: <45E06524.2090805@verizon.net> <45E06BA8.8020802@tds.net>
	<45E13742.4070208@verizon.net>
Message-ID: <errk1u$bnb$1@sea.gmane.org>


"Kirk Bailey" <deliberatus at verizon.net> wrote

> couple.  A solid and drool-proof server is the remaining leg of the

Take a look at xitami

http://www.xitami.com/download.htm

Free, small, flexible, configurable and fast being written in C.

HTH,

Alan G. 



From chris.arndt at web.de  Sun Feb 25 12:42:54 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Sun, 25 Feb 2007 12:42:54 +0100
Subject: [Tutor] Group sequence pairwise
Message-ID: <45E1763E.4070601@web.de>

Given a sequence, how can I group it pairwise, so that I get

[(s0, s1), (s2, s3), ... , (sn-1, sn)]

or, if len(s)%2 != 0

[(s0, s1), (s2, s3), ... , (sn, None)]


I have tried to find a solution, using itertools, but I'm not very
experienced in functional stuff, so I got confused. There is a recipe
("pairwise") in the itertools docs, that does something similar but not
quite what I want.

Ultimately, I want to display the items of the sequence in a two-column
table.

Chris

From rabidpoobear at gmail.com  Sun Feb 25 12:53:41 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 25 Feb 2007 05:53:41 -0600
Subject: [Tutor] Group sequence pairwise
In-Reply-To: <45E1763E.4070601@web.de>
References: <45E1763E.4070601@web.de>
Message-ID: <45E178C5.7050507@gmail.com>

Christopher Arndt wrote:
> Given a sequence, how can I group it pairwise, so that I get
>
> [(s0, s1), (s2, s3), ... , (sn-1, sn)]
>
> or, if len(s)%2 != 0
>
> [(s0, s1), (s2, s3), ... , (sn, None)]
>
>
> I have tried to find a solution, using itertools, but I'm not very
> experienced in functional stuff, so I got confused. 
Do you mean you're not experienced in using functions or do you mean 
you're inexperienced at functional programming?
(If you are not completely sure you know what functional programming is, 
that's probably not what you're doing)
I  don't know very much about FP, so I can't tell if this is some common 
idiom in that style or not.
> There is a recipe
> ("pairwise") in the itertools docs, that does something similar but not
> quite what I want.
>   
Well, this is fairly simple to do with list comprehensions...
 >>> x = [1,2,3,4,5,6,7]
 >>> if len(x) % 2 != 0: x.append(None)

 >>> [(x[a],x[a+1]) for a in range(0,len(x),2)]
[(1, 2), (3, 4), (5, 6), (7, None)]

Dunno if that's what you're after,
also note it modifies the list by adding a None at the end.
That's just the way I chose to do it, but if you need it to not modify 
it should be possible as well.
HTH,
-Luke
>   


From chris.arndt at web.de  Sun Feb 25 14:06:55 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Sun, 25 Feb 2007 14:06:55 +0100
Subject: [Tutor] Group sequence pairwise
In-Reply-To: <45E178C5.7050507@gmail.com>
References: <45E1763E.4070601@web.de> <45E178C5.7050507@gmail.com>
Message-ID: <45E189EF.3070609@web.de>

Luke Paireepinart schrieb:
> Christopher Arndt wrote:
>> I have tried to find a solution, using itertools, but I'm not very
>> experienced in functional stuff, so I got confused. 
> Do you mean you're not experienced in using functions or do you mean 
> you're inexperienced at functional programming?

I mean functional programming.

> Well, this is fairly simple to do with list comprehensions...
>  >>> x = [1,2,3,4,5,6,7]
>  >>> if len(x) % 2 != 0: x.append(None)
> 
>  >>> [(x[a],x[a+1]) for a in range(0,len(x),2)]
> [(1, 2), (3, 4), (5, 6), (7, None)]

I came a up with a similar solution:

for i in xrange(0, len(s), 2):
    do_something(s[i])
    if i+1 <= len(s):
	do_something(s[i+1])
    else:
        do_something(None)

or

try:
    for i in xrange(0, len(s), 2):
        do_something(s[i])
	do_something(s[i+1])
except IndexError:
    do_something(None)
    raise StopIteration

> Dunno if that's what you're after,

Not exactly. I wonder if this is possible without modifying the original
sequence (could be not a list too) and I'd also like to find a solution
that generally applies to iterables.

Chris

From dperlman at wisc.edu  Sun Feb 25 14:17:56 2007
From: dperlman at wisc.edu (David Perlman)
Date: Sun, 25 Feb 2007 07:17:56 -0600
Subject: [Tutor] geeks like us and the rest of THEM
In-Reply-To: <45E13742.4070208@verizon.net>
References: <45E06524.2090805@verizon.net> <45E06BA8.8020802@tds.net>
	<45E13742.4070208@verizon.net>
Message-ID: <9F0B3892-4EF8-41EA-B4EC-004266991000@wisc.edu>

Keep in mind that things generally become extremely reliable only  
after extensive real-world testing.  TANSTAAFL....

On Feb 25, 2007, at 1:14 AM, Kirk Bailey wrote:

> This has to be baby carriage reliable and simple for the business road
> warrior who has not a geekified bone in their body.

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From dperlman at wisc.edu  Sun Feb 25 14:36:07 2007
From: dperlman at wisc.edu (David Perlman)
Date: Sun, 25 Feb 2007 07:36:07 -0600
Subject: [Tutor] Group sequence pairwise
In-Reply-To: <45E189EF.3070609@web.de>
References: <45E1763E.4070601@web.de> <45E178C5.7050507@gmail.com>
	<45E189EF.3070609@web.de>
Message-ID: <6AEA5408-BF2D-4313-851C-8A1281EA4C83@wisc.edu>

I found this by "using Google".  You should be able to make a simple  
modification (I can think of a couple of ways to do it) to have it  
pad the end with "None".  It is 100% iterator input and output.

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

On Feb 25, 2007, at 7:06 AM, Christopher Arndt wrote:

> Luke Paireepinart schrieb:
>> Christopher Arndt wrote:
>>> I have tried to find a solution, using itertools, but I'm not very
>>> experienced in functional stuff, so I got confused.
>> Do you mean you're not experienced in using functions or do you mean
>> you're inexperienced at functional programming?
>
> I mean functional programming.
>
>> Well, this is fairly simple to do with list comprehensions...
>>>>> x = [1,2,3,4,5,6,7]
>>>>> if len(x) % 2 != 0: x.append(None)
>>
>>>>> [(x[a],x[a+1]) for a in range(0,len(x),2)]
>> [(1, 2), (3, 4), (5, 6), (7, None)]
>
> I came a up with a similar solution:
>
> for i in xrange(0, len(s), 2):
>     do_something(s[i])
>     if i+1 <= len(s):
> 	do_something(s[i+1])
>     else:
>         do_something(None)
>
> or
>
> try:
>     for i in xrange(0, len(s), 2):
>         do_something(s[i])
> 	do_something(s[i+1])
> except IndexError:
>     do_something(None)
>     raise StopIteration
>
>> Dunno if that's what you're after,
>
> Not exactly. I wonder if this is possible without modifying the  
> original
> sequence (could be not a list too) and I'd also like to find a  
> solution
> that generally applies to iterables.
>
> Chris
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From jsmith at medplus.com  Sun Feb 25 16:16:24 2007
From: jsmith at medplus.com (Smith, Jeff)
Date: Sun, 25 Feb 2007 10:16:24 -0500
Subject: [Tutor] List and comprehension questions
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A0201283B60@EXCHMAIL01.corp.medplus.com>

I'm getting use to using list iteration and comprehension but still have
some questions.

1. I know to replace
    for i in range(len(list1)):
        do things with list1[i]
with
    for li in list1:
        do things with li
but what if there are two lists that you need to access in sync.  Is
there a simple way to replace
    for i in range(len(list1)):
        do things with list1[i] and list2[i]
with a simple list iteration?

2. I frequently replace list iterations with comprehensions
    list2 = list()
    for li in list1:
        list2.append(somefun(li))
becomes
    list2 = [somefun(li) for li in list1]
but is there a similar way to do this with dictionaries?
    dict2 = dict()
    for (di, dv) in dict1.iteritems():
        dict2[di] = somefun(dv)

3. Last but not least.  I understand the replacement in #2 above is the
proper Pythonic idiom, but what if a list isn't being created.  Is it
considered properly idiomatic to replace
    for li in list1:
        somefun(li)
with
    [somefun(li) for li in list1]

Thanks for the input!
Jeff

From kent37 at tds.net  Sun Feb 25 17:17:22 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 25 Feb 2007 11:17:22 -0500
Subject: [Tutor] List and comprehension questions
In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A0201283B60@EXCHMAIL01.corp.medplus.com>
References: <288A3B43F7B2224D9C8441C9FC5D6A0201283B60@EXCHMAIL01.corp.medplus.com>
Message-ID: <45E1B692.9020802@tds.net>

Smith, Jeff wrote:
> I'm getting use to using list iteration and comprehension but still have
> some questions.
> 
> 1. I know to replace
>     for i in range(len(list1)):
>         do things with list1[i]
> with
>     for li in list1:
>         do things with li
> but what if there are two lists that you need to access in sync.  Is
> there a simple way to replace
>     for i in range(len(list1)):
>         do things with list1[i] and list2[i]
> with a simple list iteration?

Use zip() to generate pairs from both (or multiple) lists:
for i1, i2 in zip(list1, list2):
   do things with i1 and i2

> 
> 2. I frequently replace list iterations with comprehensions
>     list2 = list()
>     for li in list1:
>         list2.append(somefun(li))
> becomes
>     list2 = [somefun(li) for li in list1]
> but is there a similar way to do this with dictionaries?
>     dict2 = dict()
>     for (di, dv) in dict1.iteritems():
>         dict2[di] = somefun(dv)

You can construct a dictionary from a sequence of (key, value) pairs so 
this will work (using a generator expression here, add [] for Python < 2.4):
dict2 = dict( (di, somefun(dv) for di, dv in dict1.iteritems() )

> 
> 3. Last but not least.  I understand the replacement in #2 above is the
> proper Pythonic idiom, but what if a list isn't being created.  Is it
> considered properly idiomatic to replace
>     for li in list1:
>         somefun(li)
> with
>     [somefun(li) for li in list1]

I think this is somewhat a matter of personal preference; IMO it is 
ugly, I reserve list comps for when I actually want a list.

Kent

From chris.arndt at web.de  Sun Feb 25 18:58:21 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Sun, 25 Feb 2007 18:58:21 +0100
Subject: [Tutor] Group sequence pairwise
In-Reply-To: <6AEA5408-BF2D-4313-851C-8A1281EA4C83@wisc.edu>
References: <45E1763E.4070601@web.de>
	<45E178C5.7050507@gmail.com>	<45E189EF.3070609@web.de>
	<6AEA5408-BF2D-4313-851C-8A1281EA4C83@wisc.edu>
Message-ID: <45E1CE3D.4000809@web.de>

David Perlman schrieb:
> I found this by "using Google".  You should be able to make a simple  
> modification (I can think of a couple of ways to do it) to have it  
> pad the end with "None".  It is 100% iterator input and output.
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279

Yes, this looks just like what I need, thanks for the pointer. I guessed
that the islice function would probably be part of the solution, but I
couldn't quite grok how it works.

Chris

From dkuhlman at rexx.com  Sun Feb 25 19:46:37 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 25 Feb 2007 10:46:37 -0800
Subject: [Tutor] Embedding Python
In-Reply-To: <e9764b730702240250n44c9bf7dp9db2e3546d58f224@mail.gmail.com>
References: <e9764b730702240250n44c9bf7dp9db2e3546d58f224@mail.gmail.com>
Message-ID: <20070225184637.GA78381@cutter.rexx.com>

On Sat, Feb 24, 2007 at 02:50:41AM -0800, Dj Gilcrease wrote:
> I am attempting to embed Python in a C++ app and have a question
> before I get too far into it.
> 
> Is is possible to to dynamically create an extension module?
> eg, I want a module name spam and I have a stuct that contains all my
> method names, and a pointer to the proper c++ function to call

If you have not already, you will want to look at SWIG
(http://www.swig.org/).  SWIG will generate C or C++ code from a
header file containing structs and classes and function
declarations.  That generated code can then be compiled and linked
to create a shared library (.so on Linux/UNIX or .dll on Windows),
which can then be loaded with the Python "import" statement.

It seems a bit of a stretch to me, but I suppose that could all be
done from within your application, perhaps by using os.system or
popen.popenx (x = 2,3, 4).  See 
http://docs.python.org/lib/module-popen2.html.

I'l let others on the list comment on whether this is dangerous.  I
suppose if all the code (that is compiled by SWIG) is under your
control or if you trust your users, it might not be too dangerous.

Dave


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

From digitalxero at gmail.com  Sun Feb 25 22:35:52 2007
From: digitalxero at gmail.com (Dj Gilcrease)
Date: Sun, 25 Feb 2007 13:35:52 -0800
Subject: [Tutor] Embedding Python
In-Reply-To: <20070225184637.GA78381@cutter.rexx.com>
References: <e9764b730702240250n44c9bf7dp9db2e3546d58f224@mail.gmail.com>
	<20070225184637.GA78381@cutter.rexx.com>
Message-ID: <e9764b730702251335j6e68d12l61d655f244dae5cc@mail.gmail.com>

On 2/25/07, Dave Kuhlman <dkuhlman at rexx.com> wrote:
> If you have not already, you will want to look at SWIG
> (http://www.swig.org/).  SWIG will generate C or C++ code from a
> header file containing structs and classes and function
> declarations.  That generated code can then be compiled and linked
> to create a shared library (.so on Linux/UNIX or .dll on Windows),
> which can then be loaded with the Python "import" statement.

>From what I can tell SWIG cannot be used to create Python modules that
talk to a running C++ app, which is why I am embedding then extending
Python, so the import mymodule will only work while my C++ app is
running

From bgailer at alum.rpi.edu  Mon Feb 26 00:37:27 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 25 Feb 2007 15:37:27 -0800
Subject: [Tutor] List and comprehension questions
In-Reply-To: <45E1B692.9020802@tds.net>
References: <288A3B43F7B2224D9C8441C9FC5D6A0201283B60@EXCHMAIL01.corp.medplus.com>
	<45E1B692.9020802@tds.net>
Message-ID: <45E21DB7.10304@alum.rpi.edu>

Kent Johnson wrote:
> Smith, Jeff wrote:
>   
>> I'm getting use to using list iteration and comprehension but still have
>> some questions.
>>
>> 1. I know to replace
>>     for i in range(len(list1)):
>>         do things with list1[i]
>> with
>>     for li in list1:
>>         do things with li
>> but what if there are two lists that you need to access in sync.  Is
>> there a simple way to replace
>>     for i in range(len(list1)):
>>         do things with list1[i] and list2[i]
>> with a simple list iteration?
>>     
>
> Use zip() to generate pairs from both (or multiple) lists:
> for i1, i2 in zip(list1, list2):
>    do things with i1 and i2
>
>   
>> 2. I frequently replace list iterations with comprehensions
>>     list2 = list()
>>     for li in list1:
>>         list2.append(somefun(li))
>> becomes
>>     list2 = [somefun(li) for li in list1]
>> but is there a similar way to do this with dictionaries?
>>     dict2 = dict()
>>     for (di, dv) in dict1.iteritems():
>>         dict2[di] = somefun(dv)
>>     
>
> You can construct a dictionary from a sequence of (key, value) pairs so 
> this will work (using a generator expression here, add [] for Python < 2.4):
> dict2 = dict( (di, somefun(dv) for di, dv in dict1.iteritems() )
>   
Missing )?

dict((di, somefun(dv)) for di, dv in dict1.iteritems())

>   
>> 3. Last but not least.  I understand the replacement in #2 above is the
>> proper Pythonic idiom, but what if a list isn't being created.  Is it
>> considered properly idiomatic to replace
>>     for li in list1:
>>         somefun(li)
>> with
>>     [somefun(li) for li in list1]
>>     
>
> I think this is somewhat a matter of personal preference; IMO it is 
> ugly, I reserve list comps for when I actually want a list.
>
> Kent


-- 
Bob Gailer
510-978-4454


From deliberatus at verizon.net  Mon Feb 26 05:15:35 2007
From: deliberatus at verizon.net (Kirk Z Bailey)
Date: Sun, 25 Feb 2007 23:15:35 -0500
Subject: [Tutor] miniwiki 1.3 BETA bugs
In-Reply-To: <45DF521C.2080509@waywood.co.uk>
References: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>
	<45DF521C.2080509@waywood.co.uk>
Message-ID: <45E25EE7.9030408@verizon.net>

RE leaves me totally confuzzzeddded. Yep, so confuised I'm having 
trouble spelling it. Sp this one line will replace both words and give a 
reliable result?

Barnaby Scott wrote:
[snip]
> No idea if it has anything to do with your problem, but it struck me 
> that the iswikiword() function (and processword() which seems to be a 
> helper for it) could be replaced with one line, and it would be reliable!
> 
> def iswikiword(word):
>         return bool(re.match('^([A-Z][a-z]+){2,}$', word))
> 
> Of course you need to import re, but that seems a small price to pay!
> 
> HTH
> 
> Barnaby Scott
> 
> 

-- 
end

Very Truly yours,
                  - Kirk Bailey,
                    Largo Florida

                        kniht
                       +-----+
                       | BOX |
                       +-----+
                        think


From hyperneato at gmail.com  Mon Feb 26 08:20:56 2007
From: hyperneato at gmail.com (Isaac)
Date: Sun, 25 Feb 2007 23:20:56 -0800
Subject: [Tutor] wav audio playback
Message-ID: <7260654a0702252320h389069d6t6bac87f887117e94@mail.gmail.com>

hello from a programming newbie.

I am writing a metronome function.
Currently, I am using a hack with the system bell:

[code]
def tick(rate):
    while true: #do until
C-c
        print '\a' #system bell inside
terminal
        time.sleep(rate) #pause at desired
rate
[/code]

I would like to use any audio clip for a 'beat' of the metronome.
I have looked into pyaudio for .wav clips. I installed the binary for
pyaudio but it put the files into site-packages folder in
my python-2.4 framework directory; I copied the files to the site-packages
folder under 2.5 but when I import pyaudio at the Python 2.5 interpreter I
get:

"""
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/pyaudio.py:101:
RuntimeWarning: Python C API version mismatch for module _portaudio: This
Python has API version 1013, module _portaudio has version 1012.
  import _portaudio as pa   """

It does play sound but how can I get rid of this error? Do I have to wait
for the newer version of portaudio and/or pyaudio to be released to keep
this error from happening? Should I be concerned with this warning?
Is there another, better, sound playback module that anyone recommend I
could use?

I have mac ppc os X 10.4.8 (would like to have cross platform functionality,
eventually)
Using Python 2.5

cheers
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070225/8aa97800/attachment.htm 

From jeffpeery at yahoo.com  Mon Feb 26 08:12:38 2007
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Sun, 25 Feb 2007 23:12:38 -0800 (PST)
Subject: [Tutor] python shell not working like it used to
Message-ID: <621665.40494.qm@web43146.mail.sp1.yahoo.com>

hello, I just upgraded to python 2.5 and wxpython 2.6. I'm not sure the correct list for this but I'm trying to shove some variables into a py shell using the below code. this worked pretty well before, but now it gives me an error on the last line of my brief example. The error is:
   
  'dict' object has no attribute 'this' 
   
  it occurs on line 171 in shell.py. so I looked in shell.py and it looks like this:
   
      def __init__(self, other):
        """Create a ShellFacade instance."""
        d = self.__dict__
        d['other'] = other
        d['helpText'] = HELP_TEXT
        d['this'] = other.this
   
  "other" here is the dictionary I pass in (I think), so it's for some reason looking for some attribute in my dictionary called 'this'. of course my dictionary doesn't have this attribute. I have no idea what this is. any ideas? my few lines of code are below.
   
   
  import py
  import wx.py as py
   
  partList = {'this is some dictionary':1}
  pyWindow2          = py.editor.EditWindow(py.editor.Editor, splitterWindow1, -1)
pyWindow1          = py.shell.Shell(splitterWindow1, -1, introText = None)
pyWindow1.interp.locals['partList'] = py.shell.ShellFacade(partList)

 
---------------------------------
Never Miss an Email
Stay connected with Yahoo! Mail on your mobile. Get started!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070225/ec687553/attachment.html 

From Adam.Pridgen at gmail.com  Mon Feb 26 08:41:01 2007
From: Adam.Pridgen at gmail.com (Adam Pridgen)
Date: Mon, 26 Feb 2007 01:41:01 -0600
Subject: [Tutor] wav audio playback
In-Reply-To: <7260654a0702252320h389069d6t6bac87f887117e94@mail.gmail.com>
References: <7260654a0702252320h389069d6t6bac87f887117e94@mail.gmail.com>
Message-ID: <f989e6210702252341s30c45cb3sd89b4a14b24654ab@mail.gmail.com>

You are getting these errors because the API for Python varies by
release (e.g. 2.4 to 2.5)  due to additions, bug fixes, etc..  The
warning you are receiving is letting you know that it was compiled and
meant to be run on Python 2.4, and also subtly warning that problems
may arise when you run or write your scripts in the 2.5 environment.

To get rid of the error safely, if possible compile PyAudio for Python
2.5, or if you can regress back to Python 2.4 until PyAudio package is
available for Python 2.5.  There might also be a flag that can be set
to ignore warnings when you run the Python, but I am not sure about
this.  Some of the more Pythonic vets on the list might be able to
provide feed back on that.

However, from my past experience, regressing back to Python 2.4 seems
to be the easiest and safest option in most cases.

Regards,
Adam

On 2/26/07, Isaac <hyperneato at gmail.com> wrote:
> hello from a programming newbie.
>
> I am writing a metronome function.
> Currently, I am using a hack with the system bell:
>
> [code]
> def tick(rate):
>     while true: #do until C-c
>
>         print '\a' #system bell inside terminal
>
>         time.sleep(rate) #pause at desired rate
>
> [/code]
>
> I would like to use any audio clip for a 'beat' of the metronome.
> I have looked into pyaudio for .wav clips. I installed the binary for
> pyaudio but it put the files into site-packages folder in
> my python-2.4 framework directory; I copied the files to the site-packages
> folder under 2.5 but when I import pyaudio at the Python 2.5 interpreter I
> get:
>
> """
> /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/pyaudio.py:101:
> RuntimeWarning: Python C API version mismatch for module _portaudio: This
> Python has API version 1013, module _portaudio has version 1012.
>   import _portaudio as pa   """
>
> It does play sound but how can I get rid of this error? Do I have to wait
> for the newer version of portaudio and/or pyaudio to be released to keep
> this error from happening? Should I be concerned with this warning?
> Is there another, better, sound playback module that anyone recommend I
> could use?
>
>  I have mac ppc os X 10.4.8 (would like to have cross platform
> functionality, eventually)
>  Using Python 2.5
>
> cheers
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at btinternet.com  Mon Feb 26 10:02:50 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Feb 2007 09:02:50 -0000
Subject: [Tutor] python shell not working like it used to
References: <621665.40494.qm@web43146.mail.sp1.yahoo.com>
Message-ID: <eru7nu$n0s$1@sea.gmane.org>

"Jeff Peery" <jeffpeery at yahoo.com> wrote 

>      def __init__(self, other):
>        d['this'] = other.this
>   
>  "other" here is the dictionary I pass in (I think), 
> so it's for some reason looking for some attribute in 
> my dictionary called 'this'. 

other is whatever you pass in.
The code expects it to be dictionary like and to 
have a this attribute

> of course my dictionary doesn't have this attribute. 

So why is your code trying to access one if you know 
it doesn't exist? And why are you surprised at the 
error message? (Or is the init() not your code?)

> I have no idea what this is. any ideas? 

Youu seem to have answered your own question.
You are passing a dictionary into init() that does not 
have a this attribute but the code inside the init() is 
trying to access a this attribute. It can't find one so 
it raises an error.

Either remove the this access in init or add a thus 
attribute to your dictionary argument. Or pass an 
argument that does have a this attribute.

I'm slightly confused about what you are asking us to tell you?

HTH,


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


From alan.gauld at btinternet.com  Mon Feb 26 10:06:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Feb 2007 09:06:34 -0000
Subject: [Tutor] wav audio playback
References: <7260654a0702252320h389069d6t6bac87f887117e94@mail.gmail.com>
Message-ID: <eru7uu$nmb$1@sea.gmane.org>


"Isaac" <hyperneato at gmail.com> wrote
> """
> RuntimeWarning: Python C API version mismatch for module _portaudio: 
> This
> Python has API version 1013, module _portaudio has version 1012.
>  import _portaudio as pa   """
>
> It does play sound but how can I get rid of this error?

You need an updated binary.

> Is there another, better, sound playback module that anyone 
> recommend I
> could use?

On a Mac you could use the native QuickTime  stuff in MacOS.
There should be examples on the MacPython mailing list
archives and web site. And Apples quickTime documentation
is extensive. I suspect you will need the Cocoa extensions
but ISTR they come with the MacPython download.

Of course that then makes your code Mac dependant.

Alan G. 



From bds at waywood.co.uk  Mon Feb 26 13:12:32 2007
From: bds at waywood.co.uk (Barnaby Scott)
Date: Mon, 26 Feb 2007 12:12:32 +0000
Subject: [Tutor] miniwiki 1.3 BETA bugs
In-Reply-To: <45E25EE7.9030408@verizon.net>
References: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>	<45DF521C.2080509@waywood.co.uk>
	<45E25EE7.9030408@verizon.net>
Message-ID: <45E2CEB0.1090607@waywood.co.uk>

Kirk Z Bailey wrote:
> RE leaves me totally confuzzzeddded. Yep, so confuised I'm having 
> trouble spelling it. Sp this one line will replace both words and give a 
> reliable result?
> 
> Barnaby Scott wrote:
> [snip]
>> No idea if it has anything to do with your problem, but it struck me 
>> that the iswikiword() function (and processword() which seems to be a 
>> helper for it) could be replaced with one line, and it would be reliable!
>>
>> def iswikiword(word):
>>         return bool(re.match('^([A-Z][a-z]+){2,}$', word))
>>
>> Of course you need to import re, but that seems a small price to pay!
>>
>> HTH
>>
>> Barnaby Scott
>>
>>
> 

As far as I know this is 100% reliable - at least it works for me 
(www.waywood.co.uk/MonkeyWiki/). I suggest you test the function to your 
own satisfaction - feed it tricky 'possible' WikiWords, and see how it does!

I know what you mean - RE syntax is an unruly beast to try and wrestle 
with, but I *so* glad I made the effort. I don't claim to be anything 
like an expert, but I now find it very useful indeed.

Here's how the function's statement works in case you're interested:

bool(re.match('^([A-Z][a-z]+){2,}$', word))

re.match() will look for a match for us, according to the RE given as
the first argument, and the string you want to match against as the second

^ means we demand that the pattern matches from the beginning of the 
string to be tested - we don't want to say yes to 
anEmbeddedWikiWordLikeThis. (In fact because we are using re.match 
instead of re.search this is not strictly necessary, but makes it clearer)

([A-Z][a-z]+) means we want a group of letters, starting with a one in 
the range [A-Z] i.e. a capital, followed by [a-z]+ , meaning one or more 
lowercase letters ('one or more' is specified by the +). That whole 
pattern is parenthesised because we want the next element to refer to 
the whole thing

{2,} means we want a match only if our preceding pattern (i.e. a 
capitalised word) occurs a minimum of 2 times in a row, and a maximum of 
- well, we don't want to specify a maximum, so we leave it out. 
(YouMightInFactWantToSpecifyTheMaximumNumberOfWordsThatAreAllowedToAppearInYourWikiLinksToStopPeopleDoingSillyThingsLikeThis).

$ means we want a match only if the pattern reaches the end of the test 
string - i.e. we don't want to match a WordLikeThis62734.

As for bool() - nothing to do with RE, but if a match occurs, the result 
returned by re.match() is a MatchObject instance, otherwise None. I have 
used bool() to convert these two possible results into True or False 
though I guess this is not strictly necessary - the truth testing would 
happen implicitly outside the function anyway. However it seems right to 
return a boolean if that's what the function's obvious intent is.

HTH


Barnaby Scott








From arildna at stud.ntnu.no  Mon Feb 26 13:27:35 2007
From: arildna at stud.ntnu.no (=?ISO-8859-1?Q? Arild_B._N=E6ss ?=)
Date: Mon, 26 Feb 2007 13:27:35 +0100
Subject: [Tutor] dictionaries and memory handling
References: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
Message-ID: <DD5BFF7C-DB03-4C39-A183-D41BACEDE534@stud.ntnu.no>

Thanks a lot for your replies. Using a dbm seems to be a very good  
solution in some cases.

But most of my dictionaries are nested, and since both keys and  
values in the dbm 'dictionaries' have to be strings, I can't  
immediately see how I could get it to work.


A bit more detail: I deal with conditional probabilities, with up to  
4 parameters. These parameters are numbers or words and determine the  
value (which is always a number). E.g. I have a dictionary {p1:{p2: 
{p3:{p4:value}}}}, where the p's are different parameters. I  
sometimes need to sum over one or more of the parameters ? for now I  
have managed to structure the dictionaries so that I only need to sum  
over the innermost parameter, although this has been a bit cumbersome.

regards,
Arild N?ss


Videresendt melding:
> Fra: " Arild B. N?ss " <arildna at stud.ntnu.no>
> Dato: 23. februar 2007 18.30.40 GMT+01:00
> Til: tutor at python.org
> Emne: [Tutor] dictionaries and memory handling
> Delivered-To: tutor at bag.python.org
>
> Hi,
>
> I'm working on a python script for a task in statistical language
> processing. Briefly put it all boils down to counting different
> things in very large text files, doing simple computations on these
> counts and storing the results. I have been using python's dictionary
> type as my basic data structure of storing the counts. This has been
> a nice and simple solution, but turns out to be a bad idea in the
> long run, since the dictionaries become _very_ large, and create
> MemoryErrors when I try to run my script on texts of a certain size.
>
> It seems that an SQL database would probably be the way to go, but I
> am a bit concerned about speed issues (even though running time is
> not all that crucial here). In any case it would probably take me a
> while to get a database up and running and I need to hand in some
> preliminary results pretty soon, so for now I think I'll postpone the
> SQL and try to tweak my current script to be able to run it on
> slightly longer texts than it can handle now.
>
> So, enough beating around the bush, my questions are:
>
> - Will the dictionaries take up less memory if I use numbers rather
> than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory
> than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so:
> Slightly less, or substantially less memory?
>
> - What are common methods to monitor the memory usage of a script?
> Can I add a snippet to the code that prints out how many MBs of
> memory a certain dictionary takes up at that particular time?
>
> regards,
> Arild N?ss
> _______________________________________________
> 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/20070226/b24beea2/attachment.htm 

From arildna at stud.ntnu.no  Mon Feb 26 13:27:13 2007
From: arildna at stud.ntnu.no (=?ISO-8859-1?Q? Arild_B._N=E6ss ?=)
Date: Mon, 26 Feb 2007 13:27:13 +0100
Subject: [Tutor] dictionaries and memory handling
References: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
Message-ID: <5FD775B0-2883-4221-BD09-D35F4E33AC87@stud.ntnu.no>

Thanks a lot for your replies. Using a dbm seems to be a very good  
solution in some cases.

But most of my dictionaries are nested, and since both keys and  
values in the dbm 'dictionaries' have to be strings, I can't  
immediately see how I could get it to work.


A bit more detail: I deal with conditional probabilities, with up to  
4 parameters. These parameters are numbers or words and determine the  
value (which is always a number). E.g. I have a dictionary {p1:{p2: 
{p3:{p4:value}}}}, where the p's are different parameters. I  
sometimes need to sum over one or more of the parameters ? for now I  
have managed to structure the dictionaries so that I only need to sum  
over the innermost parameter, although this has been a bit cumbersome.

regards,
Arild N?ss


Videresendt melding:
> Fra: " Arild B. N?ss " <arildna at stud.ntnu.no>
> Dato: 23. februar 2007 18.30.40 GMT+01:00
> Til: tutor at python.org
> Emne: [Tutor] dictionaries and memory handling
> Delivered-To: tutor at bag.python.org
>
> Hi,
>
> I'm working on a python script for a task in statistical language
> processing. Briefly put it all boils down to counting different
> things in very large text files, doing simple computations on these
> counts and storing the results. I have been using python's dictionary
> type as my basic data structure of storing the counts. This has been
> a nice and simple solution, but turns out to be a bad idea in the
> long run, since the dictionaries become _very_ large, and create
> MemoryErrors when I try to run my script on texts of a certain size.
>
> It seems that an SQL database would probably be the way to go, but I
> am a bit concerned about speed issues (even though running time is
> not all that crucial here). In any case it would probably take me a
> while to get a database up and running and I need to hand in some
> preliminary results pretty soon, so for now I think I'll postpone the
> SQL and try to tweak my current script to be able to run it on
> slightly longer texts than it can handle now.
>
> So, enough beating around the bush, my questions are:
>
> - Will the dictionaries take up less memory if I use numbers rather
> than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory
> than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so:
> Slightly less, or substantially less memory?
>
> - What are common methods to monitor the memory usage of a script?
> Can I add a snippet to the code that prints out how many MBs of
> memory a certain dictionary takes up at that particular time?
>
> regards,
> Arild N?ss
> _______________________________________________
> 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/20070226/a10cfe4e/attachment-0001.html 

From singh01 at gmail.com  Mon Feb 26 17:48:29 2007
From: singh01 at gmail.com (Nagendra Singh)
Date: Mon, 26 Feb 2007 11:48:29 -0500
Subject: [Tutor] Running an exe from Python
In-Reply-To: <ermd0f$taq$1@sea.gmane.org>
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
	<d9e88eaf0702222138s51c3abdfs113ce9c4952aca81@mail.gmail.com>
	<ermd0f$taq$1@sea.gmane.org>
Message-ID: <cd2d0ceb0702260848o10b19adfx22d0e5d9292f02a6@mail.gmail.com>

Thanks a lot for all the suggestions. I used the function subprocess.call (
'c:\abc.exe  c:\data\file1'), but as before the command window opens and
closes very fast a value of 1 is displayed. How do I see the results??  I am
sorry if I sound dumb.

Singh

On 2/23/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote
>
> >> How can I get python to display
> >> the results in the interactive window or what is the right way to
> >> do this.
> >
> > Use os.popen:
>
> As Rikard, Richard and Hugo have pointed out there are
> numerous ways to do this in Python.
>
> The officially sanctioned way nowadays is to use the subprocess
> module. It supercedes all tthe previous methods being both more
> powerful, more flexible and fairly easy to use.
>
> All the techniques are discussed in my Using the OS topic in
> my tutorial.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> 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/20070226/b9ac7566/attachment.html 

From perlmunky at googlemail.com  Mon Feb 26 18:30:02 2007
From: perlmunky at googlemail.com (Dan Klose)
Date: Mon, 26 Feb 2007 17:30:02 +0000
Subject: [Tutor] Running an exe from Python
In-Reply-To: <cd2d0ceb0702260848o10b19adfx22d0e5d9292f02a6@mail.gmail.com>
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
	<d9e88eaf0702222138s51c3abdfs113ce9c4952aca81@mail.gmail.com>
	<ermd0f$taq$1@sea.gmane.org>
	<cd2d0ceb0702260848o10b19adfx22d0e5d9292f02a6@mail.gmail.com>
Message-ID: <b5facd7e0702260930k46e48f1iedbf9009bb3b6f1a@mail.gmail.com>

On 2/26/07, Nagendra Singh <singh01 at gmail.com> wrote:
>
> Thanks a lot for all the suggestions. I used the function subprocess.call( 'c:\abc.exe  c:\data\file1'), but as before the command window opens and
> closes very fast a value of 1 is displayed. How do I see the results??  I am
> sorry if I sound dumb.
>
> Singh
>
> On 2/23/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> >
> >
> > "Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote
> >
> > >> How can I get python to display
> > >> the results in the interactive window or what is the right way to
> > >> do this.
> > >
> > > Use os.popen:
> >
> > As Rikard, Richard and Hugo have pointed out there are
> > numerous ways to do this in Python.
> >
> > The officially sanctioned way nowadays is to use the subprocess
> > module. It supercedes all tthe previous methods being both more
> > powerful, more flexible and fairly easy to use.
> >
> > All the techniques are discussed in my Using the OS topic in
> > my tutorial.
> >
> > HTH,
> >
> > --
> > Alan Gauld
> > Author of the Learn to Program web site
> > http://www.freenetpages.co.uk/hp/alan.gauld
> >
> >
> > _______________________________________________
> > 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
>
>
I am not a big user of python, hence the username, however I used the
os.popen command as suggested by Rikard

In the shell:

data = os.popen('ls')
type(data)
    <type 'file'>
Then a loop over the data object
for f in data:
    print f

seemed to do the job.

I did notice that I could not capture the information to a var using the
subprocess call - I HAVE NOT READ THE DOCs (yet) - a quick look suggested
that this *should* work

The call I made using subprocess
from subprocess import call
foo = call("ls")
  <PRINTS CONTENTS OF /HOME/>
  <FOO IS == 0 >
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070226/92808bea/attachment.htm 

From dkuhlman at rexx.com  Mon Feb 26 19:03:34 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 26 Feb 2007 10:03:34 -0800
Subject: [Tutor] Embedding Python
In-Reply-To: <e9764b730702251335j6e68d12l61d655f244dae5cc@mail.gmail.com>
References: <e9764b730702240250n44c9bf7dp9db2e3546d58f224@mail.gmail.com>
	<20070225184637.GA78381@cutter.rexx.com>
	<e9764b730702251335j6e68d12l61d655f244dae5cc@mail.gmail.com>
Message-ID: <20070226180334.GB96257@cutter.rexx.com>

On Sun, Feb 25, 2007 at 01:35:52PM -0800, Dj Gilcrease wrote:
> On 2/25/07, Dave Kuhlman <dkuhlman at rexx.com> wrote:
> > If you have not already, you will want to look at SWIG
> > (http://www.swig.org/).  SWIG will generate C or C++ code from a
> > header file containing structs and classes and function
> > declarations.  That generated code can then be compiled and linked
> > to create a shared library (.so on Linux/UNIX or .dll on Windows),
> > which can then be loaded with the Python "import" statement.
> 
> >From what I can tell SWIG cannot be used to create Python modules that
> talk to a running C++ app, which is why I am embedding then extending
> Python, so the import mymodule will only work while my C++ app is
> running

A few additional thoughts, hoping to trigger a solution in your
mind.

SWIG creates Python modules only in the sense that it wraps the
existing implementation of a function (or C++ classes) in the C/C++
code needed to expose those functions or classes so that they can
be imported and used from Python scripts.  But, the implementation
of those functions/classes wrapped by SWIG is *still* in C/C++.  So
they can make calls back into embedding application, as long as
they are linked with the embedding application. (Whether you trust
your users enough to allow them to make C/C++ calls into your
application is an issue you should think about.)

One way of enabling *Python* scripts run by an embedding
application to communicate back with the embedding C/C++
application is to implement a Python module in C/C++ that makes
calls back into the embedding app.  For example, if the embedding
application contains a function named little_task, then you might
implement in C/C++ and expose to Python a module containing a
function wrap_little_task, which calls little_task.  Then, the
embedding C/C++ app can run a Python script which calls
wrap_little_task, which in turn calls little_task (which is back in
the embedding application).

In your case, perhaps, SWIG has wrapped up a function, so that it
can be called from Python.  That, after all is the point of using
SWIG.  But, the implementation of that function, whose declaration
was wrapped and exposed to Python by SWIG, can call any C/C++
function, even one in the embedding application.

One suggestion: Your embedding application runs scripts written in
Python which can import and call both functions exposed by the
embedding application and functions wrapped by SWIG and can pass
values back and forth between them.

And don't forget, SWIG has wrapped up a C/C++ function, let's say,
so that it can be called from Python.  That, after all is the point
of using SWIG.  But, the *implementation* of that C/C++ function,
whose declaration was wrapped and exposed to Python by SWIG, can
call any C/C++ function, even one in the embedding application.

Hope this helps.  And, hope it is not too confused.

Dave

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

From alan.gauld at btinternet.com  Mon Feb 26 19:31:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Feb 2007 18:31:36 -0000
Subject: [Tutor] Running an exe from Python
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com><d9e88eaf0702222138s51c3abdfs113ce9c4952aca81@mail.gmail.com><ermd0f$taq$1@sea.gmane.org>
	<cd2d0ceb0702260848o10b19adfx22d0e5d9292f02a6@mail.gmail.com>
Message-ID: <erv92c$1b8$1@sea.gmane.org>


"Nagendra Singh" <singh01 at gmail.com> wrote

> Thanks a lot for all the suggestions. I used the function
> subprocess.call ( 'c:\abc.exe  c:\data\file1'), but as before
> the command window opens and closes very fast
> a value of 1 is displayed. How do I see the results??

The result is 1 which indicates an error. You don't want
the result you want the outpur, which is a different thing
entirely! :-)

To get the output you need to access the output stream
of the process which is usually stdout. The old way to do
that was with os.popen, but the subprocess module
provides a new way. The m,odule docs describe how
to replace popen using subprocess' Popen class.

My tutorial shows an example of the same thing based
on the odule documentation.

Basically it looks like:

import subprocess
psout = subprocess.Popen(r'c:\abc.exe c:\data\file1', 
shell=True, stdout=PIPE).stdout
results = psout.read().split('\n')
Notice I enclosed the command with a raw string.Otherwise your 
backslashes get treated as escape characters. This might be why you 
are getting error codes back?Another way to avoid that is to use 
forward slashes which Python understands on DOS psout = 
subprocess.Popen('c:/abc.exe c:/data/file1', 
shell=True, stdout=PIPE).stdout
> I am sorry if I sound dumb.

Nope, just looking for the wrong thing. But you only
know that after you find out :-)

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



From taserian at gmail.com  Mon Feb 26 19:51:20 2007
From: taserian at gmail.com (taserian)
Date: Mon, 26 Feb 2007 13:51:20 -0500
Subject: [Tutor] Trouble creating DB2 drivers
Message-ID: <70dbc4d40702261051x41ddeb75ne64b02a522cdd1ff@mail.gmail.com>

I'm trying to build the DB2 drivers I downloaded from
http://sourceforge.net/projects/pydb2
but I'm getting an error message when I try installing them (after doing
"python setup.py install"):

Your DB2 root is: C:\Program Files\SQLLIB\
WARNING: it seems that you did not install 'Application Development Kit'.
Compilation may fail.

running install
running build
running build_py
running build_ext
building '_db2' extension
C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c /nologo
/Ox
 /MD /W3 /GX /DNDEBUG "-IC:\Program Files\SQLLIB\include"
-IC:\Python25\include
-IC:\Python25\PC /Tc_db2_module.c /Fobuild\temp.win32-
2.5\Release\_db2_module.obj
_db2_module.c
_db2_module.c(24) : fatal error C1083: Cannot open include file: 'sqlcli1.h':
No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio .NET
2003\Vc7\bin\cl.exe"' failed with exit status 2


- - - -

I can't seem to find anything through Google about the "Application
Development Kit" that the error mentions. Can anyone help?

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

From deliberatus at verizon.net  Mon Feb 26 20:46:09 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Mon, 26 Feb 2007 14:46:09 -0500
Subject: [Tutor] miniwiki 1.3 BETA bugs
In-Reply-To: <45E2CEB0.1090607@waywood.co.uk>
References: <6006643.472241172239421441.JavaMail.root@vms075.mailsrvcs.net>
	<45DF521C.2080509@waywood.co.uk> <45E25EE7.9030408@verizon.net>
	<45E2CEB0.1090607@waywood.co.uk>
Message-ID: <45E33901.5040905@verizon.net>

ok, when I have some time to do some coding I will work on trying this. 
AS is, it is pretty cleaned up, b utg making it less hairy and more 
definate in it's execution is a Great Good Thing(tm).

If the project intrests you I will sip up the current version and leave 
it on my domain so you can find it. when it is on the4re I will post a 
link on the list. this may take 2 days, I am being rather busy right now.

Barnaby Scott wrote:
> Kirk Z Bailey wrote:
>> RE leaves me totally confuzzzeddded. Yep, so confuised I'm having 
>> trouble spelling it. Sp this one line will replace both words and give 
>> a reliable result?
>>
>> Barnaby Scott wrote:
>> [snip]
>>> No idea if it has anything to do with your problem, but it struck me 
>>> that the iswikiword() function (and processword() which seems to be a 
>>> helper for it) could be replaced with one line, and it would be 
>>> reliable!
>>>
>>> def iswikiword(word):
>>>         return bool(re.match('^([A-Z][a-z]+){2,}$', word))
>>>
>>> Of course you need to import re, but that seems a small price to pay!
>>>
>>> HTH
>>>
>>> Barnaby Scott
>>>
>>>
>>
> 
> As far as I know this is 100% reliable - at least it works for me 
> (www.waywood.co.uk/MonkeyWiki/). I suggest you test the function to your 
> own satisfaction - feed it tricky 'possible' WikiWords, and see how it 
> does!
> 
> I know what you mean - RE syntax is an unruly beast to try and wrestle 
> with, but I *so* glad I made the effort. I don't claim to be anything 
> like an expert, but I now find it very useful indeed.
> 
> Here's how the function's statement works in case you're interested:
> 
> bool(re.match('^([A-Z][a-z]+){2,}$', word))
> 
> re.match() will look for a match for us, according to the RE given as
> the first argument, and the string you want to match against as the second
> 
> ^ means we demand that the pattern matches from the beginning of the 
> string to be tested - we don't want to say yes to 
> anEmbeddedWikiWordLikeThis. (In fact because we are using re.match 
> instead of re.search this is not strictly necessary, but makes it clearer)
> 
> ([A-Z][a-z]+) means we want a group of letters, starting with a one in 
> the range [A-Z] i.e. a capital, followed by [a-z]+ , meaning one or more 
> lowercase letters ('one or more' is specified by the +). That whole 
> pattern is parenthesised because we want the next element to refer to 
> the whole thing
> 
> {2,} means we want a match only if our preceding pattern (i.e. a 
> capitalised word) occurs a minimum of 2 times in a row, and a maximum of 
> - well, we don't want to specify a maximum, so we leave it out. 
> (YouMightInFactWantToSpecifyTheMaximumNumberOfWordsThatAreAllowedToAppearInYourWikiLinksToStopPeopleDoingSillyThingsLikeThis). 
> 
> 
> $ means we want a match only if the pattern reaches the end of the test 
> string - i.e. we don't want to match a WordLikeThis62734.
> 
> As for bool() - nothing to do with RE, but if a match occurs, the result 
> returned by re.match() is a MatchObject instance, otherwise None. I have 
> used bool() to convert these two possible results into True or False 
> though I guess this is not strictly necessary - the truth testing would 
> happen implicitly outside the function anyway. However it seems right to 
> return a boolean if that's what the function's obvious intent is.
> 
> HTH
> 
> 
> Barnaby Scott
> 
> 
> 
> 
> 
> 
> 
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From jsmith at medplus.com  Mon Feb 26 21:30:12 2007
From: jsmith at medplus.com (Smith, Jeff)
Date: Mon, 26 Feb 2007 15:30:12 -0500
Subject: [Tutor] Another list comprehension question
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A0201283EE3@EXCHMAIL01.corp.medplus.com>

I'm probably missing something simple here but is there anyway to
accomplish the following with a list comprehension?

def get_clists():
    return [1, 2, 3]

def get_clist(num):
    if num == 1:
        return ['a', 'b', 'c']
    if num == 2:
        return ['x', 'y', 'z']
    if num == 3:
        return ['p', 'q']

files = list()
for clist in get_clists():
    files += get_clist(clist)

My first attempt was to try 
[get_clist(c) for c in get_clists()]

but this returns a list of lists rather than the flat list from the
original.

Any help is appreciate...just trying to be as Pythonesque as possible
:-)

Jeff


From bgailer at alum.rpi.edu  Mon Feb 26 21:52:53 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 26 Feb 2007 12:52:53 -0800
Subject: [Tutor] Another list comprehension question
In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A0201283EE3@EXCHMAIL01.corp.medplus.com>
References: <288A3B43F7B2224D9C8441C9FC5D6A0201283EE3@EXCHMAIL01.corp.medplus.com>
Message-ID: <45E348A5.8060906@alum.rpi.edu>

Smith, Jeff wrote:
> I'm probably missing something simple here but is there anyway to
> accomplish the following with a list comprehension?
>   
Each element created by a comprehension corresponds to an element 
returned by the for (if) clause. So we have to find a way for the for 
clause to return successively 'a', 'b', 'c', 'x', 'y', 'z', 'p', 'q'. 
The only way I can see to do that is with a generator. Which I think is 
more work than necessary for your purposes.


> def get_clists():
>     return [1, 2, 3]
>
> def get_clist(num):
>     if num == 1:
>         return ['a', 'b', 'c']
>     if num == 2:
>         return ['x', 'y', 'z']
>     if num == 3:
>         return ['p', 'q']
>
> files = list()
>   
Or just files = []
> for clist in get_clists():
>     files += get_clist(clist)
>
> My first attempt was to try 
> [get_clist(c) for c in get_clists()]
>
> but this returns a list of lists rather than the flat list from the
> original.
>
> Any help is appreciate...just trying to be as Pythonesque as possible
> :-)
>
> Jeff
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454


From john at fouhy.net  Mon Feb 26 21:59:55 2007
From: john at fouhy.net (John Fouhy)
Date: Tue, 27 Feb 2007 09:59:55 +1300
Subject: [Tutor] Another list comprehension question
In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A0201283EE3@EXCHMAIL01.corp.medplus.com>
References: <288A3B43F7B2224D9C8441C9FC5D6A0201283EE3@EXCHMAIL01.corp.medplus.com>
Message-ID: <5e58f2e40702261259k35670666ne7b9a76c77904d61@mail.gmail.com>

Hi Jeff,

On 27/02/07, Smith, Jeff <jsmith at medplus.com> wrote:
> I'm probably missing something simple here but is there anyway to
> accomplish the following with a list comprehension?
>
> def get_clists():
>     return [1, 2, 3]
>
> def get_clist(num):
>     if num == 1:
>         return ['a', 'b', 'c']
>     if num == 2:
>         return ['x', 'y', 'z']
>     if num == 3:
>         return ['p', 'q']

This would be better represented as a dictionary:

>>> clists = { 1:['a', 'b', 'c'],
...            2:['x', 'y', 'z'],
...            3:['p', 'q'] }

You may also be able to replace get_clists() with a call to
clists.keys() (or just simple iteration), depending on what you are
doing.

>>> for k in clists:
...  print clists[k]
...
['a', 'b', 'c']
['x', 'y', 'z']
['p', 'q']

> files = list()
> for clist in get_clists():
>     files += get_clist(clist)

Just a comment -- you could write this as
"files.extend(get_clist(clist))", which would be slightly more
efficient.

> My first attempt was to try
> [get_clist(c) for c in get_clists()]
>
> but this returns a list of lists rather than the flat list from the
> original.

This will do it:

>>> [x for k in clists for x in clists[k]]
['a', 'b', 'c', 'x', 'y', 'z', 'p', 'q']

Or [x for k in get_clists() for x in get_clist(k)] using your original
structure.

HTH!

-- 
John.

From jeffpeery at yahoo.com  Mon Feb 26 20:37:05 2007
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Mon, 26 Feb 2007 11:37:05 -0800 (PST)
Subject: [Tutor] python shell not working like it used to
In-Reply-To: <eru7nu$n0s$1@sea.gmane.org>
Message-ID: <652828.55129.qm@web43141.mail.sp1.yahoo.com>

well the __init__() funciton is not my code, it is in:
 
 C:\Python24\Lib\site-packages\wx-2.6-msw-unicode\wx\py\shell.py
 
as I mentioned I upgraded wxpython... maybe I should email there... anyhow I just want to use my dictionary in the shell, but I'm not sure what the attribute 'this' is... it seems to be something different from my previous version of wxpython.

thanks. 
J

Alan Gauld <alan.gauld at btinternet.com> wrote: "Jeff Peery"  wrote 

>      def __init__(self, other):
>        d['this'] = other.this
>   
>  "other" here is the dictionary I pass in (I think), 
> so it's for some reason looking for some attribute in 
> my dictionary called 'this'. 

other is whatever you pass in.
The code expects it to be dictionary like and to 
have a this attribute

> of course my dictionary doesn't have this attribute. 

So why is your code trying to access one if you know 
it doesn't exist? And why are you surprised at the 
error message? (Or is the init() not your code?)

> I have no idea what this is. any ideas? 

Youu seem to have answered your own question.
You are passing a dictionary into init() that does not 
have a this attribute but the code inside the init() is 
trying to access a this attribute. It can't find one so 
it raises an error.

Either remove the this access in init or add a thus 
attribute to your dictionary argument. Or pass an 
argument that does have a this attribute.

I'm slightly confused about what you are asking us to tell you?

HTH,


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

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


 	
---------------------------------
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/20070226/bf7aab88/attachment.htm 

From bgailer at alum.rpi.edu  Mon Feb 26 22:24:57 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 26 Feb 2007 13:24:57 -0800
Subject: [Tutor] Another list comprehension question
In-Reply-To: <5e58f2e40702261259k35670666ne7b9a76c77904d61@mail.gmail.com>
References: <288A3B43F7B2224D9C8441C9FC5D6A0201283EE3@EXCHMAIL01.corp.medplus.com>
	<5e58f2e40702261259k35670666ne7b9a76c77904d61@mail.gmail.com>
Message-ID: <45E35029.9070308@alum.rpi.edu>

John Fouhy wrote:
[snip]
>
> Or [x for k in get_clists() for x in get_clist(k)] using your original
> structure.
>   
Well I learned something!

-- 
Bob Gailer
510-978-4454


From 3dbernard at gmail.com  Mon Feb 26 22:33:46 2007
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 26 Feb 2007 16:33:46 -0500
Subject: [Tutor] isinstance -> instance
Message-ID: <61d0e2b40702261333u41bd986by955ddc69c0d72fcc@mail.gmail.com>

Hello,

Following the guidelines here, at the bottom of the page:
http://www.python.org/dev/peps/pep-0008/

I'm using isinstance() to test the type of some data.
Now the thing is that, what is the name to use for a class instance?

For example, say I run this:

class A:
    def __init__( self ):
        self.a = 'a'

a = A()

print type( a )

Outputs:
<type 'instance'>




Now if I test against the instance type like I would for integer,
strings and the likes:

isinstance( a, instance )

Outputs:
NameError: name 'instance' is not defined


So I'm a bit at a loss here. I don't want to know if the instance is
an instance of a specific class, I just want to know if it's an
instance.


Thanks
Bernard

From Mike.Hansen at atmel.com  Mon Feb 26 22:44:20 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Mon, 26 Feb 2007 14:44:20 -0700
Subject: [Tutor] FW:  isinstance -> instance
Message-ID: <57B026980605A64F9B23484C5659E32E637505@poccso.US.ad.atmel.com>

Oops...I replied instead of replied all. 

> -----Original Message-----
> From: Mike Hansen 
> Sent: Monday, February 26, 2007 2:43 PM
> To: 'Bernard Lebel'
> Subject: RE: [Tutor] isinstance -> instance
> 
>  
> 
> > -----Original Message-----
> > From: tutor-bounces at python.org 
> > [mailto:tutor-bounces at python.org] On Behalf Of Bernard Lebel
> > Sent: Monday, February 26, 2007 2:34 PM
> > To: Tutor
> > Subject: [Tutor] isinstance -> instance
> > 
> > Hello,
> > 
> > Following the guidelines here, at the bottom of the page:
> > http://www.python.org/dev/peps/pep-0008/
> > 
> > I'm using isinstance() to test the type of some data.
> > Now the thing is that, what is the name to use for a class instance?
> > 
> > For example, say I run this:
> > 
> > class A:
> >     def __init__( self ):
> >         self.a = 'a'
> > 
> > a = A()
> > 
> > print type( a )
> > 
> > Outputs:
> > <type 'instance'>
> > 
> > 
> > 
> > 
> > Now if I test against the instance type like I would for integer,
> > strings and the likes:
> > 
> > isinstance( a, instance )
> > 
> > Outputs:
> > NameError: name 'instance' is not defined
> > 
> > 
> > So I'm a bit at a loss here. I don't want to know if the instance is
> > an instance of a specific class, I just want to know if it's an
> > instance.
> > 
> > 
> > Thanks
> > Bernard
> 
> Shouldn't that be
> 
> isinstance(a, A)
> 
> ?
> 
> Mike 

From 3dbernard at gmail.com  Mon Feb 26 22:58:59 2007
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 26 Feb 2007 16:58:59 -0500
Subject: [Tutor] FW: isinstance -> instance
In-Reply-To: <57B026980605A64F9B23484C5659E32E637505@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E637505@poccso.US.ad.atmel.com>
Message-ID: <61d0e2b40702261358m2c941ccmb1b204183387854@mail.gmail.com>

That's fine, but that tells me that 'a' is an instance of 'A'.
It doesn't, however, tell me if 'a' is an instance or the actual class object.


Thanks
Bernard



On 2/26/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:
> Oops...I replied instead of replied all.
>
> > -----Original Message-----
> > From: Mike Hansen
> > Sent: Monday, February 26, 2007 2:43 PM
> > To: 'Bernard Lebel'
> > Subject: RE: [Tutor] isinstance -> instance
> >
> >
> >
> > > -----Original Message-----
> > > From: tutor-bounces at python.org
> > > [mailto:tutor-bounces at python.org] On Behalf Of Bernard Lebel
> > > Sent: Monday, February 26, 2007 2:34 PM
> > > To: Tutor
> > > Subject: [Tutor] isinstance -> instance
> > >
> > > Hello,
> > >
> > > Following the guidelines here, at the bottom of the page:
> > > http://www.python.org/dev/peps/pep-0008/
> > >
> > > I'm using isinstance() to test the type of some data.
> > > Now the thing is that, what is the name to use for a class instance?
> > >
> > > For example, say I run this:
> > >
> > > class A:
> > >     def __init__( self ):
> > >         self.a = 'a'
> > >
> > > a = A()
> > >
> > > print type( a )
> > >
> > > Outputs:
> > > <type 'instance'>
> > >
> > >
> > >
> > >
> > > Now if I test against the instance type like I would for integer,
> > > strings and the likes:
> > >
> > > isinstance( a, instance )
> > >
> > > Outputs:
> > > NameError: name 'instance' is not defined
> > >
> > >
> > > So I'm a bit at a loss here. I don't want to know if the instance is
> > > an instance of a specific class, I just want to know if it's an
> > > instance.
> > >
> > >
> > > Thanks
> > > Bernard
> >
> > Shouldn't that be
> >
> > isinstance(a, A)
> >
> > ?
> >
> > Mike
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From malaclypse2 at gmail.com  Mon Feb 26 23:07:56 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 26 Feb 2007 17:07:56 -0500
Subject: [Tutor] FW: isinstance -> instance
In-Reply-To: <61d0e2b40702261358m2c941ccmb1b204183387854@mail.gmail.com>
References: <57B026980605A64F9B23484C5659E32E637505@poccso.US.ad.atmel.com>
	<61d0e2b40702261358m2c941ccmb1b204183387854@mail.gmail.com>
Message-ID: <16651e80702261407t6a30e8e3j6c9a35d788901e0d@mail.gmail.com>

On 2/26/07, Bernard Lebel <3dbernard at gmail.com> wrote:
> That's fine, but that tells me that 'a' is an instance of 'A'.
> It doesn't, however, tell me if 'a' is an instance or the actual class object.

It doesn't?

>>> class A:
	pass

>>> a = A()
>>> isinstance(a, A)
True
>>> isinstance(A, A)
False

If you want to know if a is an instance of any type, try this:
>>> import types
>>> isinstance (a, types.InstanceType)
True

I'm pretty sure that types.InstanceType only works on old-style
classes.  I believe you can check for an instance of a new-style class
with:
isinstance(a, object)

-- 
Jerry

From alan.gauld at btinternet.com  Mon Feb 26 23:14:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Feb 2007 22:14:45 -0000
Subject: [Tutor] isinstance -> instance
References: <61d0e2b40702261333u41bd986by955ddc69c0d72fcc@mail.gmail.com>
Message-ID: <ervm4q$m83$1@sea.gmane.org>


"Bernard Lebel" <3dbernard at gmail.com> wrote

> class A:
>    def __init__( self ):
>        self.a = 'a'
> 
> a = A()
> 
> print type( a )
> 
> Outputs:
> <type 'instance'>

So use types.Instancetype

import types as t
>>> class A: pass
...
>>> a = A()
>>> type(a)
<type 'instance'>
>>> type(A)
<type 'classobj'>
>>> type(a) == t.InstanceType
True
>>>

HTH,


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


From kent37 at tds.net  Mon Feb 26 23:26:34 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Feb 2007 17:26:34 -0500
Subject: [Tutor] FW: isinstance -> instance
In-Reply-To: <61d0e2b40702261358m2c941ccmb1b204183387854@mail.gmail.com>
References: <57B026980605A64F9B23484C5659E32E637505@poccso.US.ad.atmel.com>
	<61d0e2b40702261358m2c941ccmb1b204183387854@mail.gmail.com>
Message-ID: <45E35E9A.209@tds.net>

Bernard Lebel wrote:
> That's fine, but that tells me that 'a' is an instance of 'A'.
> It doesn't, however, tell me if 'a' is an instance or the actual class object.

I'm not sure what you are trying to do.

In [1]: class A: pass
    ...:
In [2]: a=A()
In [3]: isinstance(a, A)
Out[3]: True
In [4]: isinstance(A, A)
Out[4]: False

The actual class object is not an instance of itself.

 >>>> So I'm a bit at a loss here. I don't want to know if the instanceis
 >>>> an instance of a specific class, I just want to know if it's an
 >>>> instance.

*Everything* in Python is an instance of *some* class. int, str, classes 
themselves, modules, etc. Everything is an instance of something.

The specific <type 'instance'> is the type of instances of old-style 
classes. There is some funny business going on that I don't fully 
understand but AFAIK instances of old-style classes are in some sense 
all instances of this <type 'instance'>.

If you are trying to test whether an object is an instance of an 
old-style class you can do it like this (though I can't imagine why you 
would want to):

In [10]: class C:
    ....:      pass
    ....:
In [11]: c=C()
In [12]: isinstance(c, type(a))
Out[12]: True

Or you can import types and check against types.InstanceType:

In [13]: import types
In [14]: dir(types)
In [15]: isinstance(c, types.InstanceType)
Out[15]: True

Kent

From kent37 at tds.net  Mon Feb 26 23:29:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Feb 2007 17:29:55 -0500
Subject: [Tutor] FW: isinstance -> instance
In-Reply-To: <16651e80702261407t6a30e8e3j6c9a35d788901e0d@mail.gmail.com>
References: <57B026980605A64F9B23484C5659E32E637505@poccso.US.ad.atmel.com>	<61d0e2b40702261358m2c941ccmb1b204183387854@mail.gmail.com>
	<16651e80702261407t6a30e8e3j6c9a35d788901e0d@mail.gmail.com>
Message-ID: <45E35F63.4030903@tds.net>

Jerry Hill wrote:
> I believe you can check for an instance of a new-style class
> with:
> isinstance(a, object)

I'm not sure if that will ever fail. Given values from my previous post, 
I get:
In [16]: isinstance(a, object)
Out[16]: True
In [17]: isinstance(A, object)
Out[17]: True
In [18]: isinstance(b, object)
Out[18]: True
In [19]: isinstance(types, object)
Out[19]: True
In [20]: def f(): pass
    ....:
In [21]: isinstance(f, object)
Out[21]: True

Kent

From 3dbernard at gmail.com  Tue Feb 27 00:11:13 2007
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 26 Feb 2007 18:11:13 -0500
Subject: [Tutor] FW: isinstance -> instance
In-Reply-To: <45E35F63.4030903@tds.net>
References: <57B026980605A64F9B23484C5659E32E637505@poccso.US.ad.atmel.com>
	<61d0e2b40702261358m2c941ccmb1b204183387854@mail.gmail.com>
	<16651e80702261407t6a30e8e3j6c9a35d788901e0d@mail.gmail.com>
	<45E35F63.4030903@tds.net>
Message-ID: <61d0e2b40702261511w253e798ax6c2879d3ef4943c2@mail.gmail.com>

Okay..... right now I'm using types.InstanceType approach.


To elaborate on the context of my question, I have this module whose
only job is to test an object against a large array of types. The
thing is that I never know in advance what is going to be the data,
and it could be just about anything (string, int, float, bool, class
object, class instance, etc), and I never in advance against what type
it will be tested. Plus, in case the data is an instance of a class I
have coded, the module never knows what is the actual class object the
instance is obtained from.

Only the functions making call to this module "know" what they expect
from the module. There are countless of such functions, and each has
its own specificities.

So I'm aiming as a generic code as possible, where only the type of
the object is relevant, without any need for additional data.


Thanks
Bernard




On 2/26/07, Kent Johnson <kent37 at tds.net> wrote:
> Jerry Hill wrote:
> > I believe you can check for an instance of a new-style class
> > with:
> > isinstance(a, object)
>
> I'm not sure if that will ever fail. Given values from my previous post,
> I get:
> In [16]: isinstance(a, object)
> Out[16]: True
> In [17]: isinstance(A, object)
> Out[17]: True
> In [18]: isinstance(b, object)
> Out[18]: True
> In [19]: isinstance(types, object)
> Out[19]: True
> In [20]: def f(): pass
>     ....:
> In [21]: isinstance(f, object)
> Out[21]: True
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From justin.mailinglists at gmail.com  Tue Feb 27 02:32:23 2007
From: justin.mailinglists at gmail.com (Justin Ezequiel)
Date: Tue, 27 Feb 2007 09:32:23 +0800
Subject: [Tutor] Group sequence pairwise
Message-ID: <3c6718980702261732s7c6db7e0vfa7b2126f8e06005@mail.gmail.com>

>>> a = list('asdfg')
>>> map(None, a[::2], a[1::2])
[('a', 's'), ('d', 'f'), ('g', None)]
>>> a = list('asdfgh')
>>> map(None, a[::2], a[1::2])
[('a', 's'), ('d', 'f'), ('g', 'h')]
>>>

From Thane.Frivold at nokia.com  Tue Feb 27 02:49:09 2007
From: Thane.Frivold at nokia.com (Thane.Frivold at nokia.com)
Date: Mon, 26 Feb 2007 19:49:09 -0600
Subject: [Tutor] Question about profile.run() and decorators
Message-ID: <60A427E0B02CC34B98D22BDCAA25361203F1A1C9@daebe101.NOE.Nokia.com>

To whom it may concern,

	I was directed to this forum... I searched for 'decorator
profile' in the Python tutorial archives, and had no hits, so I hope
this is not a lame question.

	Is there a way to construct a string version (suitable to pass
into profile.run()) from what is available inside a decorator function?
I realize that what I am trying to do could probably be done otherwise,
but this arose out of questions and problems possed in a Python class I
just completed, and I am still trying to find my way around the
language. My 'best' attempt is shown below.

	Also, I have limited myself to a function with only 1 parameter,
but it seems to get even worse if you have 2 or more arguments, since
repr() takes only a single argument.

	BTW, I am using ActiveState Python 2.4.3 on Windows XP.

	Any and all suggestions or solutions welcomed.

	Thank you.

	Cheers,

- Thane

=-=-=

import profile

def myProfileDecorator(function):
  def newFunction(obj, *args):
    # This attempt does not seem to give an object expression that can
be used
    #expression = function.__name__ + '(' + repr(obj) + ',' +
repr(*args) + ')'

    # This attempt generates a NameError exception
    expression = function.__name__ + '(' + repr(*args) + ')'

    print 'About to call: profile.run(', expression, ')'
    profile.run(expression)
  return newFunction

import random

class Foo:
  @myProfileDecorator
  def results(x):
    print str(x) + " Done"

x = Foo()

print x.results("Almost")

=-=-=



 

From kent37 at tds.net  Tue Feb 27 04:25:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Feb 2007 22:25:58 -0500
Subject: [Tutor] Question about profile.run() and decorators
In-Reply-To: <60A427E0B02CC34B98D22BDCAA25361203F1A1C9@daebe101.NOE.Nokia.com>
References: <60A427E0B02CC34B98D22BDCAA25361203F1A1C9@daebe101.NOE.Nokia.com>
Message-ID: <45E3A4C6.9030809@tds.net>

Thane.Frivold at nokia.com wrote:

> 	Is there a way to construct a string version (suitable to pass
> into profile.run()) from what is available inside a decorator function?
> I realize that what I am trying to do could probably be done otherwise,
> but this arose out of questions and problems possed in a Python class I
> just completed, and I am still trying to find my way around the
> language. My 'best' attempt is shown below.

Take a look at profile.Profile.runcall() (look at the source for 
profile, it is not in the docs). This function takes an actual function 
object as its parameter rather than a string describing the function call.

Kent

> 
> 	Also, I have limited myself to a function with only 1 parameter,
> but it seems to get even worse if you have 2 or more arguments, since
> repr() takes only a single argument.
> 
> 	BTW, I am using ActiveState Python 2.4.3 on Windows XP.
> 
> 	Any and all suggestions or solutions welcomed.
> 
> 	Thank you.
> 
> 	Cheers,
> 
> - Thane
> 
> =-=-=
> 
> import profile
> 
> def myProfileDecorator(function):
>   def newFunction(obj, *args):
>     # This attempt does not seem to give an object expression that can
> be used
>     #expression = function.__name__ + '(' + repr(obj) + ',' +
> repr(*args) + ')'
> 
>     # This attempt generates a NameError exception
>     expression = function.__name__ + '(' + repr(*args) + ')'
> 
>     print 'About to call: profile.run(', expression, ')'
>     profile.run(expression)
>   return newFunction
> 
> import random
> 
> class Foo:
>   @myProfileDecorator
>   def results(x):
>     print str(x) + " Done"
> 
> x = Foo()
> 
> print x.results("Almost")
> 
> =-=-=
> 
> 
> 
>  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From enfors at enfors.net  Tue Feb 27 11:28:10 2007
From: enfors at enfors.net (Christer Enfors)
Date: Tue, 27 Feb 2007 11:28:10 +0100
Subject: [Tutor] Module search path problem
Message-ID: <45E407BA.40506@enfors.net>

I have two files, in the same directory: main.py, and user.py I have the 
following code in main.py:

   ----main.py----
   import user

   [snip]

   user_man = user.UserMan()
   -----end-----

This works without problems.

But then I tried moving user.py to a subdirectory, and adding that 
directory to Python's module search path, so this is what main.py looks 
like now:

   ----main.py---
   import sys
   sys.path.append("/correct/complete/path/to/subdir")

   import user  # Generates no error message, so it's finding user.py

   [snip]

   user_man = user.UserMan()
   -----end-----

But now I get an error message for the last line shown above:

   ----start----
   Traceback (most recent call last):
     File "./main.py", line 56, in ?
       driver.boot()
     File "./main.py", line 34, in boot
       user_man = user.UserMan()
   AttributeError: 'module' object has no attribute 'UserMan'
   -----end-----

What's up with this?

From kent37 at tds.net  Tue Feb 27 13:25:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Feb 2007 07:25:52 -0500
Subject: [Tutor] Module search path problem
In-Reply-To: <45E407BA.40506@enfors.net>
References: <45E407BA.40506@enfors.net>
Message-ID: <45E42350.8060205@tds.net>

Christer Enfors wrote:
> I have two files, in the same directory: main.py, and user.py
> 
> This works without problems.
> 
> But then I tried moving user.py to a subdirectory, and adding that 
> directory to Python's module search path

> But now I get an error message for the last line shown above:
> 
>    ----start----
>    Traceback (most recent call last):
>      File "./main.py", line 56, in ?
>        driver.boot()
>      File "./main.py", line 34, in boot
>        user_man = user.UserMan()
>    AttributeError: 'module' object has no attribute 'UserMan'
>    -----end-----
> 
> What's up with this?

There is a library module called 'user'. Since you appended to sys.path 
your program is finding the library module instead of your own.

Best solution is to rename your module to something else.

Kent

From govindgoyal at gmail.com  Tue Feb 27 16:28:18 2007
From: govindgoyal at gmail.com (govind goyal)
Date: Tue, 27 Feb 2007 20:58:18 +0530
Subject: [Tutor] Matching string
Message-ID: <f96f96bc0702270728ve5ce405we30a17ea5f712cbe@mail.gmail.com>

Hello,

I want to use a pattern matcing (regular expression) inside "if loop" such
that if it will find "*MBytes*" and *"Mbits/sec"* both *at a time *regardless
of there position in a particular string ,then only it executes code inside
"if block".

for example if my string is  *"[904]  1.0- 2.0 sec  1.19 MBytes  10.0Mbits/sec
2.345 ms    0/  850 (0%)"* then if condition evalutes to TRUE and code
inside it will be executed.

If my string is *"Server listening on UDP port 5001"* then if condition
evaluates to False and code inside it will be not executed.

Can anybody help?

Regards,
Govind
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070227/dc79e4e0/attachment.html 

From kent37 at tds.net  Tue Feb 27 16:55:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Feb 2007 10:55:25 -0500
Subject: [Tutor] Matching string
In-Reply-To: <f96f96bc0702270728ve5ce405we30a17ea5f712cbe@mail.gmail.com>
References: <f96f96bc0702270728ve5ce405we30a17ea5f712cbe@mail.gmail.com>
Message-ID: <45E4546D.4050002@tds.net>

govind goyal wrote:
> Hello,
>  
> I want to use a pattern matcing (regular expression) inside "if 
> loop" such that if it will find "*MBytes*" and *"Mbits/sec"* both *at a 
> time * regardless of there position in a particular string ,then only it 
> executes code inside "if block".
>  
> for example if my string is  *"[904]  1.0- 2.0 sec  1.19 MBytes  10.0 
> Mbits/sec  2.345 ms    0/  850 (0%)"* then if condition evalutes to TRUE 
> and code inside it will be executed.
>  
> If my string is *"Server listening on UDP port 5001"* then if condition 
> evaluates to False and code inside it will be not executed.

You don't need a regular expression for this, just search for both strings:

if 'MBytes' in s or 'Mbits/sec' in s:

You might want to change 'or' to 'and', I'm not sure which you want from 
your description.

Kent

From malaclypse2 at gmail.com  Tue Feb 27 17:16:41 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 27 Feb 2007 11:16:41 -0500
Subject: [Tutor] Matching string
In-Reply-To: <f96f96bc0702270728ve5ce405we30a17ea5f712cbe@mail.gmail.com>
References: <f96f96bc0702270728ve5ce405we30a17ea5f712cbe@mail.gmail.com>
Message-ID: <16651e80702270816p6102b819n1f7259682ccb181d@mail.gmail.com>

On 2/27/07, govind goyal <govindgoyal at gmail.com> wrote:
> Hello,
>
> I want to use a pattern matcing (regular expression) inside "if loop" such
> that if it will find "MBytes" and "Mbits/sec" both at a time  regardless of
> there position in a particular string ,then only it executes code inside "if
> block".


Something like this, perhaps?
>>> myStrings = ["[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec
2.345 ms    0/  850 (0%)",
	     "Server listening on UDP port 5001"]
>>> for myString in myStrings:
	if ("MBytes" in myString and "Mbits/sec" in myString):
		print myString

prints:
[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345 ms    0/  850 (0%)

Nothing in your example calls for the use of regular expressions, so I
didn't use them.

If you need to use a regular expression to extract the numeric portion
you could do something like this to extract the values you want once
you've identified the strings you need.

import re

myStrings = ["[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345
ms    0/  850 (0%)",
         "Server listening on UDP port 5001"]

mb_re = re.compile(r'(\d+\.{0,1}\d*) MBytes')
mbps_re = re.compile(r'(\d+\.{0,1}\d*) Mbits/sec')

for myString in myStrings:
    if ("MBytes" in myString and "Mbits/sec" in myString):
            print myString
            mb = mb_re.findall(myString)[0]
            mbps = mbps_re.findall(myString)[0]
            print "MBytes:", mb
            print "Mbits/sec:", mbps


prints:
[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345 ms    0/  850 (0%)
MBytes: 1.19
Mbits/sec: 10.0

-- 
Jerry

From bgailer at alum.rpi.edu  Tue Feb 27 17:49:14 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 27 Feb 2007 08:49:14 -0800
Subject: [Tutor] Module search path problem
In-Reply-To: <45E407BA.40506@enfors.net>
References: <45E407BA.40506@enfors.net>
Message-ID: <45E4610A.9000006@alum.rpi.edu>

Christer Enfors wrote:
> I have two files, in the same directory: main.py, and user.py I have the 
> following code in main.py:
>
>    ----main.py----
>    import user
>
>    [snip]
>
>    user_man = user.UserMan()
>    -----end-----
>
> This works without problems.
>
> But then I tried moving user.py to a subdirectory, and adding that 
> directory to Python's module search path, so this is what main.py looks 
> like now:
>
>    ----main.py---
>    import sys
>    sys.path.append("/correct/complete/path/to/subdir")
>
>    import user  # Generates no error message, so it's finding user.py
>
>    [snip]
>
>    user_man = user.UserMan()
>    -----end-----
>
> But now I get an error message for the last line shown above:
>
>    ----start----
>    Traceback (most recent call last):
>      File "./main.py", line 56, in ?
>        driver.boot()
>      File "./main.py", line 34, in boot
>        user_man = user.UserMan()
>    AttributeError: 'module' object has no attribute 'UserMan'
>    -----end-----
>
> What's up with this?
>   
Kent gave the answer for this case. In general use the __file__ 
attribute of the module object to see what was actually imported. In 
your case:

print user.__file__

-- 
Bob Gailer
510-978-4454


From chris.arndt at web.de  Tue Feb 27 18:14:12 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Tue, 27 Feb 2007 18:14:12 +0100
Subject: [Tutor] Group sequence pairwise
In-Reply-To: <3c6718980702261732s7c6db7e0vfa7b2126f8e06005@mail.gmail.com>
References: <3c6718980702261732s7c6db7e0vfa7b2126f8e06005@mail.gmail.com>
Message-ID: <45E466E4.7020506@web.de>

Justin Ezequiel schrieb:
>>>> a = list('asdfg')
>>>> map(None, a[::2], a[1::2])
> [('a', 's'), ('d', 'f'), ('g', None)]
>>>> a = list('asdfgh')
>>>> map(None, a[::2], a[1::2])
> [('a', 's'), ('d', 'f'), ('g', 'h')]

That's clever! Thanks!

Chris

From challman at gmail.com  Tue Feb 27 19:08:56 2007
From: challman at gmail.com (Chris Hallman)
Date: Tue, 27 Feb 2007 13:08:56 -0500
Subject: [Tutor] Telnet and special characters
Message-ID: <9f68812f0702271008m569bb073xb27de9f9b6c3ee11@mail.gmail.com>

Is it possible to send a F1 "character" over a telnet connection? I've
searched but I can't find a solution. I've tried
SendKeys<http://www.rutherfurd.net/python/sendkeys/>and other methods,
but I can't get it to work.

import telnetlib

pswd = "***"
host = "***"
tn = telnetlib.Telnet(host)
tn.read_until("password:", 7)
tn.write(pswd + "\n")
tn.write(chr(27)) # ESC
tn.write(chr(78)) # Shift N
tn.write(chr(25)) # Down arrow
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070227/a90ebd50/attachment.html 

From jsmith at medplus.com  Tue Feb 27 19:21:01 2007
From: jsmith at medplus.com (Smith, Jeff)
Date: Tue, 27 Feb 2007 13:21:01 -0500
Subject: [Tutor] Another list comprehension question
In-Reply-To: <45E348A5.8060906@alum.rpi.edu>
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A02012E27D5@EXCHMAIL01.corp.medplus.com>

-----Original Message-----
From: Bob Gailer [mailto:bgailer at alum.rpi.edu] 
Sent: Monday, February 26, 2007 3:53 PM
To: Smith, Jeff
Cc: tutor at python.org
Subject: Re: [Tutor] Another list comprehension question


>> files = list()
   
>Or just files = []

I tend to prefer the former since it has a more OO feel to it...

Jeff

From jsmith at medplus.com  Tue Feb 27 19:39:15 2007
From: jsmith at medplus.com (Smith, Jeff)
Date: Tue, 27 Feb 2007 13:39:15 -0500
Subject: [Tutor] Another list comprehension question
In-Reply-To: <5e58f2e40702261259k35670666ne7b9a76c77904d61@mail.gmail.com>
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A02012E27EE@EXCHMAIL01.corp.medplus.com>

-----Original Message-----
From: jfouhy at gmail.com [mailto:jfouhy at gmail.com] On Behalf Of John Fouhy
Sent: Monday, February 26, 2007 4:00 PM
To: Smith, Jeff
Cc: tutor at python.org
Subject: Re: [Tutor] Another list comprehension question

On 27/02/07, Smith, Jeff <jsmith at medplus.com> wrote:
>> I'm probably missing something simple here but is there anyway to 
>> accomplish the following with a list comprehension?
>>
>> def get_clists():
>>     return [1, 2, 3]
>>
>> def get_clist(num):
>>     if num == 1:
>>         return ['a', 'b', 'c']
>>     if num == 2:
>>         return ['x', 'y', 'z']
>>     if num == 3:
>>         return ['p', 'q']

>This would be better represented as a dictionary:
>
>>>> clists = { 1:['a', 'b', 'c'],
>...            2:['x', 'y', 'z'],
>...            3:['p', 'q'] }

This was a mockup from a much larger code fragment where the
get_clists() and get_clist() functions are part of an API to a CMS
system which return lists constructed from calls into the CMS system.


>> files = list()
>> for clist in get_clists():
>>     files += get_clist(clist)

>Just a comment -- you could write this as
"files.extend(get_clist(clist))", which would be slightly more
efficient.



>This will do it:
>
>Or [x for k in get_clists() for x in get_clist(k)] using your original
structure.

I realize however that this is probably much less efficient since you
are iterating over the inner list rather than just taking it on in
whole.

Thanks!
Jeff

From Thane.Frivold at nokia.com  Tue Feb 27 20:21:38 2007
From: Thane.Frivold at nokia.com (Thane.Frivold at nokia.com)
Date: Tue, 27 Feb 2007 13:21:38 -0600
Subject: [Tutor] Question about profile.run() and decorators
In-Reply-To: <45E3A4C6.9030809@tds.net>
References: <60A427E0B02CC34B98D22BDCAA25361203F1A1C9@daebe101.NOE.Nokia.com>
	<45E3A4C6.9030809@tds.net>
Message-ID: <60A427E0B02CC34B98D22BDCAA25361203F4C4C0@daebe101.NOE.Nokia.com>

Kent,

	Thank you. 

	That was just the kind of hint I needed. I will make sure to
look for objects inside imported packages in the future too; I missed
the Profile attribute when I first ran dir(profile) looking for
available functions.

	In case you archive the full email threads, I have included a
copy of the working program for reference for future neophytes like
myself...

	Cheers,

- Thane
  
=-=-=

import profile

def myProfileDecorator(function):
  def newFunction(obj, *args, **keywords):
    p = profile.Profile()
    p.runcall(function, *args, **keywords)
    p.print_stats()
  return newFunction

import random

class Foo:
  @myProfileDecorator
  def results(x):
    spin = [x*x for x in range(2000000)]
    print str(x) + " Done"

x = Foo()

print x.results("Almost")

=-=-=

>-----Original Message-----
>From: ext Kent Johnson [mailto:kent37 at tds.net] 
>Sent: Monday, February 26, 2007 7:26 PM
>To: Frivold Thane (Nokia-M/SanFrancisco)
>Cc: tutor at python.org
>Subject: Re: [Tutor] Question about profile.run() and decorators
>
>Thane.Frivold at nokia.com wrote:
>
>> 	Is there a way to construct a string version (suitable to pass
into 
>> profile.run()) from what is available inside a decorator function?
>> I realize that what I am trying to do could probably be done 
>> otherwise, but this arose out of questions and problems possed in a 
>> Python class I just completed, and I am still trying to find my way 
>> around the language. My 'best' attempt is shown below.
>
>Take a look at profile.Profile.runcall() (look at the source 
>for profile, it is not in the docs). This function takes an 
>actual function object as its parameter rather than a string 
>describing the function call.
>
>Kent
>
>> 
>> 	Also, I have limited myself to a function with only 1 parameter,
but 
>> it seems to get even worse if you have 2 or more arguments, since
>> repr() takes only a single argument.
>> 
>> 	BTW, I am using ActiveState Python 2.4.3 on Windows XP.
>> 
>> 	Any and all suggestions or solutions welcomed.
>> 
>> 	Thank you.
>> 
>> 	Cheers,
>> 
>> - Thane
>> 
>> =-=-=
>> 
>> import profile
>> 
>> def myProfileDecorator(function):
>>   def newFunction(obj, *args):
>>     # This attempt does not seem to give an object expression that
can be used
>>     #expression = function.__name__ + '(' + repr(obj) + ',' +
repr(*args) + ')'
>> 
>>     # This attempt generates a NameError exception
>>     expression = function.__name__ + '(' + repr(*args) + ')'
>> 
>>     print 'About to call: profile.run(', expression, ')'
>>     profile.run(expression)
>>   return newFunction
>> 
>> import random
>> 
>> class Foo:
>>   @myProfileDecorator
>>   def results(x):
>>     print str(x) + " Done"
>> 
>> x = Foo()
>> 
>> print x.results("Almost")
>> 
>> =-=-=
>> 
>> 
>> 
>>  
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>> 
>
>

From rabidpoobear at gmail.com  Tue Feb 27 20:56:53 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 27 Feb 2007 13:56:53 -0600
Subject: [Tutor] Telnet and special characters
In-Reply-To: <9f68812f0702271008m569bb073xb27de9f9b6c3ee11@mail.gmail.com>
References: <9f68812f0702271008m569bb073xb27de9f9b6c3ee11@mail.gmail.com>
Message-ID: <45E48D05.3080909@gmail.com>

Chris Hallman wrote:
>
> Is it possible to send a F1 "character" over a telnet connection? I've 
> searched but I can't find a solution. I've tried SendKeys 
> <http://www.rutherfurd.net/python/sendkeys/> and other methods, but I 
> can't get it to work.
>
> import telnetlib
>
> pswd = "***"
> host = "***"
> tn = telnetlib.Telnet(host)
> tn.read_until("password:", 7)
> tn.write(pswd + "\n")
> tn.write(chr(27)) # ESC
> tn.write (chr(78)) # Shift N
> tn.write(chr(25)) # Down arrow
You could have a special sequence of characters that wouldn't normally 
be used, like \1\1\2\3\1\2\4,
and if the server receives this, you can use pyHook or something to 
generate a keypress on the other end.
It seems to me that the function keys would have a value too.
I don't have time to investigate the matter further currently, I'll try 
to look into it later.
-Luke
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From john at fouhy.net  Tue Feb 27 21:41:51 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 28 Feb 2007 09:41:51 +1300
Subject: [Tutor] Another list comprehension question
In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A02012E27EE@EXCHMAIL01.corp.medplus.com>
References: <5e58f2e40702261259k35670666ne7b9a76c77904d61@mail.gmail.com>
	<288A3B43F7B2224D9C8441C9FC5D6A02012E27EE@EXCHMAIL01.corp.medplus.com>
Message-ID: <5e58f2e40702271241n15ed9ebaoc79e771a5cc16bf0@mail.gmail.com>

On 28/02/07, Smith, Jeff <jsmith at medplus.com> wrote:
> I realize however that this is probably much less efficient since you
> are iterating over the inner list rather than just taking it on in
> whole.

Well, you know what they say --- don't guess, profile :-)

Morpork:~ repton$ python -m timeit -s
'lsts=[["a","b","c"],["1","2","3"],["x","y","z"]]' 'flattened = [x for
l in lsts for x in l]'
100000 loops, best of 3: 3.9 usec per loop

Morpork:~ repton$ python -m timeit -s
'lsts=[["a","b","c"],["1","2","3"],["x","y","z"]]' 'flattened = []'
'for lst in lsts:' ' flattened.extend(lst)'
100000 loops, best of 3: 2.61 usec per loop

Hmm, interestingly, my claim that using .extend is more efficient
appears to be false, at least for this example:

Morpork:~ repton$ python -m timeit -s
'lsts=[["a","b","c"],["1","2","3"],["x","y","z"]]' 'flattened = []'
'for lst in lsts:' ' flattened = flattened + lst'
100000 loops, best of 3: 2.56 usec per loop

(not that there's much in it)

-- 
John.

From dejstone at pacbell.net  Tue Feb 27 23:58:20 2007
From: dejstone at pacbell.net (Doug Stone)
Date: Tue, 27 Feb 2007 14:58:20 -0800
Subject: [Tutor] origin of the name python
Message-ID: <036b01c75ac2$c7408c80$8119fea9@deshpzx01>

tutors at python.org:
Hi.  I just started investigating Python and was wondering about the origin
of Python's name.
What did van Rossum have in-mind when he named Python?
 
Thanks,
Doug
 
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070227/168057f0/attachment.html 

From tomdrak at gmail.com  Wed Feb 28 00:14:22 2007
From: tomdrak at gmail.com (tomdrak at gmail.com)
Date: Wed, 28 Feb 2007 00:14:22 +0100
Subject: [Tutor] origin of the name python
In-Reply-To: <036b01c75ac2$c7408c80$8119fea9@deshpzx01>
Message-ID: <45e4bb65.539215a9.36a0.682d@mx.google.com>

Monty Python:
http://en.wikipedia.org/wiki/Monty_python

I believe full story is somewhere on python.org website.

--
Cheers, Tom
http://www.vscripts.net


From deliberatus at verizon.net  Wed Feb 28 05:25:42 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Tue, 27 Feb 2007 23:25:42 -0500
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in your
	notebook?
Message-ID: <45E50446.8060502@verizon.net>

ok, I realized  SOME TIME BACK that to run MANY THINGS in your windows 
computer you need a server in there- and a nice SMALL one if it is going 
to coexist with everything else going on. I found one in python, and 
posted it, and it caused a stirr. Well, I found a LISTING of them, and 
tried all the more promising ones. here is that page:
http://microsoft.toddverbeek.com/phttpd.html

In breif, they are:
xitami - fast, powerful, and the basic version is free.
Omnihttpd - looks good, very configurable, maqny features.
Sambar - many features, more thsan just httpd by a long shot.
Savant - SECURE? in my laptop? well, so it says. MAny other features.
MiniPortal - includes apache and ftp and a web baised control panel.
               possibly this is overkill?
BadBlue - it talks a good fight, but I found it's setup and installation
           confuising. possibly a criticism of it's documentaion, or
           maybe a lack of coffee on my part. give it a look.
Viking - another does everthing server. this includes dns and web mail
          and hosting lists and... jeez louise, will it wask my car?
INframail - from the site: "...Inframail is a combination
             mail/web/ftp/news/gopher server, available in different
             versions with varying capabilities, all of them
             inexpensive." Not free, but cheap.
SompleServerWWW - trivally easy to install. but not easy to bend to my
                   will. I have to reorganise mu directory tree to suit
                   it, as I could not conviently discover a way to tell
                   it where my webpages live.  Maybe studying the manual
                   at length will reveal this, but it is not obvious. Is
                   this a criticism of myself, the program, or the docs?
                   Hmmm...
Serving - not to be found on host site. ???
Falcon- limited, but good if it's limitations do now hamper your
         needed application. it concerned me, so I gave it a miss.
TinyWeb - Ignoring the name thing, it is pretty simple to use, is
           configured witrh command line arguements (old BBS sysop that
           I am, this is nothing new) and the impact on my laptop was-
           none. as in less than 1% cpu usage, memory requirements that
           sound like the guts of my digital watch. And it works. it
           hosts scripts, invokes python, hands off environment
           variables, works with the directory tree the way I set it up,
           and is very sparing with my resources. and it's free. This one
           is a definate looker, check it out and see if it suits your
           needs. A GUI front end is available if you want it. Both are
           $free$.
MacHttp - beats me, I do intel/pc stuff. No opinion.
RobinHood - did not evalulate.
Smallhttps -  VERY good, many features, powerful, web management and
               configuration. $25.free version limits how many
               simultanious connections to 3, and only licenses for 21
               days. Russian author is not ideal for documenting the work
               for english reading eyes, but I managed. It's VERY good,
               and my second choice for my personal server.

So there it is, click to read the page and go from there and see if 
something suits ytour needs and wallet. For now tiny is serving my needs 
with complete satisfaction. I may write a tiddlywiki manual for it as a 
donation to support the project.








-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rabidpoobear at gmail.com  Wed Feb 28 06:52:15 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 27 Feb 2007 23:52:15 -0600
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in
 your	notebook?
In-Reply-To: <45E50446.8060502@verizon.net>
References: <45E50446.8060502@verizon.net>
Message-ID: <45E5188F.7010902@gmail.com>

Kirk Bailey wrote:
> ok, I realized  SOME TIME BACK that to run MANY THINGS in your windows 
> computer you need a server in there- and a nice SMALL one if it is going 
> to coexist with everything else going on.
You need a server for what now?
Web pages?  FTP? SVN?
I can't think of much else.

I run apache and ftp services on my windows machine, and they're 
using... let me check...
4 MB of ram for the FTP server, and 4.6 MB of ram for Apache.  neither 
of these are considered 'lightweight' apps.  Both are fully-featured.  
Neither are listed as using more than 0% CPU. 
My IM client uses 14 MB, my music program uses 32 MB, my browser is 
using 63 MB, and my e-mail client is using 47 MB.
I would consider Apache fairly resource-friendly, compared to these 
other apps.  Not to mention it's used on over 50% of EVERY web server, 
so I'm pretty sure it's reliable.  And I don't see a need to use 
anything else.  If your software asked me to install some obscure web 
server I've never heard of, I would probably cancel the installation and 
forget about it, for fear it would interfere with my already-established 
Apache server.
>  I found one in python, and 
> posted it, and it caused a stirr.
I don't know what you're referring to, maybe it was before I joined the 
list.
>  Well, I found a LISTING of them, and 
> tried all the more promising ones. here is that page:
> http://microsoft.toddverbeek.com/phttpd.html
>   
Can I ask why are you looking into this?
As far as I can tell, the software you're writing (miniwiki) will be 
served from the client's computer directly to the client's web  
browser.  No actual web stuff is necessary, right?
I don't understand why you'd want to make the user have to install 
another webserver to use your program.  You're writing it in Python, why 
not use a Python HTTP server library, and have that included in your 
distribution when you py2exe it?
It seems by far a better solution.

JMO,
-Luke


From deliberatus at verizon.net  Wed Feb 28 07:46:04 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 28 Feb 2007 01:46:04 -0500
Subject: [Tutor] MiniWiki
Message-ID: <45E5252C.1050009@verizon.net>

OK, 1.3.0 is coming along well, and works pretty nice. BUT...

It lives inside my laptop, and I want to be able to duck out and go back 
to the regular webpages I put into it. Remember, I have a server in 
there, tinyweb. So there it is, working well, and I put in a link to 
referr back to localhost:
http://localhost/index.html

And it goes banannas, misprocessing the link construction. BUT, when I 
look it over with a normal link:
http://www.tinylist.org/
It processes fine. hmmm... Not seeing it yet, and I know, it's right 
there in front of me- somewhere...

For any who are intrested, here's a link to the current sourcecode for 
the rendering engine.
http://www.tinylist.org/MW.txt

And if you like a nice simple server for your testing use, tinyweb is a 
dandy. while you configure it from the command line, it is very small 
and low impact on system resources (clock cycles, memory, blab lab la) 
and supports interpeted python scripts well.
http://www.ritlabs.com/tinyweb/

-- 

Salute!
       -Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rikard.bosnjakovic at gmail.com  Wed Feb 28 09:18:22 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 28 Feb 2007 09:18:22 +0100
Subject: [Tutor] origin of the name python
In-Reply-To: <036b01c75ac2$c7408c80$8119fea9@deshpzx01>
References: <036b01c75ac2$c7408c80$8119fea9@deshpzx01>
Message-ID: <d9e88eaf0702280018m3661c598od61a887139027ac4@mail.gmail.com>

On 2/27/07, Doug Stone <dejstone at pacbell.net> wrote:

> Hi.  I just started investigating Python and was wondering about the origin
> of Python's name.
> What did van Rossum have in-mind when he named Python?

http://en.wikipedia.org/wiki/Guido_van_Rossum

About the origin of Python, Van Rossum wrote in 1996:

    Over six years ago, in December 1989, I was looking for a "hobby"
programming project that would keep me occupied during the week around
Christmas. My office ... would be closed, but I had a home computer,
and not much else on my hands. I decided to write an interpreter for
the new scripting language I had been thinking about lately: a
descendant of ABC that would appeal to Unix/C hackers. I chose Python
as a working title for the project, being in a slightly irreverent
mood (and a big fan of Monty Python's Flying Circus).


-- 
- Rikard.

From cbc at unc.edu  Tue Feb 27 21:55:09 2007
From: cbc at unc.edu (Chris Calloway)
Date: Tue, 27 Feb 2007 15:55:09 -0500
Subject: [Tutor] Three days left for Zope3 boot camp registration
Message-ID: <45E49AAD.1010101@unc.edu>

Registration ends Friday:

http://trizpug.org/boot-camp/camp5

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599




From kent37 at tds.net  Wed Feb 28 12:54:59 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Feb 2007 06:54:59 -0500
Subject: [Tutor] MiniWiki
In-Reply-To: <45E5252C.1050009@verizon.net>
References: <45E5252C.1050009@verizon.net>
Message-ID: <45E56D93.5020809@tds.net>

Kirk Bailey wrote:
> OK, 1.3.0 is coming along well, and works pretty nice. BUT...
> 
> It lives inside my laptop, and I want to be able to duck out and go back 
> to the regular webpages I put into it. Remember, I have a server in 
> there, tinyweb. So there it is, working well, and I put in a link to 
> referr back to localhost:
> http://localhost/index.html
> 
> And it goes banannas, misprocessing the link construction. BUT, when I 
> look it over with a normal link:
> http://www.tinylist.org/
> It processes fine. hmmm... Not seeing it yet, and I know, it's right 
> there in front of me- somewhere...

Is that a question? If so, what do you mean by "it goes banannas, 
misprocessing the link construction"? Is this a Python problem or a link 
problem?

Kent

From johan at accesstel.co.za  Wed Feb 28 13:55:33 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Wed, 28 Feb 2007 14:55:33 +0200
Subject: [Tutor] Telnet and special characters
In-Reply-To: <45E48D05.3080909@gmail.com>
Message-ID: <20070228124912.76BBD1675B@mail.accesstel.co.za>

 I have used special characters before in Telnet sessions, but always use
hex characters. i.e.: \x0B for ESC.

Maybe F-keys are some form of internal OS signals and are not send out on
the network connection. In that case, I'm not sure how to send it.

Johan

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Luke Paireepinart
Sent: 27 February 2007 09:57 PM
To: Chris Hallman
Cc: tutor at python.org
Subject: Re: [Tutor] Telnet and special characters

Chris Hallman wrote:
>
> Is it possible to send a F1 "character" over a telnet connection? I've 
> searched but I can't find a solution. I've tried SendKeys 
> <http://www.rutherfurd.net/python/sendkeys/> and other methods, but I 
> can't get it to work.
>
> import telnetlib
>
> pswd = "***"
> host = "***"
> tn = telnetlib.Telnet(host)
> tn.read_until("password:", 7)
> tn.write(pswd + "\n")
> tn.write(chr(27)) # ESC
> tn.write (chr(78)) # Shift N
> tn.write(chr(25)) # Down arrow
You could have a special sequence of characters that wouldn't normally be
used, like \1\1\2\3\1\2\4, and if the server receives this, you can use
pyHook or something to generate a keypress on the other end.
It seems to me that the function keys would have a value too.
I don't have time to investigate the matter further currently, I'll try to
look into it later.
-Luke
>
>
> ----------------------------------------------------------------------
> --
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/698 - Release Date: 2007/02/23
04:39 AM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.446 / Virus Database: 268.18.4/703 - Release Date: 2007/02/26
02:56 PM
 


From dperlman at wisc.edu  Wed Feb 28 15:31:48 2007
From: dperlman at wisc.edu (David Perlman)
Date: Wed, 28 Feb 2007 08:31:48 -0600
Subject: [Tutor] Telnet and special characters
In-Reply-To: <9f68812f0702271008m569bb073xb27de9f9b6c3ee11@mail.gmail.com>
References: <9f68812f0702271008m569bb073xb27de9f9b6c3ee11@mail.gmail.com>
Message-ID: <DF3AA1AA-39EC-4333-A1AF-E2B02AA87E17@wisc.edu>

This question isn't well posed.  There is no such thing as an F1  
"character".

Data is sent over telnet connections as 8-bit bytes.  You can send  
any combination of 8-bit bytes you want by coding them in a number of  
different ways, such as chr(xx) like you wrote below, or '\xnn' or  
whatever suits your fancy.  The reason you are having problems is  
that you don't know what bytes you want to send over the connection.   
If you figure that out, then you will be able to send those bytes  
without any further trouble.

If you're having trouble figuring out what bytes you want to send  
over the connection, you need to take a step back and ask what it is  
you're actually trying to do.  What are you sending the data to?  Are  
you trying to emulate something else that would normally be sending  
the data?  Find the documentation for the sending and/or receiving  
ends, and figure out what combinations of characters, escape  
sequences, whatever, are involved in triggering the behavior that you  
want.  Then you will know what bytes you want to send.

If you are emulating something else on the client end, you could fire  
up the regular client and sniff the connection while you hit whatever  
'F1' key you're interested in, and see what actually gets sent over  
the connection when you do that.

On Feb 27, 2007, at 12:08 PM, Chris Hallman wrote:

>
> Is it possible to send a F1 "character" over a telnet connection?  
> I've searched but I can't find a solution. I've tried SendKeys and  
> other methods, but I can't get it to work.
>
> import telnetlib
>
> pswd = "***"
> host = "***"
> tn = telnetlib.Telnet(host)
> tn.read_until("password:", 7)
> tn.write(pswd + "\n")
> tn.write(chr(27)) # ESC
> tn.write (chr(78)) # Shift N
> tn.write(chr(25)) # Down arrow
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From deliberatus at verizon.net  Wed Feb 28 16:09:42 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 28 Feb 2007 10:09:42 -0500
Subject: [Tutor] MiniWiki
In-Reply-To: <45E56D93.5020809@tds.net>
References: <45E5252C.1050009@verizon.net> <45E56D93.5020809@tds.net>
Message-ID: <45E59B36.6010701@verizon.net>

It's a result problem; I do not see the reason it is doing this. AS I do 
not yet understand it, I cannot say where the problem is. Anyone got an 
idea?

I am posting musings and rumbling about my project so anyone who is 
interested may offer suggestions, or simply follow along for their own 
interest and amusement. Who knows, maybe someone will spark an idea off 
of it and gain something.

Kent Johnson wrote:
> Kirk Bailey wrote:
>> OK, 1.3.0 is coming along well, and works pretty nice. BUT...
>>
>> It lives inside my laptop, and I want to be able to duck out and go 
>> back to the regular webpages I put into it. Remember, I have a server 
>> in there, tinyweb. So there it is, working well, and I put in a link 
>> to referr back to localhost:
>> http://localhost/index.html
>>
>> And it goes banannas, misprocessing the link construction. BUT, when I 
>> look it over with a normal link:
>> http://www.tinylist.org/
>> It processes fine. hmmm... Not seeing it yet, and I know, it's right 
>> there in front of me- somewhere...
> 
> Is that a question? If so, what do you mean by "it goes banannas, 
> misprocessing the link construction"? Is this a Python problem or a link 
> problem?
> 
> Kent
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From nephish at gmail.com  Wed Feb 28 16:45:34 2007
From: nephish at gmail.com (shawn bright)
Date: Wed, 28 Feb 2007 09:45:34 -0600
Subject: [Tutor] question about forwarding mail with poplib
Message-ID: <384c93600702280745y20c48604nbb1ce455ffa121bc@mail.gmail.com>

Hello there all,

i am poplib to retrieve mail from a pop server here on my local machine.
i need to be able to forward every message i get to another email address.
i looked through the poplib page on the reference online but i can't
find anything there to help me out with this. Also, the message has a
64bit encoded attachment.

anyone have a tip on how i should proceed with this ?

thanks.

From tsila.hassine at gmail.com  Wed Feb 28 17:49:41 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Wed, 28 Feb 2007 17:49:41 +0100
Subject: [Tutor] "IOError: decoder jpeg not available"
Message-ID: <da5291e90702280849g2b59ba7ak4fd22633b006d34d@mail.gmail.com>

Dear fellow Pythoneers,

I have recently upgraded to Mac 10.4, and since then this error appears when
trying to manipulate an image (resize it actually),
can anyone help me out ?

thanks!
Tsila
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070228/a365219a/attachment.html 

From singh01 at gmail.com  Wed Feb 28 18:28:14 2007
From: singh01 at gmail.com (Nagendra Singh)
Date: Wed, 28 Feb 2007 12:28:14 -0500
Subject: [Tutor] Running an exe from Python
In-Reply-To: <erv92c$1b8$1@sea.gmane.org>
References: <cd2d0ceb0702221114k4ee09100o40110c21fa094c4b@mail.gmail.com>
	<d9e88eaf0702222138s51c3abdfs113ce9c4952aca81@mail.gmail.com>
	<ermd0f$taq$1@sea.gmane.org>
	<cd2d0ceb0702260848o10b19adfx22d0e5d9292f02a6@mail.gmail.com>
	<erv92c$1b8$1@sea.gmane.org>
Message-ID: <cd2d0ceb0702280928rc42ba16vf8600f86cb3b7b82@mail.gmail.com>

Thanks a lot for all you helps. Alan your tutorial is very helpful But I
have another problem which I will post soon.

On 2/26/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "Nagendra Singh" <singh01 at gmail.com> wrote
>
> > Thanks a lot for all the suggestions. I used the function
> > subprocess.call ( 'c:\abc.exe  c:\data\file1'), but as before
> > the command window opens and closes very fast
> > a value of 1 is displayed. How do I see the results??
>
> The result is 1 which indicates an error. You don't want
> the result you want the outpur, which is a different thing
> entirely! :-)
>
> To get the output you need to access the output stream
> of the process which is usually stdout. The old way to do
> that was with os.popen, but the subprocess module
> provides a new way. The m,odule docs describe how
> to replace popen using subprocess' Popen class.
>
> My tutorial shows an example of the same thing based
> on the odule documentation.
>
> Basically it looks like:
>
> import subprocess
> psout = subprocess.Popen(r'c:\abc.exe c:\data\file1',
> shell=True, stdout=PIPE).stdout
> results = psout.read().split('\n')
> Notice I enclosed the command with a raw string.Otherwise your
> backslashes get treated as escape characters. This might be why you
> are getting error codes back?Another way to avoid that is to use
> forward slashes which Python understands on DOS psout =
> subprocess.Popen('c:/abc.exe c:/data/file1',
> shell=True, stdout=PIPE).stdout
> > I am sorry if I sound dumb.
>
> Nope, just looking for the wrong thing. But you only
> know that after you find out :-)
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> 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/20070228/7be249df/attachment.html 

From flickita at gmail.com  Wed Feb 28 18:49:14 2007
From: flickita at gmail.com (Cecilia Alm)
Date: Wed, 28 Feb 2007 11:49:14 -0600
Subject: [Tutor] Two sys.exit questions
Message-ID: <7a4620dc0702280949h16acae51w207d1fe5ba0bb1d4@mail.gmail.com>

I have two quick questions:

1) Why does sys.exit() not work in a try clause (but it does in the except
clause)?

>>> try:
...    print 1
...    sys.exit(0)
... except:
...    print 2
...    sys.exit(0)
...
1
2
# python exited

2) If opening a file fails in the below 2 cases, sys.exit(message) prints a
message in the except clause before program termination.
    Some use file.close() in the except clause (or in a finally clause). It
seems superflous in the below case of read and write. (?)

        try:
            file = open('myinfile.txt', 'r')
        except IOError:
            sys.exit('Couldn't open myinfile.txt')

        try:
            file = open('myoutfile.txt', 'w')
        except IOError:
            sys.exit('Couldn't open myoutfile.txt')
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070228/96405c6b/attachment-0001.htm 

From paulino1 at sapo.pt  Wed Feb 28 19:01:26 2007
From: paulino1 at sapo.pt (paulino1 at sapo.pt)
Date: Wed, 28 Feb 2007 18:01:26 +0000
Subject: [Tutor] howto filter access to a cgi script
Message-ID: <20070228180126.3octfcevekg0c00o@w8.mail.sapo.pt>

Hi!

I have some python CGI scripts in an intranet, in a windows network, I  
would like to restrict the access to some of those scripts to a list  
of computers in the domain.

How?

Thanks, Paulino

From jason.massey at gmail.com  Wed Feb 28 19:07:06 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Wed, 28 Feb 2007 12:07:06 -0600
Subject: [Tutor] Two sys.exit questions
In-Reply-To: <7a4620dc0702280949h16acae51w207d1fe5ba0bb1d4@mail.gmail.com>
References: <7a4620dc0702280949h16acae51w207d1fe5ba0bb1d4@mail.gmail.com>
Message-ID: <7e3eab2c0702281007v27d4676v44c91c3aaea52f00@mail.gmail.com>

When you call sys.exit() you're raising a SystemExit exception.

>>> help(sys.exit)
Help on built-in function exit in module sys:

exit(...)
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is numeric, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

So that explains why you're falling through to except clause.
You can see the same type of behavior if you manually raise an exception
(ValueError for example) within a try clause

In your example concerning the reading and writing to files, as far as a
close() statement goes you would get this error:
>>> try:
...     i_file = open('doesnt_exit.tmp','r')
... except IOError:
...     i_file.close()
...
Traceback (most recent call last):
  File "<interactive input>", line 4, in ?
NameError: name 'i_file' is not defined
>>>

Since i_file never got defined because the open wasn't successful.

BTW don't use file as a variable since it will mask python's built-in file
object

On 2/28/07, Cecilia Alm <flickita at gmail.com> wrote:
>
> I have two quick questions:
>
> 1) Why does sys.exit() not work in a try clause (but it does in the except
> clause)?
>
> >>> try:
> ...    print 1
> ...    sys.exit(0)
> ... except:
> ...    print 2
> ...    sys.exit(0)
> ...
> 1
> 2
> # python exited
>
> 2) If opening a file fails in the below 2 cases, sys.exit(message) prints
> a message in the except clause before program termination.
>     Some use file.close() in the except clause (or in a finally clause).
> It seems superflous in the below case of read and write. (?)
>
>         try:
>             file = open('myinfile.txt', 'r')
>         except IOError:
>             sys.exit('Couldn't open myinfile.txt')
>
>         try:
>             file = open('myoutfile.txt', 'w')
>         except IOError:
>             sys.exit('Couldn't open myoutfile.txt')
>
>
>
>
>
>
>
> _______________________________________________
> 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/20070228/61c0390d/attachment.htm 

From rabidpoobear at gmail.com  Wed Feb 28 19:07:13 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 28 Feb 2007 12:07:13 -0600
Subject: [Tutor] Two sys.exit questions
In-Reply-To: <7a4620dc0702280949h16acae51w207d1fe5ba0bb1d4@mail.gmail.com>
References: <7a4620dc0702280949h16acae51w207d1fe5ba0bb1d4@mail.gmail.com>
Message-ID: <45E5C4D1.1090408@gmail.com>

Cecilia Alm wrote:
> I have two quick questions:
>
> 1) Why does sys.exit() not work in a try clause (but it does in the 
> except clause)?
sys.exit raises an exception.  That's how it exits program execution.
If you use it in a try block, the exception it raises will have no 
effect because your except clause isn't catching
a particular kind of error, it's catching all errors (including 
"SystemExit" ones)

an example of a sys.exit working in a try block would be something like 
this:

import sys
try:
   f = file('somefile_you_have.txt','r')
   sys.exit(0)

except IOError:
   print "You had an error on file input"


hope that clears some things up for you.
-Luke

From singh01 at gmail.com  Wed Feb 28 19:07:21 2007
From: singh01 at gmail.com (Nagendra Singh)
Date: Wed, 28 Feb 2007 13:07:21 -0500
Subject: [Tutor] Problem with Import
Message-ID: <cd2d0ceb0702281007n3fb09979k1d223863721080f9@mail.gmail.com>

Hi all,

I am running python on Cygwin and I have also installed gdal which is a
raster translator library. When I run the command import gdal, Python gives
me an error :

Python 2.4.3 (#1, May 18 2006, 07:40:45)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import gdal
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.4/site-packages/gdal.py", line 191, in ?
    import _gdal
ImportError: No module named _gdal

The file gdal.py and gdal.pyc are in : /usr/lib/python2.4/site-packages, but
still it gives this error.

Thanks

Singh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070228/917be805/attachment.html 

From kent37 at tds.net  Wed Feb 28 19:42:09 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Feb 2007 13:42:09 -0500
Subject: [Tutor] howto filter access to a cgi script
In-Reply-To: <20070228180126.3octfcevekg0c00o@w8.mail.sapo.pt>
References: <20070228180126.3octfcevekg0c00o@w8.mail.sapo.pt>
Message-ID: <45E5CD01.4030209@tds.net>

paulino1 at sapo.pt wrote:
> Hi!
> 
> I have some python CGI scripts in an intranet, in a windows network, I  
> would like to restrict the access to some of those scripts to a list  
> of computers in the domain.
> 
> How?

Within the CGI I think you can look at the environment variable 
REMOTE_HOST or REMOTE_ADDR.

You could also do this by configuring the web server (e.g. apache) that 
is serving the CGI, or some other method of restricting access to the 
computer running the server.

Kent

From sulfurfff at hotmail.com  Wed Feb 28 20:21:58 2007
From: sulfurfff at hotmail.com (=?iso-8859-1?B?SXNtYWVsIEZhcmbhbiBFc3RyYWRh?=)
Date: Wed, 28 Feb 2007 19:21:58 +0000
Subject: [Tutor] howto call DOM with python
Message-ID: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>

hi there

I was wondering wheter someone knows how to use python to write
a client-side scripts like if it were java, I want to get someting like
this working
<html>
<script type="text/python">
window.alert("python")
</script>
</html>

but nothing happens. I don't know javascript but this code works
if I put javascript instead of python, I've also tried with pythonscript
python-source, etc

hope you can help me, I'm using GNU/Suse, Opera, and Firefox for test

_________________________________________________________________
El mejor destino, con los mejores contenidos http://www.prodigy.msn.com


From rabidpoobear at gmail.com  Wed Feb 28 21:11:51 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 28 Feb 2007 14:11:51 -0600
Subject: [Tutor] Two sys.exit questions
In-Reply-To: <7a4620dc0702281122q307b5e24ted6f160410c796ef@mail.gmail.com>
References: <7a4620dc0702280949h16acae51w207d1fe5ba0bb1d4@mail.gmail.com>	
	<45E5C4D1.1090408@gmail.com>
	<7a4620dc0702281122q307b5e24ted6f160410c796ef@mail.gmail.com>
Message-ID: <45E5E207.2030906@gmail.com>

[snip]
>
> (Although, I'm not sure what you meant by "working" in the below case, 
> since your example doesn't exit the interpreter.)
> [snip]
>
>
>     try:
>        f = file('somefile_you_have.txt','r')
>        sys.exit(0)
>
>     except IOError:
>        print "You had an error on file input"
>
It would if you had a file named 'somefile_you_have.txt' in the same 
working directory as your python interpreter is set to.
If you don't, the f = file( ... ) line will fail to find the file to 
open for input, so it will throw an IOError and print out
"You had an error on file input"
If you do have such a file, the assignment to f will pass successfully, 
sys.exit will throw a SystemExit, and the except block won't catch it 
because it only catches IOErrors.

HTH,
-Luke

P.S. Please use the reply-all button so your replies go to the list and 
not to me.

From jalilsan at gmail.com  Wed Feb 28 21:12:47 2007
From: jalilsan at gmail.com (Jalil)
Date: Wed, 28 Feb 2007 12:12:47 -0800
Subject: [Tutor] Problem with Import
In-Reply-To: <cd2d0ceb0702281007n3fb09979k1d223863721080f9@mail.gmail.com>
References: <cd2d0ceb0702281007n3fb09979k1d223863721080f9@mail.gmail.com>
Message-ID: <5850ed90702281212v44da18b7t945af7698acb79be@mail.gmail.com>

check your python path

On 2/28/07, Nagendra Singh <singh01 at gmail.com> wrote:
>
> Hi all,
>
> I am running python on Cygwin and I have also installed gdal which is a
> raster translator library. When I run the command import gdal, Python gives
> me an error :
>
> Python 2.4.3 (#1, May 18 2006, 07:40:45)
> [GCC 3.3.3 (cygwin special)] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import gdal
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/usr/lib/python2.4/site-packages/gdal.py", line 191, in ?
>     import _gdal
> ImportError: No module named _gdal
>
> The file gdal.py and gdal.pyc are in : /usr/lib/python2.4/site-packages,
> but still it gives this error.
>
> Thanks
>
> Singh
>
>
> _______________________________________________
> 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/20070228/6649f3e6/attachment.html 

From malaclypse2 at gmail.com  Wed Feb 28 21:18:32 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Wed, 28 Feb 2007 15:18:32 -0500
Subject: [Tutor] howto call DOM with python
In-Reply-To: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
References: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
Message-ID: <16651e80702281218g17495edau4dfa991aeecb192b@mail.gmail.com>

On 2/28/07, Ismael Farf?n Estrada <sulfurfff at hotmail.com> wrote:
> I was wondering wheter someone knows how to use python to write
> a client-side scripts like if it were java

I don't think this is possible, at least without creating a
custom-compiled version of Firefox.

There's a little bit of discussion from last year on the python
mailing list here:
http://mail.python.org/pipermail/python-list/2006-November/415805.html

There's some more information available out there if you search for
PyXPCOM or python and nsdom.  If you do end up getting it working, I
would be interested in hearing how it went.

-- 
Jerry

From dperlman at wisc.edu  Wed Feb 28 21:36:12 2007
From: dperlman at wisc.edu (David Perlman)
Date: Wed, 28 Feb 2007 14:36:12 -0600
Subject: [Tutor] Two sys.exit questions
In-Reply-To: <7e3eab2c0702281007v27d4676v44c91c3aaea52f00@mail.gmail.com>
References: <7a4620dc0702280949h16acae51w207d1fe5ba0bb1d4@mail.gmail.com>
	<7e3eab2c0702281007v27d4676v44c91c3aaea52f00@mail.gmail.com>
Message-ID: <04DADCC3-3B54-4428-97C8-D977923C8973@wisc.edu>

If you want to play around with this stuff, you can first import sys,  
and then insert this line in the except clause:
print repr(sys.exc_info())
(or some other way of getting the details out of the returned tuple.)

That will tell you exactly what brought you to the except clause.

On Feb 28, 2007, at 12:07 PM, Jason Massey wrote:

> When you call sys.exit() you're raising a SystemExit exception.
>
> >>> help(sys.exit)
> Help on built-in function exit in module sys:
>
> exit(...)
>     exit([status])
>
>     Exit the interpreter by raising SystemExit(status).
>     If the status is omitted or None, it defaults to zero (i.e.,  
> success).
>     If the status is numeric, it will be used as the system exit  
> status.
>     If it is another kind of object, it will be printed and the system
>     exit status will be one (i.e., failure).
>
> So that explains why you're falling through to except clause.
> You can see the same type of behavior if you manually raise an  
> exception (ValueError for example) within a try clause
>
> In your example concerning the reading and writing to files, as far  
> as a close() statement goes you would get this error:
> >>> try:
> ...     i_file = open('doesnt_exit.tmp','r')
> ... except IOError:
> ...     i_file.close()
> ...
> Traceback (most recent call last):
>   File "<interactive input>", line 4, in ?
> NameError: name 'i_file' is not defined
> >>>
>
> Since i_file never got defined because the open wasn't successful.
>
> BTW don't use file as a variable since it will mask python's built- 
> in file object
>
> On 2/28/07, Cecilia Alm <flickita at gmail.com> wrote:I have two quick  
> questions:
>
> 1) Why does sys.exit() not work in a try clause (but it does in the  
> except clause)?
>
> >>> try:
> ...    print 1
> ...    sys.exit(0)
> ... except:
> ...    print 2
> ...    sys.exit(0)
> ...
> 1
> 2
> # python exited
>
> 2) If opening a file fails in the below 2 cases, sys.exit(message)  
> prints a message in the except clause before program termination.
>     Some use file.close() in the except clause (or in a finally  
> clause). It seems superflous in the below case of read and write. (?)
>
>         try:
>             file = open('myinfile.txt', 'r')
>         except IOError:
>             sys.exit('Couldn't open myinfile.txt')
>
>         try:
>             file = open('myoutfile.txt', 'w')
>         except IOError:
>             sys.exit('Couldn't open myoutfile.txt')
>
>
>
>
>
>
>
> _______________________________________________
> 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

--
-dave----------------------------------------------------------------
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -G?the



From hugonz-lists at h-lab.net  Wed Feb 28 22:37:44 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Wed, 28 Feb 2007 15:37:44 -0600
Subject: [Tutor] "IOError: decoder jpeg not available"
In-Reply-To: <da5291e90702280849g2b59ba7ak4fd22633b006d34d@mail.gmail.com>
References: <da5291e90702280849g2b59ba7ak4fd22633b006d34d@mail.gmail.com>
Message-ID: <45E5F628.8070006@h-lab.net>

Hi,

It looks like there is a capability you don't have installed in your 
image processing lib. but you really give us nothing. Please tell us:

  - Was this working before in any other operating system or python version?
  - What module are you using for working with jpeg?
  - Show us the code that throws this exception, or how you use it..

And maybe we'll have some info to help you out.


Tsila Hassine wrote:
> Dear fellow Pythoneers,
> 
> I have recently upgraded to Mac 10.4, and since then this error appears 
> when trying to manipulate an image (resize it actually),
> can anyone help me out ?
> 

From hugonz-lists at h-lab.net  Wed Feb 28 22:40:59 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Wed, 28 Feb 2007 15:40:59 -0600
Subject: [Tutor] howto call DOM with python
In-Reply-To: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
References: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
Message-ID: <45E5F6EB.30408@h-lab.net>

I too wish it worked. In javascript, it works because the browser has a 
Javascript implementation. There's no stock browser with a Python 
implementation, and I've looked for any client side implementation with 
no success.

Hugo

Ismael Farf?n Estrada wrote:
> hi there
> 
> I was wondering wheter someone knows how to use python to write
> a client-side scripts like if it were java, I want to get someting like
> this working
> <html>
> <script type="text/python">
> window.alert("python")
> </script>
> </html>
> 
> but nothing happens. I don't know javascript but this code works
> if I put javascript instead of python, I've also tried with pythonscript
> python-source, etc
> 
> hope you can help me, I'm using GNU/Suse, Opera, and Firefox for test
> 
> _________________________________________________________________
> El mejor destino, con los mejores contenidos http://www.prodigy.msn.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>