From david at boddie.org.uk  Sat Dec  1 01:04:04 2007
From: david at boddie.org.uk (David Boddie)
Date: Sat, 1 Dec 2007 01:04:04 +0100
Subject: [Tutor] PyQt segfault
Message-ID: <200712010104.05329.david@boddie.org.uk>

On Fri Nov 30 18:56:04 CET 2007, Eric Brunson wrote:

> This comboboxsegfault.py doesn't seem to do anything on my box, but I
> did get an "MemoryError" and a stack trace when I ran cbox.py and
> changed the dropdown menu selection.
> 
> I changed the line:
>         Globals.changedtext = qstring
> 
> to:
>         Globals.changedtext = qstring[:]
> 
> to get a copy of qstring instead of a reference to it, and cbox.py seems
> to execute without problems now.  My guess is that the qstring is being
> disposed of when the dialog is torn down.

Something like that, yes. The internal character data becomes invalid, but
there's still a reference to the QString object.

Here's the original code posted by Tiago:

> class Combobox(QtGui.QDialog):
>     def __init__(self):
>         QtGui.QDialog.__init__(self)
>         self.ui = Ui_Dialog()
>         self.ui.setupUi(self)
>                         
>         self.connect(self.ui.comboBox, QtCore.SIGNAL("activated(QString)"),
>                      self.save)
>         def save(self, qstring):
>             # Here it works:
>             #Aux.mystring = unicode(qstring)
>             Aux.mystring = qstring

The correct way to handle this is commented out: to take a copy of the data,
as you pointed out. This could be done by converting it to a Python unicode
object, as shown, or by copying the QString:

  Aux.mystring = QString(string)

[Off topic, but PyQt-related: You need to explicitly copy value types with
PyQt because the semantics of copying objects with Python are different to
those for copying Qt's value classes in C++. In Python, you just bind an
object to a name, but the equivalent assignment in C++ is basically just
creating an additional reference to the same object.]

David


From matt at mattanddawn.orangehome.co.uk  Sat Dec  1 15:42:23 2007
From: matt at mattanddawn.orangehome.co.uk (Matt Smith)
Date: Sat, 01 Dec 2007 14:42:23 +0000
Subject: [Tutor] Use of sqrt() from math module
Message-ID: <475172CF.1010405@mattanddawn.orangehome.co.uk>

Hi,

I need to find the square root of a number in a program I am writing. I have 
imported the 'math' module so I thought I could just call sqrt(x) but I get an 
error message. Extact from my code and error message below.


import sys, pygame, math

...

     if ypos >= 384 and velocity > 0:
         impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 160)))

...


Traceback (most recent call last):
   File "<stdin>", line 32, in <module>
ValueError: math domain error

This one has me stumped as the usage of the module looks straight forward from 
the documentation. Thanks for looking.

Matt




From matt at mattanddawn.orangehome.co.uk  Sat Dec  1 15:46:27 2007
From: matt at mattanddawn.orangehome.co.uk (Matt Smith)
Date: Sat, 01 Dec 2007 14:46:27 +0000
Subject: [Tutor] Use of sqrt() from math module
In-Reply-To: <475172CF.1010405@mattanddawn.orangehome.co.uk>
References: <475172CF.1010405@mattanddawn.orangehome.co.uk>
Message-ID: <475173C3.8090305@mattanddawn.orangehome.co.uk>

Matt Smith wrote:
> import sys, pygame, math
> 
> ...
> 
>     if ypos >= 384 and velocity > 0:
>         impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 
> 160)))
> 
> ...
> 
> 
> Traceback (most recent call last):
>   File "<stdin>", line 32, in <module>
> ValueError: math domain error

Apologies, the actual error I get when I run the code above is:

Traceback (most recent call last):
   File "<stdin>", line 31, in <module>
NameError: name 'sqrt' is not defined

The error I quoted first was when I tried to call 'math.sqrt(x)'

Matt


From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?=  Sat Dec  1 16:04:15 2007
From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?=)
Date: Sat, 01 Dec 2007 18:04:15 +0300
Subject: [Tutor] Use of sqrt() from math module
In-Reply-To: <475172CF.1010405@mattanddawn.orangehome.co.uk>
References: <475172CF.1010405@mattanddawn.orangehome.co.uk>
Message-ID: <475177EF.4010402@saudi.net.sa>

Matt Smith wrote:
> Hi,
Hi...

> 
> I need to find the square root of a number in a program I am writing. I have 
> imported the 'math' module so I thought I could just call sqrt(x) but I get an 
> error message. Extact from my code and error message below.
> 
> 
> import sys, pygame, math
You import the module "math", not what's _inside_ it!  (This is 
important!  Both ways are okay, but in your case this is important!)

> 
> ...
> 
>      if ypos >= 384 and velocity > 0:
>          impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 160)))
> 
> ...
Where did you get this thing called "sqrt"?  You didn't define a 
function called "sqrt", did you?

What you need is the "sqrt" function (or method) that lives _inside_ the 
"math" module, and you *must* tell that to Python, otherwise it won't 
find it!

To fix your problem, either:
  - Use: "from math import sqrt".  But this will import the "sqrt"
    function only.  If all you need from the "math" module is this
    function/method then this is fine.  (Though, this is generally not
    good practice, since you'll pollute you name space.  The other
    solution is better.)

  - Or in the line that triggers the error, use: "math.sqrt(..." instead.
    By using "math." you tell Python where to find this thing that's
    called "sqrt", which is what you want.

> 
> 
> Traceback (most recent call last):
>    File "<stdin>", line 32, in <module>
> ValueError: math domain error
I see you sent a new message with the actual error which is:

    Traceback (most recent call last):
      File "<stdin>", line 32, in <module>
    ValueError: math domain error

which confirm what I wrote above.


Hope this helps.
Ziyad.

From goldwamh at slu.edu  Sat Dec  1 16:19:54 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Sat, 1 Dec 2007 09:19:54 -0600
Subject: [Tutor] Use of sqrt() from math module
In-Reply-To: <475173C3.8090305@mattanddawn.orangehome.co.uk>
References: <475172CF.1010405@mattanddawn.orangehome.co.uk>
	<475173C3.8090305@mattanddawn.orangehome.co.uk>
Message-ID: <18257.31642.341099.132976@euclid.slu.edu>


Matt,

After using "import math" you will need to use the qualified name
math.sqrt(blah) to call the square root function.   That explains the
NameError when trying to use the unqualified name, sqrt.

As to your first message, the ValueError that you are reporting with
the usage math.sqrt is likely due to an attempt to take the square
root of a negative number (presumably because your (ypos - 384 * 160)
factor is negative.

With regard,
Michael


On Saturday December 1, 2007, Matt Smith wrote: 

>    Matt Smith wrote:
>    > import sys, pygame, math
>    > 
>    > ...
>    > 
>    >     if ypos >= 384 and velocity > 0:
>    >         impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 
>    > 160)))
>    > 
>    > ...
>    > 
>    > 
>    > Traceback (most recent call last):
>    >   File "<stdin>", line 32, in <module>
>    > ValueError: math domain error
>    
>    Apologies, the actual error I get when I run the code above is:
>    
>    Traceback (most recent call last):
>       File "<stdin>", line 31, in <module>
>    NameError: name 'sqrt' is not defined
>    
>    The error I quoted first was when I tried to call 'math.sqrt(x)'
>    
>    Matt
>    
>    _______________________________________________
>    Tutor maillist  -  Tutor at python.org
>    http://mail.python.org/mailman/listinfo/tutor


From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?=  Sat Dec  1 16:07:40 2007
From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?=)
Date: Sat, 01 Dec 2007 18:07:40 +0300
Subject: [Tutor] Use of sqrt() from math module
In-Reply-To: <475173C3.8090305@mattanddawn.orangehome.co.uk>
References: <475172CF.1010405@mattanddawn.orangehome.co.uk>
	<475173C3.8090305@mattanddawn.orangehome.co.uk>
Message-ID: <475178BC.2000409@saudi.net.sa>

Matt Smith wrote:
> 
> Apologies, the actual error I get when I run the code above is:
> 
> Traceback (most recent call last):
>    File "<stdin>", line 31, in <module>
> NameError: name 'sqrt' is not defined
> 
> The error I quoted first was when I tried to call 'math.sqrt(x)'
> 
> Matt
> 
Apologies myself...  I didn't read your whole message.

Frankly, I don't know what's the problem in your program.

Sorry.
Ziyad.

From Pierre.DeWet at BITC.ORG.UK  Sat Dec  1 16:22:50 2007
From: Pierre.DeWet at BITC.ORG.UK (Pierre DeWet)
Date: Sat, 01 Dec 2007 15:22:50 +0000
Subject: [Tutor] Use of sqrt() from math module (Out of office)
Message-ID: <s7517c5a.097@mail.bitc.org.uk>

I will be out of the office until Monday 10 December. If your request is
urgent, please contact the helpdesk at: helpdesk at bitc.org.uk,
alternatively, please dial: 0207 566 8771

Cheers
Pierre

From matt at mattanddawn.orangehome.co.uk  Sat Dec  1 16:46:03 2007
From: matt at mattanddawn.orangehome.co.uk (Matt Smith)
Date: Sat, 01 Dec 2007 15:46:03 +0000
Subject: [Tutor] Use of sqrt() from math module
In-Reply-To: <18257.31642.341099.132976@euclid.slu.edu>
References: <475172CF.1010405@mattanddawn.orangehome.co.uk>	<475173C3.8090305@mattanddawn.orangehome.co.uk>
	<18257.31642.341099.132976@euclid.slu.edu>
Message-ID: <475181BB.8030309@mattanddawn.orangehome.co.uk>

Michael H.Goldwasser wrote:
> After using "import math" you will need to use the qualified name
> math.sqrt(blah) to call the square root function.   That explains the
> NameError when trying to use the unqualified name, sqrt.
> 
> As to your first message, the ValueError that you are reporting with
> the usage math.sqrt is likely due to an attempt to take the square
> root of a negative number (presumably because your (ypos - 384 * 160)
> factor is negative.

Thanks Michael and Ziyad, it seems I just had my brackets in the wrong place 
leading to trying to square root a number less than 0.

Matt


From tiagosaboga at terra.com.br  Sat Dec  1 19:12:01 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Sat, 1 Dec 2007 16:12:01 -0200
Subject: [Tutor] PyQt segfault
In-Reply-To: <200712010104.05329.david@boddie.org.uk>
References: <200712010104.05329.david@boddie.org.uk>
Message-ID: <20071201181201.GA5220@localdomain>

On Sat, Dec 01, 2007 at 01:04:04AM +0100, David Boddie wrote:
> Something like that, yes. The internal character data becomes invalid, but
> there's still a reference to the QString object.
> 
> Here's the original code posted by Tiago:
> 
> > class Combobox(QtGui.QDialog):
> >     def __init__(self):
> >         QtGui.QDialog.__init__(self)
> >         self.ui = Ui_Dialog()
> >         self.ui.setupUi(self)
> >                         
> >         self.connect(self.ui.comboBox, QtCore.SIGNAL("activated(QString)"),
> >                      self.save)
> >         def save(self, qstring):
> >             # Here it works:
> >             #Aux.mystring = unicode(qstring)
> >             Aux.mystring = qstring
> 
> The correct way to handle this is commented out: to take a copy of the data,
> as you pointed out. This could be done by converting it to a Python unicode
> object, as shown, or by copying the QString:
> 
>   Aux.mystring = QString(string)
>
> [Off topic, but PyQt-related: You need to explicitly copy value types with
> PyQt because the semantics of copying objects with Python are different to
> those for copying Qt's value classes in C++. In Python, you just bind an
> object to a name, but the equivalent assignment in C++ is basically just
> creating an additional reference to the same object.]

If I understand that correctly, my Aux.mystring is pointing to the
same object passed by QtCore.SIGNAL, which is being garbage-collected?
But the reference in Aux.mystring should not be enough to keep the
object around?

Thanks,

Tiago.

From mwalsh at groktech.org  Sun Dec  2 06:37:39 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sat, 01 Dec 2007 23:37:39 -0600
Subject: [Tutor] Selecting a browser
In-Reply-To: <47500600.3050204@bigfoot.com>
References: <47500600.3050204@bigfoot.com>
Message-ID: <475244A3.10406@groktech.org>

Ricardo Ar?oz wrote:
> Hi, I've checked webbrowser module and so far I find no way of selecting
> a browser other than the default one. Say I want certain places opened
> with IE and others with Mozilla, and I don't want to mess with the
> user's setting of the default browser. Any tips?
> TIA

I think one would normally use the form webbrowser.get('firefox'), on
unix systems. But if I understand correctly, the "problem" with the
webbrowser module on windows (and perhaps it is similar on a mac) is
that unless the program can be found on your system PATH, only a generic
'windows-default' browser class is registered, which uses os.startfile,
releasing control to the os, and serves to open the url in the user's
default browser.

If you're determined to use the webbrowser module on windows, you might
be able to do something like this:

import webbrowser

ffcommand = "c:/program files/mozilla firefox/firefox.exe %s &"
ff = webbrowser.get(ffcommand)
ff.open("http://www.example.com")

iecommand = "c:/program files/internet explorer/iexplore.exe %s &"
ie = webbrowser.get(iecommand)
ie.open("http://www.example.com")

I suppose you could also register them manually for later use with the
webbrowser.get(browser_name) form.

webbrowser.register('firefox', None, ff)
webbrowser.get('firefox').open('http://example.com')

Personally, I would probably just cut out the middle module and use
subprocess.Popen to start the browser, after checking if it is installed
(with os.path.isfile, or similar) -- which seems to be, more or less,
what the webbrowser module does if it finds one of the predefined
browsers on your system PATH. Something like this (pseudo-code):

browser = 'c:/program files/mozilla firefox/firefox.exe'

if os.path.isfile(browser):
    p = subprocess.Popen([browser, 'http://www.example.com'])
        # if you want to wait for the browser to
        # close before continuing use p.wait() here
else:
    ... web browser not found ...

For dispatching based on site (url, or some other criteria), one idea
would be to wrap something like the above in a function which accepts
the web browser program path as an argument, and then pass the function
a path appropriate for the given criteria. Here is another (untested)
example to demonstrate:

import subprocess
import urlparse
import sys, os

FFPATH = 'c:/program files/mozilla firefox/firefox.exe'
IEPATH = 'c:/program files/internet explorer/iexplore.exe'

IESITES = ['microsoft.com', 'www.microsoft.com']

def launch(url, browser, wait=False):
    if os.path.isfile(browser):
        p = subprocess.Popen([browser, url])
        if wait:
            p.wait()
    else:
        print 'Invalid browser.'

def main(url):
    # pick browser path by domain name
    netloc = urlparse.urlparse(url)[1]
    if netloc in IESITES:
        launch(url, IEPATH)
    else:
        launch(url, FFPATH)

if __name__ == '__main__':
    if sys.argv[1:]:
        main(sys.argv[1])
    else:
        print 'Not enough arguments.'

In theory, if you run this script from a console on windows with any
microsoft.com url as an argument, it should open in IE -- where all
others open in firefox. Really rough, but I hope it helps.

Regards,
Marty


From hunter92383 at gmail.com  Sun Dec  2 16:16:11 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Sun, 2 Dec 2007 23:16:11 +0800
Subject: [Tutor] windows api
Message-ID: <674d5ce60712020716k673321b2hd32942813d1a0680@mail.gmail.com>

this code uses windows api, but where do I find documentation about how to
use them?



import time
import ImageGrab # Part of PIL
from ctypes import *


#time.sleep(5)


# Load up the Win32 APIs we need to use.
class RECT(Structure):
    _fields_ = [
    ('left', c_ulong),
    ('top', c_ulong),
    ('right', c_ulong),
    ('bottom', c_ulong)
    ]


# time.sleep(2)

GetForegroundWindow = windll.user32.GetForegroundWindow
GetWindowRect = windll.user32.GetWindowRect

# Grab the foreground window's screen rectangle.
rect = RECT()
foreground_window = GetForegroundWindow()
GetWindowRect(foreground_window, byref(rect))
image = ImageGrab.grab((rect.left, rect.top, rect.right, rect.bottom))

# Save the screenshot as a BMP.
image.save("C:\projects\screenshot.bmp")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071202/bbe9a76d/attachment.htm 

From hunter92383 at gmail.com  Sun Dec  2 16:34:40 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Sun, 2 Dec 2007 23:34:40 +0800
Subject: [Tutor] windows api (Out of office)
In-Reply-To: <s752cf2c.073@mail.bitc.org.uk>
References: <s752cf2c.073@mail.bitc.org.uk>
Message-ID: <674d5ce60712020734n7d6675d7h162ee202ba68927b@mail.gmail.com>

On Dec 2, 2007 11:28 PM, Pierre DeWet <Pierre.DeWet at bitc.org.uk> wrote:

> I will be out of the office until Monday 10 December. If your request is
> urgent, please contact the helpdesk at: helpdesk at bitc.org.uk,
> alternatively, please dial: 0207 566 8771
>
> Cheers
> Pierre
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071202/801e3778/attachment.htm 

From bgailer at alum.rpi.edu  Sun Dec  2 16:36:37 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sun, 02 Dec 2007 10:36:37 -0500
Subject: [Tutor] windows api
In-Reply-To: <674d5ce60712020716k673321b2hd32942813d1a0680@mail.gmail.com>
References: <674d5ce60712020716k673321b2hd32942813d1a0680@mail.gmail.com>
Message-ID: <4752D105.5070102@alum.rpi.edu>

elis aeris wrote:
> this code uses windows api, but where do I find documentation about 
> how to use them?
Hmm - looks like something from Experts Exchange.

If you are asking for the Windows API Reference, try:

http://msdn2.microsoft.com/en-us/library/aa383749.aspx

ctypes is a Python module that wraps the api calls
>
>
>
> import time
> import ImageGrab # Part of PIL
> from ctypes import *
>
>
> #time.sleep(5)
>
>
> # Load up the Win32 APIs we need to use.
> class RECT(Structure):
>     _fields_ = [
>     ('left', c_ulong),
>     ('top', c_ulong),
>     ('right', c_ulong),
>     ('bottom', c_ulong)
>     ]
>
>
> # time.sleep(2)
>
> GetForegroundWindow = windll.user32.GetForegroundWindow
> GetWindowRect = windll.user32.GetWindowRect
>
> # Grab the foreground window's screen rectangle.
> rect = RECT()
> foreground_window = GetForegroundWindow()
> GetWindowRect(foreground_window, byref(rect))
> image = ImageGrab.grab((rect.left, rect.top, rect.right, rect.bottom))
>
> # Save the screenshot as a BMP.
> image.save("C:\projects\screenshot.bmp")
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From dkuhlman at rexx.com  Sun Dec  2 18:13:06 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 2 Dec 2007 09:13:06 -0800
Subject: [Tutor] Indentation Issue and Blind People
In-Reply-To: <7c8c39801d5b1fd60aab09ef137ac4f9@well.com>
References: <OF6F547C55.EC5E5707-ON852573A3.0067A087-852573A3.00683D63@highmark.com>
	<7c8c39801d5b1fd60aab09ef137ac4f9@well.com>
Message-ID: <20071202171306.GA90709@cutter.rexx.com>

On Fri, Nov 30, 2007 at 11:34:05AM -0800, jim stockford wrote:
> 
>     you might consider keeping your code at two
> spaces and when/if the need arises to share
> your code, write a little filter program that
> translates the two-space indents to four.
>     very interesting idea to play piano notes.
> how'd you do that?

Tools for this already exist.  On Linux/UNIX, they might look like
the following:

  Convert from 2 space indents into 4 space indents:
    $ cat oldfile.py | unexpand -t 2 | expand -t 4 > newfile.py

  Convert from 4 space indents into 2 space indents:
    $ cat oldfile.py | unexpand -t 4 | expand -t 2 > newfile.py

If you are on MS Windows, I believe that you can get replacements
for the above tools here:

    http://unxutils.sourceforge.net/

Also look at scripts contained in the Tools/scripts/ directory of
the Python source code distribution.  In particular, these may be of
interest: reindent.py and tabify.py.  And, for those who feel that
they must have some marker at the end of a block (in addition to an
"out-dent"), look at Tools/scripts/pindent.py.

Dave

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

From david at boddie.org.uk  Sun Dec  2 18:17:45 2007
From: david at boddie.org.uk (David Boddie)
Date: Sun, 2 Dec 2007 18:17:45 +0100
Subject: [Tutor] PyQt segfault
Message-ID: <200712021817.46386.david@boddie.org.uk>

On Sat Dec 1 19:12:01 CET 2007, Tiago Saboga wrote:

> If I understand that correctly, my Aux.mystring is pointing to the
> same object passed by QtCore.SIGNAL, which is being garbage-collected?
> But the reference in Aux.mystring should not be enough to keep the
> object around?

I think PyQt would have to copy the QString internally to do this, and
maybe it only copies a pointer to the QString. You would need to ask this
question on the PyQt mailing list to get an accurate answer to this
question; it's located here:

  http://www.riverbankcomputing.com/mailman/listinfo/pyqt

If you're reluctant to join another mailing list just to ask one question
then I can ask it on your behalf. Let me know if would prefer that.

David



From hunter92383 at gmail.com  Sun Dec  2 21:14:53 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Mon, 3 Dec 2007 04:14:53 +0800
Subject: [Tutor] windows api
In-Reply-To: <4752D105.5070102@alum.rpi.edu>
References: <674d5ce60712020716k673321b2hd32942813d1a0680@mail.gmail.com>
	<4752D105.5070102@alum.rpi.edu>
Message-ID: <674d5ce60712021214x39a1a132n2b21af5800985079@mail.gmail.com>

i know that site, i program in c++ on windows.

however, the syntax in different. how do I find out python's way of using
it?



On Dec 2, 2007 11:36 PM, bob gailer <bgailer at alum.rpi.edu> wrote:

> elis aeris wrote:
> > this code uses windows api, but where do I find documentation about
> > how to use them?
> Hmm - looks like something from Experts Exchange.
>
> If you are asking for the Windows API Reference, try:
>
> http://msdn2.microsoft.com/en-us/library/aa383749.aspx
>
> ctypes is a Python module that wraps the api calls
> >
> >
> >
> > import time
> > import ImageGrab # Part of PIL
> > from ctypes import *
> >
> >
> > #time.sleep(5)
> >
> >
> > # Load up the Win32 APIs we need to use.
> > class RECT(Structure):
> >     _fields_ = [
> >     ('left', c_ulong),
> >     ('top', c_ulong),
> >     ('right', c_ulong),
> >     ('bottom', c_ulong)
> >     ]
> >
> >
> > # time.sleep(2)
> >
> > GetForegroundWindow = windll.user32.GetForegroundWindow
> > GetWindowRect = windll.user32.GetWindowRect
> >
> > # Grab the foreground window's screen rectangle.
> > rect = RECT()
> > foreground_window = GetForegroundWindow()
> > GetWindowRect(foreground_window, byref(rect))
> > image = ImageGrab.grab((rect.left, rect.top, rect.right, rect.bottom))
> >
> > # Save the screenshot as a BMP.
> > image.save("C:\projects\screenshot.bmp")
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > 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/20071203/86a48f50/attachment.htm 

From bgailer at alum.rpi.edu  Sun Dec  2 21:43:07 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sun, 02 Dec 2007 15:43:07 -0500
Subject: [Tutor] windows api
In-Reply-To: <674d5ce60712021214x39a1a132n2b21af5800985079@mail.gmail.com>
References: <674d5ce60712020716k673321b2hd32942813d1a0680@mail.gmail.com>	
	<4752D105.5070102@alum.rpi.edu>
	<674d5ce60712021214x39a1a132n2b21af5800985079@mail.gmail.com>
Message-ID: <475318DB.10306@alum.rpi.edu>

elis aeris wrote:
> i know that site, i program in c++ on windows.
>
> however, the syntax in different. how do I find out python's way of 
> using it?
This is a ctypes question; See

http://python.net/crew/theller/ctypes/

especially the Documentation links.

From crackeur at comcast.net  Sun Dec  2 21:40:35 2007
From: crackeur at comcast.net (jimmy Zhang)
Date: Sun, 2 Dec 2007 12:40:35 -0800
Subject: [Tutor]  ElementTree - reading large XML files as file handles
Message-ID: <000901c83523$971878b0$0402a8c0@your55e5f9e3d2>

I think you may find vtd-xml (http://vtd-xml.sf.net) useful, it has Java, C and C# version
available. so you may have to do it in a different language other than Java


Dear tutors, 

I use ElementTree for XML works. I have a 1.3GB file
to parse. 


I takes a lot of time to open my input XML file. 

Is that because of my hardware limitation or am I
using a blunt method to load the file.

my computer config:
Inte(R)
Pentium(R)4 CPU 2.80GHz
2.79GHz, 0.99GB of RAM

from elementtree import ElementTree
myfile = open('myXML.out','r')

Do you suggest any tip to circumvent the file opening
problem. 

thanks
Srini

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071202/6e664296/attachment.htm 

From varsha.purohit at gmail.com  Mon Dec  3 01:29:07 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 2 Dec 2007 16:29:07 -0800
Subject: [Tutor] [wxPython-users] Dynamically loading images on the panel of
	GUI
Message-ID: <c2157c790712021629m41750a41p158d9791b550fc03@mail.gmail.com>

hello everyone,
        i made a small applicatin where i need to display an image on a
panel. and then when i press the read button it should read another image
and display it on the same panel. Its working but i have to press the read
button two times then only its working....

import wx
import os

APP_SIZE_X = 700
APP_SIZE_Y = 300


class MainWindow(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None,-1,"Agent-Based Model of Residential
Development", size = (APP_SIZE_X, APP_SIZE_Y))

        self.panel = wx.Panel(self,-1)
        self.imageFile = "r10001t0.asc.jpg"  # provide a diff file name in
same directory/path
        self.bmp = wx.Image(self.imageFile,wx.BITMAP_TYPE_JPEG
).ConvertToBitmap()
        wx.StaticBitmap(self.panel, -1, self.bmp, (20,20), (80,120))

        button42 = wx.Button(self.panel, -1, "Read", pos=(240,20))
        self.Bind(wx.EVT_BUTTON, self.OnRead,button42)

    def OnRead(self,event):
        self.imageFile1="DSCN3378.jpg" # you have to provide a diff image
file name
        self.bmp = wx.Image(self.imageFile1,wx.BITMAP_TYPE_JPEG
).ConvertToBitmap()
        wx.StaticBitmap(self.panel, -1, self.bmp, (20,20), (80,120))


app = wx.PySimpleApp()
MainWindow().Show()
app.MainLoop()

Load two different jpeg images.
-- 
Varsha
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071202/68045017/attachment-0001.htm 

From varsha.purohit at gmail.com  Mon Dec  3 02:20:01 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 2 Dec 2007 17:20:01 -0800
Subject: [Tutor] [wxPython-users] Dynamically loading images on the
	panel of GUI
In-Reply-To: <c2157c790712021629m41750a41p158d9791b550fc03@mail.gmail.com>
References: <c2157c790712021629m41750a41p158d9791b550fc03@mail.gmail.com>
Message-ID: <c2157c790712021720y6bd4fd09u373b36a21f610515@mail.gmail.com>

This problem is getting solved if i use the Refresh function in the button
handler. But I have a function where i am generating Jpeg images dynamically
in a separate script. And i need to load these images on GUI as soon as they
start generating. They have common names like xyz1.jpeg and xyz2.jpeg. And i
need to start loading images one after another on the gui panel when they
are created. these images are created one after another with a particular
time delay(not constant). So i have to check when they are created, and i
should load them on gui. So how should i communicate to the gui that image
has been created and it should load the image ?


On Dec 2, 2007 4:29 PM, Varsha Purohit <varsha.purohit at gmail.com> wrote:

> hello everyone,
>         i made a small applicatin where i need to display an image on a
> panel. and then when i press the read button it should read another image
> and display it on the same panel. Its working but i have to press the read
> button two times then only its working....
>
> import wx
> import os
>
> APP_SIZE_X = 700
> APP_SIZE_Y = 300
>
>
> class MainWindow(wx.Frame):
>     def __init__(self):
>         wx.Frame.__init__(self,None,-1,"Agent-Based Model of Residential
> Development", size = (APP_SIZE_X, APP_SIZE_Y))
>
>         self.panel = wx.Panel(self,-1)
>         self.imageFile = "r10001t0.asc.jpg"  # provide a diff file name in
> same directory/path
>         self.bmp = wx.Image(self.imageFile,wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
>         wx.StaticBitmap(self.panel, -1, self.bmp, (20,20), (80,120))
>
>         button42 = wx.Button(self.panel, -1, "Read", pos=(240,20))
>         self.Bind(wx.EVT_BUTTON, self.OnRead ,button42)
>
>     def OnRead(self,event):
>         self.imageFile1="DSCN3378.jpg" # you have to provide a diff image
> file name
>         self.bmp = wx.Image(self.imageFile1,wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
>
>         self.obj = wx.StaticBitmap(self.panel, -1, self.bmp, (20,20),
> (80,120))
>         self.obj.Refresh()
>
> app = wx.PySimpleApp()
> MainWindow().Show()
> app.MainLoop()
>
> Load two different jpeg images.
> --
> Varsha
>
>


-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071202/07f98c3e/attachment.htm 

From varsha.purohit at gmail.com  Mon Dec  3 02:57:01 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 2 Dec 2007 17:57:01 -0800
Subject: [Tutor] [wxPython-users] passing file name from one script to the
	GUI class
Message-ID: <c2157c790712021757r5b01a569ucd1947d680ddd371@mail.gmail.com>

hello All,
     I am attaching two scripts. One is readfile.py which is a gui script
where there is a image display panel and a button. Now what i want is when i
click on the button, then it should call a function which is there in second
script clases_calling.py which basically passes the second image file name
to the readfile and it should call imagetobit function of the gui script and
display the passed imagefile name. I am getting runtime errors....

thanks
-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071202/3ef25e3f/attachment.htm 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: clases_calling.py
Url: http://mail.python.org/pipermail/tutor/attachments/20071202/3ef25e3f/attachment.txt 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: readfile.py
Url: http://mail.python.org/pipermail/tutor/attachments/20071202/3ef25e3f/attachment-0001.txt 

From ricaraoz at gmail.com  Mon Dec  3 11:57:21 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 03 Dec 2007 07:57:21 -0300
Subject: [Tutor] Indentation Issue and Blind People
In-Reply-To: <7c8c39801d5b1fd60aab09ef137ac4f9@well.com>
References: <OF6F547C55.EC5E5707-ON852573A3.0067A087-852573A3.00683D63@highmark.com>
	<7c8c39801d5b1fd60aab09ef137ac4f9@well.com>
Message-ID: <4753E111.7090805@bigfoot.com>

jim stockford wrote:
>     you might consider keeping your code at two
> spaces and when/if the need arises to share
> your code, write a little filter program that
> translates the two-space indents to four.
>     very interesting idea to play piano notes.
> how'd you do that?
> 

Why not just use Tabs. Just one character, might be easy on Braille
(know nothing about it), and almost every editor will convert from tabs
to any quantity of spaces you require. Just modify your program to play
the piano notes on tabs and you're done.

> 
> On Nov 30, 2007, at 10:58 AM, james.homme at highmark.com wrote:
> 
>> Hi,
>> I am just getting started with Python, as in learning the syntax for 
>> basic
>> statements and how to write functions and all. Here is my question.
>> Usually, if you are a person who is blind, you run the risk of having
>> trouble keeping your code indented properly. There are ways to do it, 
>> but
>> they are often time-consuming. Can I get a program that I can use that 
>> will
>> take my Python code as input and make sure it is indented properly? Or,
>> does Python let you write code, compile it, and indent it later? For 
>> anyone
>> who may be interested, I have created a scheme for my screen reader 
>> that
>> plays piano notes at indentations of two space increments. I made the 
>> code
>> indent that way because four spaces is a lot to have on a braille 
>> display.
>> If four spaces is more acceptable, I could globally replace two spaces 
>> with
>> four.
>>
>> Thanks.
>>
>> Jim

From ricaraoz at gmail.com  Mon Dec  3 11:59:18 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 03 Dec 2007 07:59:18 -0300
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <Pine.LNX.4.63.0711301433050.3190@cs.wpi.edu>
References: <200711300817.38828.tim@johnsons-web.com>
	<Pine.LNX.4.63.0711301433050.3190@cs.wpi.edu>
Message-ID: <4753E186.50705@bigfoot.com>

Danny Yoo wrote:
>> Hello:
>> I'm seeing some strange behavior with lstrip operating
>> on string representations of *nix-style file paths
>> Example:
>>>>> s = '/home/test/'
>>>>> s1 = s.lstrip('/home')
>>>>> s1
>> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
>> Any comments or corrective measures are welcome
> 
> 
> 
> Hi Tim,
> 
> Here's another example to help you see what's going on:
> 
> ##########################
>>>> s = '/home/test/'
>>>> s1 = s.lstrip('/ehmo')
>>>> s1
> 'test/'
> ##########################
> 
> Take a closer look at the documentation of lstrip, and you should see that 
> what it takes in isn't treated as a prefix: rather, it'll be treated as a 
> set of characters.
> 

But then the real bug is why does it not strip the trailing '/' in
'test/' or the 'e' that is in your set?




From aditya.n.lal at gmail.com  Mon Dec  3 12:15:21 2007
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Mon, 3 Dec 2007 16:45:21 +0530
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <4753E186.50705@bigfoot.com>
References: <200711300817.38828.tim@johnsons-web.com>
	<Pine.LNX.4.63.0711301433050.3190@cs.wpi.edu>
	<4753E186.50705@bigfoot.com>
Message-ID: <5df213700712030315g432adf7bkf064a43080bac83a@mail.gmail.com>

On Dec 3, 2007 4:29 PM, Ricardo Ar?oz <ricaraoz at gmail.com> wrote:

> Danny Yoo wrote:
> >> Hello:
> >> I'm seeing some strange behavior with lstrip operating
> >> on string representations of *nix-style file paths
> >> Example:
> >>>>> s = '/home/test/'
> >>>>> s1 = s.lstrip('/home')
> >>>>> s1
> >> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
> >> Any comments or corrective measures are welcome
> >
> >
> >
> > Hi Tim,
> >
> > Here's another example to help you see what's going on:
> >
> > ##########################
> >>>> s = '/home/test/'
> >>>> s1 = s.lstrip('/ehmo')
> >>>> s1
> > 'test/'
> > ##########################
> >
> > Take a closer look at the documentation of lstrip, and you should see
> that
> > what it takes in isn't treated as a prefix: rather, it'll be treated as
> a
> > set of characters.
> >
>
> But then the real bug is why does it not strip the trailing '/' in
> 'test/' or the 'e' that is in your set?
>
>
Thats because you called lstrip() and not strip() which will strip only from
left side.

-- 
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071203/2423d5b0/attachment.htm 

From brunson at brunson.com  Mon Dec  3 14:53:41 2007
From: brunson at brunson.com (Eric Brunson)
Date: Mon, 03 Dec 2007 06:53:41 -0700
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <4753E186.50705@bigfoot.com>
References: <200711300817.38828.tim@johnsons-web.com>	<Pine.LNX.4.63.0711301433050.3190@cs.wpi.edu>
	<4753E186.50705@bigfoot.com>
Message-ID: <47540A65.9040402@brunson.com>

Ricardo Ar?oz wrote:
> Danny Yoo wrote:
>   
>>> Hello:
>>> I'm seeing some strange behavior with lstrip operating
>>> on string representations of *nix-style file paths
>>> Example:
>>>       
>>>>>> s = '/home/test/'
>>>>>> s1 = s.lstrip('/home')
>>>>>> s1
>>>>>>             
>>> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
>>> Any comments or corrective measures are welcome
>>>       
>>
>> Hi Tim,
>>
>> Here's another example to help you see what's going on:
>>
>> ##########################
>>     
>>>>> s = '/home/test/'
>>>>> s1 = s.lstrip('/ehmo')
>>>>> s1
>>>>>           
>> 'test/'
>> ##########################
>>
>> Take a closer look at the documentation of lstrip, and you should see that 
>> what it takes in isn't treated as a prefix: rather, it'll be treated as a 
>> set of characters.
>>
>>     
>
> But then the real bug is why does it not strip the trailing '/' in
> 'test/' or the 'e' that is in your set?
>
>   
Because it's lstrip(), the "L" meaning "left".  Not strip() or rstrip().



From li_grim at yahoo.co.uk  Mon Dec  3 19:53:36 2007
From: li_grim at yahoo.co.uk (Andrew Critchley)
Date: Mon, 3 Dec 2007 18:53:36 +0000 (GMT)
Subject: [Tutor] help
Message-ID: <346688.95690.qm@web25609.mail.ukl.yahoo.com>

I recently downloaded the newer version of python, the 2.5.1 one, and when ever i try to make an input what ever i type into the brackets appears on the next line and when i try to add the next line it carries on from the input,This is what happens:

I type this down:

# Area calculation program

>>>print ?Welcome to the Area calculation program?
>>>print ???????????????
>>>print

>>># Print out the menu:
>>>print ?Please select a shape:?
>>>print ?1  Rectangle?
>>>print ?2  Circle?

>>># Get the user?s choice:
shape = input(?>30 ?)
>30 (and then this line appears)
(here i should type "# Calculate the area:" but it carries on from the above line and when i press enter i encunter an error and it all goes wrong)
please help me with this problem.


      __________________________________________________________
Sent from Yahoo! - the World's favourite mail http://uk.mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071203/46e02a4a/attachment.htm 

From janos.juhasz at VELUX.com  Mon Dec  3 20:43:48 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Mon, 3 Dec 2007 20:43:48 +0100
Subject: [Tutor] multithread question
Message-ID: <OFFE90598E.B92C3D3C-ONC12573A6.0069F04F-C12573A6.006C60E8@velux.com>

Dear Tutors,

I have a multithread python service on a windows server,
that brekas down sometimes.
It is a service, that runs on a server and listen on the 9100
tcp port on three IP addresses, just as three jetdirect devices.
It listens as a virtual printer, captures the content of the 
print jobs and makes local backups from them. It also creates
a bat file, that can be used to copy the captured files to the
real printers via nc.




I feel that the problem is somewhere on the write_files process.
The tree threads feeds the queues paralelly, and the manger.write_files()
is responsible to pick the first ones and write them into local files.
I have no got any idea, how may I controll to pick up them only once.
I am affraid that, this function is called more times from different 
threads
in the same time, and it could stop that thread.


I have tried to place a try except into the threads itself, but 
it made it absolutly unstable. 
It was funny as it worked absolutly well in service debug mode
and stoped allways started in service mode, anyway.


I am also interested about that,
where should I place the try except blocks in the thread.



Yours sincerely,
______________________________
Janos Juhasz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071203/869f002a/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: VirtualPrinterService.py
Type: application/octet-stream
Size: 7427 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20071203/869f002a/attachment.obj 

From tim at johnsons-web.com  Mon Dec  3 23:16:37 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Mon, 3 Dec 2007 13:16:37 -0900
Subject: [Tutor] Problems with List Server?
Message-ID: <200712031316.37287.tim@johnsons-web.com>

I appear to be having a weird problem with the List Server.
At first, email sent to this address did not appear at
all.
After contacting the ML maintainers only one email from
me to this address go through. When I replied to the
thread which the email started, it was not delivered. 

This is a very frustrating turn of events and I am hoping
that it will be corrected soon. I wonder if anyone else is
having similar problems?

I suspect that this email will be delivered, but I might not
be able to send another on the same thread.

Any ideas?
tim

From ricaraoz at gmail.com  Mon Dec  3 14:19:20 2007
From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=)
Date: Mon, 03 Dec 2007 10:19:20 -0300
Subject: [Tutor] Selecting a browser
In-Reply-To: <475244A3.10406@groktech.org>
References: <47500600.3050204@bigfoot.com> <475244A3.10406@groktech.org>
Message-ID: <47540258.4010204@bigfoot.com>

Martin Walsh wrote:
> Ricardo Ar?oz wrote:
>> Hi, I've checked webbrowser module and so far I find no way of selecting
>> a browser other than the default one. Say I want certain places opened
>> with IE and others with Mozilla, and I don't want to mess with the
>> user's setting of the default browser. Any tips?
>> TIA
> 
> I think one would normally use the form webbrowser.get('firefox'), on
> unix systems. But if I understand correctly, the "problem" with the
> webbrowser module on windows (and perhaps it is similar on a mac) is
> that unless the program can be found on your system PATH, only a generic
> 'windows-default' browser class is registered, which uses os.startfile,
> releasing control to the os, and serves to open the url in the user's
> default browser.
> 
> If you're determined to use the webbrowser module on windows, you might
> be able to do something like this:
> 
> import webbrowser
> 
> ffcommand = "c:/program files/mozilla firefox/firefox.exe %s &"
> ff = webbrowser.get(ffcommand)
> ff.open("http://www.example.com")
> 
> iecommand = "c:/program files/internet explorer/iexplore.exe %s &"
> ie = webbrowser.get(iecommand)
> ie.open("http://www.example.com")
> 
> I suppose you could also register them manually for later use with the
> webbrowser.get(browser_name) form.
> 
> webbrowser.register('firefox', None, ff)
> webbrowser.get('firefox').open('http://example.com')
> 

Hi Marty, thanks for your help.
I've tried your suggestions but they don't seem to work for me. In W's
system window I can do :
C:/> S:\FirefoxPortable\FirefoxPortable.exe http://www.google.com
and it will open my browser ok. But no matter what I try :
"c:/program files/mozilla firefox/firefox.exe %s &" or "c:/program
files/mozilla firefox/firefox.exe %s" as input to webbrowser.get() it
won't work.
Here's my session :

>>> import webbrowser
>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>> ff.open('http://www.google.com')
False
>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>> ff
<webbrowser.BackgroundBrowser object at 0x01BF7AD0>
>>> ff.open(r'http://www.google.com')
False
>>> ff.open('')
False
>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s")
>>> ff.open(r'http://www.google.com')
False

Besides looking at the Python 2.5 documentation gave me no clues. It is
very poorly documented e.g. :

register( name, constructor[, instance])
	Register the browser type name. Once a browser type is registered, the
get() function can return a controller for that browser type. If
instance is not provided, or is None, constructor will be called without
parameters to create an instance when needed. If instance is provided,
constructor will never be called, and may be None.
	This entry point is only useful if you plan to either set the BROWSER
variable or call get with a nonempty argument matching the name of a
handler you declare.

But it does not define what a 'constructor' is (I guess a function, but
no clue about what it's signature or functionality should be) or what an
"instance" is (but I can guess). Trouble is when you guess and things
don't work you don't have a clue if the fault lies in your 'guess' or in
your code. Note that it mentions 'the BROWSER variable' but does not say
what it is, what it's value should be, nor any clue about it's use.
Probably I lack knowledge in the subject, but hey! the whole purpose of
this module is to be able to call the browser WITHOUT any knowledge of
the subject.
I guess I'll have to look at the code when I have a couple of free hours.
I'd rather go with the 'webbrowser' module than the subprocess.Popen
option, as it 'should' abstract me from browser management. Anyway if I
can't advance through webbrowser I'll give your examples a try.
Thanks a lot for your help.

Ricardo

> Personally, I would probably just cut out the middle module and use
> subprocess.Popen to start the browser, after checking if it is installed
> (with os.path.isfile, or similar) -- which seems to be, more or less,
> what the webbrowser module does if it finds one of the predefined
> browsers on your system PATH. Something like this (pseudo-code):
> 
> browser = 'c:/program files/mozilla firefox/firefox.exe'
> 
> if os.path.isfile(browser):
>     p = subprocess.Popen([browser, 'http://www.example.com'])
>         # if you want to wait for the browser to
>         # close before continuing use p.wait() here
> else:
>     ... web browser not found ...
> 
> For dispatching based on site (url, or some other criteria), one idea
> would be to wrap something like the above in a function which accepts
> the web browser program path as an argument, and then pass the function
> a path appropriate for the given criteria. Here is another (untested)
> example to demonstrate:
> 
> import subprocess
> import urlparse
> import sys, os
> 
> FFPATH = 'c:/program files/mozilla firefox/firefox.exe'
> IEPATH = 'c:/program files/internet explorer/iexplore.exe'
> 
> IESITES = ['microsoft.com', 'www.microsoft.com']
> 
> def launch(url, browser, wait=False):
>     if os.path.isfile(browser):
>         p = subprocess.Popen([browser, url])
>         if wait:
>             p.wait()
>     else:
>         print 'Invalid browser.'
> 
> def main(url):
>     # pick browser path by domain name
>     netloc = urlparse.urlparse(url)[1]
>     if netloc in IESITES:
>         launch(url, IEPATH)
>     else:
>         launch(url, FFPATH)
> 
> if __name__ == '__main__':
>     if sys.argv[1:]:
>         main(sys.argv[1])
>     else:
>         print 'Not enough arguments.'
> 
> In theory, if you run this script from a console on windows with any
> microsoft.com url as an argument, it should open in IE -- where all
> others open in firefox. Really rough, but I hope it helps.
> 
> Regards,
> Marty
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From keridee at jayco.net  Tue Dec  4 01:25:49 2007
From: keridee at jayco.net (Tiger12506)
Date: Mon, 3 Dec 2007 19:25:49 -0500
Subject: [Tutor] lstrip removes '/' unexpectedly
References: <200711300817.38828.tim@johnsons-web.com><Pine.LNX.4.63.0711301433050.3190@cs.wpi.edu>
	<4753E186.50705@bigfoot.com>
Message-ID: <002201c8360c$3e1b8ec0$94fce004@jslaptop>

>> ##########################
>>>>> s = '/home/test/'
>>>>> s1 = s.lstrip('/ehmo')
>>>>> s1
>> 'test/'
>> ##########################
>>
>> Take a closer look at the documentation of lstrip, and you should see
>> that
>> what it takes in isn't treated as a prefix: rather, it'll be treated as a
>> set of characters.
>>
>
> But then the real bug is why does it not strip the trailing '/' in
> 'test/' or the 'e' that is in your set?

Because lstrip strips the characters within that set, starting from the
left,
until it encounters a character not in that set. Then it stops. This code
produces the same results, though surely more slowly.

def lstrip(s, set):
  for x in s:
    if x in set:
      return lstrip(s[1:],set)
    return s

JS


From keridee at jayco.net  Tue Dec  4 01:59:30 2007
From: keridee at jayco.net (Tiger12506)
Date: Mon, 3 Dec 2007 19:59:30 -0500
Subject: [Tutor] [wxPython-users] passing file name from one script to
	theGUI class
References: <c2157c790712021757r5b01a569ucd1947d680ddd371@mail.gmail.com>
Message-ID: <00a001c83611$7b41e880$94fce004@jslaptop>

I do not currently have wx installed, but I can see the errors...
I think some information will help you more than answers in this instance.

When you 'import clases_calling', what you are doing is creating a new 
namespace. Inside that namespace is the class 'funct'. In your code, you 
call the function 'clases_calling.func_call' which does not exist because it 
is hidden inside of the class 'funct'. To access this function you would 
have to 'clases_calling.funct.func_call(self)'. This is bad practice, and 
defeats the purpose of using a class. Which is understandable since the 
class 'funct' is not necessary here. All you need is a function that will 
return the new filename right? So, in the clases_calling module place a 
'getnewfilename' function which will return the new filename (no class in 
clases_calling) and in your 'readfile.py' call it by 
'clases_calling.getnewfilename()'. Also, when you try to call 'imagetobit' 
from your current 'func_call' function it will fail because in *this* module 
(clases_calling.py) you have it imported as 'MainWindow.imagetobit'. I would 
highly recommend *not* putting this code in this module anyway, intuitively 
it would belong in the 'OnRead' method right after the call to your new 
function 'getnewfilename'.

More errors to be... sigh.  Here we go.

In your function 'imagetobit' in readfile.py you should get an error because 
'self' is not defined. You have not put self in the argument list as you did 
in all the other methods of MainWindow. This also means that self.imageFile1 
will not be defined either, and should give you an error when trying to 
define it. If you adjust the imagetobit function so that it is a method of 
the class, we see that the imagename parameter is no longer necessary, as we 
can set the self.imageFile variable directly from one of the other 
functions. Also, I see code that looks very similar in the __init__  method 
of MainWindow and the function imagetobit. I suggest that you change this so 
that in the __init__ method you actually call self.imagetobit.

To summarize:
  1) Change clases_calling.py to be a single function that return the new 
filename as a string.
  2) Change MainWindow.OnRead so that it calls this new function first (I 
used clases_calling.getnewfilename()), then self.imagetobit(), and finally 
run the rest of the commented stuff you have there (Remembering that the 
Image redrawing has already been done in self.imagetobit() you can delete it 
here)
 3) Change imagetobit so that it is a method of the class MainWindow, and 
remove the imagename parameter
 4) Change all references of self.imageFile1 to just self.imageFile. You do 
not need the extra.
 5) Change MainWindow.__init__ so that it calls self.imagetobit() 
immediately after you set the variable self.imageFile

And... I think that's everything. IMHO the important concept inherently 
missed in these two modules is that the names of the functions and variable 
inside are hidden behind the names. i.e.
import math  is used as math.sqrt, instead of just sqrt.

HTH,
JS 


From kent37 at tds.net  Tue Dec  4 02:05:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 03 Dec 2007 20:05:35 -0500
Subject: [Tutor] Selecting a browser
In-Reply-To: <47540258.4010204@bigfoot.com>
References: <47500600.3050204@bigfoot.com> <475244A3.10406@groktech.org>
	<47540258.4010204@bigfoot.com>
Message-ID: <4754A7DF.8090404@tds.net>

Ricardo Ar?oz wrote:
>>>> import webbrowser
>>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>>> ff.open('http://www.google.com')
> False

Beware of backslashes in file paths - backslash introduces a character 
escape in Python strings. You can fix by any of
- use \\ instead of \
- use / instead of \ (it works fine)
- use raw strings (prefix with r) e.g. 
r"S:\FirefoxPortable\FirefoxPortable.exe %s &"

Kent

From mwalsh at groktech.org  Tue Dec  4 02:25:14 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Mon, 03 Dec 2007 19:25:14 -0600
Subject: [Tutor] Selecting a browser
In-Reply-To: <47540258.4010204@bigfoot.com>
References: <47500600.3050204@bigfoot.com> <475244A3.10406@groktech.org>
	<47540258.4010204@bigfoot.com>
Message-ID: <4754AC7A.6070909@groktech.org>

Ricardo Ar?oz wrote:
> Martin Walsh wrote:
> Hi Marty, thanks for your help.
> I've tried your suggestions but they don't seem to work for me. In W's
> system window I can do :
> C:/> S:\FirefoxPortable\FirefoxPortable.exe http://www.google.com
> and it will open my browser ok. But no matter what I try :
> "c:/program files/mozilla firefox/firefox.exe %s &" or "c:/program
> files/mozilla firefox/firefox.exe %s" as input to webbrowser.get() it
> won't work.

Hi Ricardo,

Never would have guessed that you were using a portable browser :) But
it really shouldn't matter. And by the way, the '&' has special meaning
to the webbrowser.get method -- it determines whether a
BackgroundBrowser or GenericBrowser object is returned.

> Here's my session :
> 
>>>> import webbrowser
>>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>>> ff.open('http://www.google.com')
> False

I suspect (with no way to confirm at the moment) that something in the
webbrowser module is confused by the backslashes. As you may know, the
backslash has special meaning in python strings, used as an escape
character to denote newlines (\n), tabs (\t), among others. I believe it
is helpful to be aware of this when using subprocess.Popen also. And, I
think you have more than one option for dealing with slashes in windows
paths, but I typically just replace the backslashes with forward slashes:

ff = webbrowser.get("S:/FirefoxPortable/FirefoxPortable.exe %s &")

> Besides looking at the Python 2.5 documentation gave me no clues. It is
> very poorly documented e.g. :
> 
> register( name, constructor[, instance])
> 	Register the browser type name. Once a browser type is registered, the
> get() function can return a controller for that browser type. If
> instance is not provided, or is None, constructor will be called without
> parameters to create an instance when needed. If instance is provided,
> constructor will never be called, and may be None.
> 	This entry point is only useful if you plan to either set the BROWSER
> variable or call get with a nonempty argument matching the name of a
> handler you declare.
> 
> But it does not define what a 'constructor' is (I guess a function, but
> no clue about what it's signature or functionality should be) or what an
> "instance" is (but I can guess). Trouble is when you guess and things
> don't work you don't have a clue if the fault lies in your 'guess' or in
> your code. Note that it mentions 'the BROWSER variable' but does not say

Based only on my own review of the webbrowser module source, the
constructor is the '*Browser' class object [ in other words
BackgroundBrowser and not BackgroundBrowser() ], presumably it should be
a subclass of webbrowser.GenericBrowser. And instance is what you would
think, an instance of a '*Browser' class.

> what it is, what it's value should be, nor any clue about it's use.
> Probably I lack knowledge in the subject, but hey! the whole purpose of
> this module is to be able to call the browser WITHOUT any knowledge of
> the subject.
> I guess I'll have to look at the code when I have a couple of free hours.

I would highly recommend it. It's straight forward, and very readable.

A helpful tip, perhaps: one of my favorite features of ipython, allows
fairly trivial access to a module's python source (not that it's
difficult by other means, really):

In [1]: import webbrowser

In [2]: webbrowser??

A single question mark prints the doc string if available, where the ??
pages the source. On linux, not sure about windows, I can move around
and search for text with all the same familiar keyboard commands (less
style).

> I'd rather go with the 'webbrowser' module than the subprocess.Popen
> option, as it 'should' abstract me from browser management. Anyway if I

I think that's the intent of the module, and a worthwhile pursuit. But,
IMHO you may find it's more work, and less flexible, than keeping track
of the browser paths yourself and calling subprocess.Popen -- on Windows
at least. YMMV. And it is certainly possible that you'll discover some
feature of the webbrowser module that I've overlooked. So, I hope you'll
report back to the list with your progress.

Good luck!
Marty

> can't advance through webbrowser I'll give your examples a try.
> Thanks a lot for your help.
> 
> Ricardo
> 


From bgailer at alum.rpi.edu  Tue Dec  4 04:05:15 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Mon, 03 Dec 2007 22:05:15 -0500
Subject: [Tutor] help
In-Reply-To: <346688.95690.qm@web25609.mail.ukl.yahoo.com>
References: <346688.95690.qm@web25609.mail.ukl.yahoo.com>
Message-ID: <4754C3EB.8070401@alum.rpi.edu>

Andrew Critchley wrote:
> I recently downloaded the newer version of python, the 2.5.1 one, and 
> when ever i try to make an input what ever i type into the brackets 
> appears on the next line and when i try to add the next line it 
> carries on from the input,This is what happens:
>  
> I type this down:
>  
> # Area calculation program
>
> >>>print ?Welcome to the Area calculation program?
> >>>print ???????????????
> >>>print
>
> >>># Print out the menu:
> >>>print ?Please select a shape:?
> >>>print ?1  Rectangle?
> >>>print ?2  Circle?
>
> >>># Get the user?s choice:
> shape = input(?>30 ?)
> >30 (and then this line appears)
> (here i should type "# Calculate the area:" but it carries on from the 
> above line and when i press enter i encunter an error and it all goes 
> wrong)
> please help me with this problem.
You are running the interpreter. Each line is executed after you enter 
it. You should be typing your program in an editor or IDE
> such as IDLE.
> ------------------------------------------------------------------------


From ricaraoz at gmail.com  Tue Dec  4 05:45:31 2007
From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=)
Date: Tue, 04 Dec 2007 01:45:31 -0300
Subject: [Tutor] Selecting a browser
In-Reply-To: <4754A7DF.8090404@tds.net>
References: <47500600.3050204@bigfoot.com>
	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>
	<4754A7DF.8090404@tds.net>
Message-ID: <4754DB6B.7050506@bigfoot.com>

Kent Johnson wrote:
> Ricardo Ar?oz wrote:
>>>>> import webbrowser
>>>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>>>> ff.open('http://www.google.com')
>> False
> 
> Beware of backslashes in file paths - backslash introduces a character 
> escape in Python strings. You can fix by any of
> - use \\ instead of \
> - use / instead of \ (it works fine)
> - use raw strings (prefix with r) e.g. 
> r"S:\FirefoxPortable\FirefoxPortable.exe %s &"
> 

Thanks Kent, that was certainly the problem. So I went through it just
to hit another wall, when issuing the open method :

>>> ff.open('http://www.google.com')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "E:\Python25\lib\webbrowser.py", line 168, in open
    p = subprocess.Popen(cmdline, close_fds=True)
  File "E:\Python25\lib\subprocess.py", line 551, in __init__
    raise ValueError("close_fds is not supported on Windows "
ValueError: close_fds is not supported on Windows platforms

No easy way, I'll have to check the module's code. Or go Marty's way
(that's popen).

Thanks


From ricaraoz at gmail.com  Tue Dec  4 05:51:52 2007
From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=)
Date: Tue, 04 Dec 2007 01:51:52 -0300
Subject: [Tutor] Selecting a browser
In-Reply-To: <4754AC7A.6070909@groktech.org>
References: <47500600.3050204@bigfoot.com>
	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>
	<4754AC7A.6070909@groktech.org>
Message-ID: <4754DCE8.4070005@bigfoot.com>

Martin Walsh wrote:
> Ricardo Ar?oz wrote:
>> Martin Walsh wrote:
>> Hi Marty, thanks for your help.
>> I've tried your suggestions but they don't seem to work for me. In W's
>> system window I can do :
>> C:/> S:\FirefoxPortable\FirefoxPortable.exe http://www.google.com
>> and it will open my browser ok. But no matter what I try :
>> "c:/program files/mozilla firefox/firefox.exe %s &" or "c:/program
>> files/mozilla firefox/firefox.exe %s" as input to webbrowser.get() it
>> won't work.
> 
> Hi Ricardo,
> 
> Never would have guessed that you were using a portable browser :) But
> it really shouldn't matter. And by the way, the '&' has special meaning
> to the webbrowser.get method -- it determines whether a
> BackgroundBrowser or GenericBrowser object is returned.

LOL, another demerit to documentation.
I not only use a portable browser, it's inside a TrueCrypt volume in my
pen drive. That means I'm not restrained to my company's choices on
browsers or their settings, and I get 'some' degree of privacy.


> 
>> Here's my session :
>>
>>>>> import webbrowser
>>>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>>>> ff.open('http://www.google.com')
>> False
> 
> I suspect (with no way to confirm at the moment) that something in the
> webbrowser module is confused by the backslashes. As you may know, the
> backslash has special meaning in python strings, used as an escape
> character to denote newlines (\n), tabs (\t), among others. I believe it
> is helpful to be aware of this when using subprocess.Popen also. And, I
> think you have more than one option for dealing with slashes in windows
> paths, but I typically just replace the backslashes with forward slashes:
> 
> ff = webbrowser.get("S:/FirefoxPortable/FirefoxPortable.exe %s &")
> 

That did it, but as I told Kent :

ff.open('http://www.google.com')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "E:\Python25\lib\webbrowser.py", line 168, in open
    p = subprocess.Popen(cmdline, close_fds=True)
  File "E:\Python25\lib\subprocess.py", line 551, in __init__
    raise ValueError("close_fds is not supported on Windows "
ValueError: close_fds is not supported on Windows platforms

Don't worry, I see I'll have to look into the module's code or go the
popen() way. I'll let you know.

Again, thanks a lot for your help.

Ricardo


From simozack at yahoo.it  Tue Dec  4 08:28:55 2007
From: simozack at yahoo.it (Simone)
Date: Tue, 04 Dec 2007 08:28:55 +0100
Subject: [Tutor] Selecting a browser
In-Reply-To: <4754DCE8.4070005@bigfoot.com>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>
	<4754DCE8.4070005@bigfoot.com>
Message-ID: <475501B7.6020202@yahoo.it>

Ricardo Ar?oz ha scritto:


>> ff = webbrowser.get("S:/FirefoxPortable/FirefoxPortable.exe %s &")
> That did it, but as I told Kent :
> 
> ff.open('http://www.google.com')
> Traceback (most recent call last):
>   File "<input>", line 1, in <module>
>   File "E:\Python25\lib\webbrowser.py", line 168, in open
>     p = subprocess.Popen(cmdline, close_fds=True)
>   File "E:\Python25\lib\subprocess.py", line 551, in __init__
>     raise ValueError("close_fds is not supported on Windows "
> ValueError: close_fds is not supported on Windows platforms

I think the problem is in '&' at the end of the command line.

The '&' is used on Linux/Unix system to start processes in a independent 
thread.

Remove it and it works!

Simone
Chiacchiera con i tuoi amici in tempo reale! 
 http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com 

From mail at timgolden.me.uk  Tue Dec  4 10:27:48 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 04 Dec 2007 09:27:48 +0000
Subject: [Tutor] Selecting a browser
In-Reply-To: <4754DCE8.4070005@bigfoot.com>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>
	<4754DCE8.4070005@bigfoot.com>
Message-ID: <47551D94.8070501@timgolden.me.uk>

Ricardo Ar?oz wrote:
> Martin Walsh wrote:
>> And by the way, the '&' has special meaning
>> to the webbrowser.get method -- it determines whether a
>> BackgroundBrowser or GenericBrowser object is returned.
> 
> LOL, another demerit to documentation.

Agreed. But it would be more constructive to offer a simple
patch to the webbrowser docs. You can get hold of the relevant
docs here [1] and you want the webbrowser.rst file (obviously!).
If you raise an Issue on the tracker [2] and attach a patch, it
will generally get a quick response from Georg or one of the
other doc maintainers.

TJG

[1] http://svn.python.org/projects/python/trunk/Doc/library
[2] http://bugs.python.org/issue?@template=item

From ricaraoz at gmail.com  Tue Dec  4 11:08:28 2007
From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=)
Date: Tue, 04 Dec 2007 07:08:28 -0300
Subject: [Tutor] Selecting a browser
In-Reply-To: <47551D94.8070501@timgolden.me.uk>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>
	<47551D94.8070501@timgolden.me.uk>
Message-ID: <4755271C.50006@bigfoot.com>

Tim Golden wrote:
> Ricardo Ar?oz wrote:
>> Martin Walsh wrote:
>>> And by the way, the '&' has special meaning
>>> to the webbrowser.get method -- it determines whether a
>>> BackgroundBrowser or GenericBrowser object is returned.
>> LOL, another demerit to documentation.
> 
> Agreed. But it would be more constructive to offer a simple
> patch to the webbrowser docs. You can get hold of the relevant
> docs here [1] and you want the webbrowser.rst file (obviously!).
> If you raise an Issue on the tracker [2] and attach a patch, it
> will generally get a quick response from Georg or one of the
> other doc maintainers.
> 
> TJG
> 
> [1] http://svn.python.org/projects/python/trunk/Doc/library
> [2] http://bugs.python.org/issue?@template=item

Thanks Tim.
And please don't take it personal. These guys have given their free time
so that we can enjoy their module, they could have no documentation at
all and we should thank them anyway. That said, my comments about
documentation lacking still stand.
I'll check your links as soon as I have some time (right now my use of
python is just for the love of the trade) and if I can come up with
something to improve the docs I'll send it to these blokes.

From mail at timgolden.me.uk  Tue Dec  4 11:27:03 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 04 Dec 2007 10:27:03 +0000
Subject: [Tutor] Selecting a browser
In-Reply-To: <4755271C.50006@bigfoot.com>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>
	<4755271C.50006@bigfoot.com>
Message-ID: <47552B77.70204@timgolden.me.uk>

Ricardo Ar?oz wrote:
> These guys have given their free time so that we can enjoy their module, 
 > hey could have no documentation at all...
 > That said, my comments about documentation lacking still stand.

I think the important thing here is that "these guys" is you
and me. Documentation is exactly one of those areas where less
experienced people -- or people with less time on their hands --
can add to the quality of the overall product.

> I'll check your links as soon as I have some time (right now my use of
> python is just for the love of the trade) and if I can come up with
> something to improve the docs I'll send it to these blokes.

If you don't think you'll be able to get something together within
a day or two, get back to me and I'll write something up while it's
still fresh in my mind. It's only a line or two...

TJG

From ricaraoz at gmail.com  Tue Dec  4 11:38:31 2007
From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=)
Date: Tue, 04 Dec 2007 07:38:31 -0300
Subject: [Tutor] Selecting a browser
In-Reply-To: <47551D94.8070501@timgolden.me.uk>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>
	<47551D94.8070501@timgolden.me.uk>
Message-ID: <47552E27.3050903@bigfoot.com>

Tim Golden wrote:
> Ricardo Ar?oz wrote:
>> Martin Walsh wrote:
>>> And by the way, the '&' has special meaning
>>> to the webbrowser.get method -- it determines whether a
>>> BackgroundBrowser or GenericBrowser object is returned.
>> LOL, another demerit to documentation.
> 
> Agreed. But it would be more constructive to offer a simple
> patch to the webbrowser docs. You can get hold of the relevant
> docs here [1] and you want the webbrowser.rst file (obviously!).
> If you raise an Issue on the tracker [2] and attach a patch, it
> will generally get a quick response from Georg or one of the
> other doc maintainers.
> 
> TJG
> 
> [1] http://svn.python.org/projects/python/trunk/Doc/library
> [2] http://bugs.python.org/issue?@template=item

Ok, I took a look. Nice link to know [1], I've added it to my links.

Sadly ValueError is not mentioned in the rst, they only mention

"""
The following exception is defined:


.. exception:: Error

   Exception raised when a browser control error occurs.
"""

I'll try to read the module's code and come up with something. Then I'll
send them a report (if Kronos allows me to).
Cheers.

Ricardo




From mail at timgolden.me.uk  Tue Dec  4 11:45:54 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 04 Dec 2007 10:45:54 +0000
Subject: [Tutor] Selecting a browser
In-Reply-To: <47552E27.3050903@bigfoot.com>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>
	<47552E27.3050903@bigfoot.com>
Message-ID: <47552FE2.1090201@timgolden.me.uk>

Ricardo Ar?oz wrote:
> Tim Golden wrote:
>> Ricardo Ar?oz wrote:
>>> Martin Walsh wrote:
>>>> And by the way, the '&' has special meaning
>>>> to the webbrowser.get method -- it determines whether a
>>>> BackgroundBrowser or GenericBrowser object is returned.
>>> LOL, another demerit to documentation.
>> Agreed. But it would be more constructive to offer a simple
>> patch to the webbrowser docs. You can get hold of the relevant
>> docs here [1] and you want the webbrowser.rst file (obviously!).
>> If you raise an Issue on the tracker [2] and attach a patch, it
>> will generally get a quick response from Georg or one of the
>> other doc maintainers.
>>
>> TJG
>>
>> [1] http://svn.python.org/projects/python/trunk/Doc/library
>> [2] http://bugs.python.org/issue?@template=item
> 
> Ok, I took a look. Nice link to know [1], I've added it to my links.
> 
> Sadly ValueError is not mentioned in the rst, they only mention
> 
> """
> The following exception is defined:
> 
> 
> .. exception:: Error
> 
>    Exception raised when a browser control error occurs.
> """
> 
> I'll try to read the module's code and come up with something. Then I'll
> send them a report (if Kronos allows me to).

I think the sensible thing is: rather than determine all the
many exceptions that could be raised through one circumstance
or another, to define the critical thing that the "&" at the
end of the webbrowser.get/open[...] functions causes a different
mode to fire. Arguably it should be added to the docstrings as
well.

TJG

From kent37 at tds.net  Tue Dec  4 14:10:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 04 Dec 2007 08:10:05 -0500
Subject: [Tutor] Selecting a browser
In-Reply-To: <4754DB6B.7050506@bigfoot.com>
References: <47500600.3050204@bigfoot.com>
	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>
	<4754A7DF.8090404@tds.net> <4754DB6B.7050506@bigfoot.com>
Message-ID: <475551AD.9070208@tds.net>

Ricardo Ar?oz wrote:
> Thanks Kent, that was certainly the problem. So I went through it just
> to hit another wall, when issuing the open method :
> 
>>>> ff.open('http://www.google.com')
> Traceback (most recent call last):
>   File "<input>", line 1, in <module>
>   File "E:\Python25\lib\webbrowser.py", line 168, in open
>     p = subprocess.Popen(cmdline, close_fds=True)
>   File "E:\Python25\lib\subprocess.py", line 551, in __init__
>     raise ValueError("close_fds is not supported on Windows "
> ValueError: close_fds is not supported on Windows platforms
> 
> No easy way, I'll have to check the module's code. Or go Marty's way
> (that's popen).

You must be using Python 2.5. This was fixed in 2.5.1
http://www.python.org/download/releases/2.5.1/NEWS.txt (search for 
webbrowser)

Kent

From kent37 at tds.net  Tue Dec  4 14:14:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 04 Dec 2007 08:14:52 -0500
Subject: [Tutor] Selecting a browser
In-Reply-To: <47552E27.3050903@bigfoot.com>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>
	<47552E27.3050903@bigfoot.com>
Message-ID: <475552CC.6050802@tds.net>

Ricardo Ar?oz wrote:
> Tim Golden wrote:
>> Agreed. But it would be more constructive to offer a simple
>> patch to the webbrowser docs.

You don't even need to give a formal patch. Just write the doc change in 
plain text and submit it as a bug.

> Ok, I took a look. Nice link to know [1], I've added it to my links.
> 
> Sadly ValueError is not mentioned in the rst

Usually the exceptions that can be raised by a function are *not* 
documented.

IMO what is missing from the docs is the ability to provide a full path 
to webbrowser.get(). All of these are valid arguments, and they all have 
a different meaning:

get('firefox')
get('/path/to/firefox %s')
get('/path/to/firefox %s &')

The docs only cover the first one.

Kent

From mail at timgolden.me.uk  Tue Dec  4 15:09:29 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 04 Dec 2007 14:09:29 +0000
Subject: [Tutor] Selecting a browser
In-Reply-To: <475552CC.6050802@tds.net>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>
	<47552E27.3050903@bigfoot.com> <475552CC.6050802@tds.net>
Message-ID: <47555F99.4090008@timgolden.me.uk>

Kent Johnson wrote:
> Ricardo Ar?oz wrote:
>> Tim Golden wrote:
>>> Agreed. But it would be more constructive to offer a simple
>>> patch to the webbrowser docs.
> 
> You don't even need to give a formal patch. Just write the doc change in 
> plain text and submit it as a bug.

True. But the entry level is now *much* lower
than it used to be, both to submit a bug and to
modify the docs source, the former thanks to the
switch to roundup, the latter thanks to Georg
Brandl's work on Sphinx and the switch to .rst.

Certainly if the OP were to submit a plain text
update I'd happily do the conversion to .rst. (I've
recently submitted a patch to Sphinx so the new-style
docs all build correctly under Windows).

In addition, for those not following that particular
story, the Google Highly Open thingy (GHOP) is seeing
a bunch of updates, additions and corrections to the
docs being submitted pretty much every day. Which can
only be a good thing!

TJG

From kent37 at tds.net  Tue Dec  4 16:13:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 04 Dec 2007 10:13:23 -0500
Subject: [Tutor] Selecting a browser
In-Reply-To: <47555F99.4090008@timgolden.me.uk>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>	<47552E27.3050903@bigfoot.com>
	<475552CC.6050802@tds.net> <47555F99.4090008@timgolden.me.uk>
Message-ID: <47556E93.9090801@tds.net>

Tim Golden wrote:
> In addition, for those not following that particular
> story, the Google Highly Open thingy (GHOP) is seeing
> a bunch of updates, additions and corrections to the
> docs being submitted pretty much every day. Which can
> only be a good thing!

In fact updating the webbrowser docs would make a fine GHOP task.

Kent

From andre.roberge at gmail.com  Tue Dec  4 16:36:42 2007
From: andre.roberge at gmail.com (Andre Roberge)
Date: Tue, 4 Dec 2007 11:36:42 -0400
Subject: [Tutor] Selecting a browser
In-Reply-To: <47556E93.9090801@tds.net>
References: <47500600.3050204@bigfoot.com> <475244A3.10406@groktech.org>
	<47540258.4010204@bigfoot.com> <4754AC7A.6070909@groktech.org>
	<4754DCE8.4070005@bigfoot.com> <47551D94.8070501@timgolden.me.uk>
	<47552E27.3050903@bigfoot.com> <475552CC.6050802@tds.net>
	<47555F99.4090008@timgolden.me.uk> <47556E93.9090801@tds.net>
Message-ID: <7528bcdd0712040736o30c2f21cx8f2c20bfade2bdaa@mail.gmail.com>

Forwarded to the ghop-discussion list :-)

Thanks Kent for the suggestion.

Andr?

On Dec 4, 2007 11:13 AM, Kent Johnson <kent37 at tds.net> wrote:

> Tim Golden wrote:
> > In addition, for those not following that particular
> > story, the Google Highly Open thingy (GHOP) is seeing
> > a bunch of updates, additions and corrections to the
> > docs being submitted pretty much every day. Which can
> > only be a good thing!
>
> In fact updating the webbrowser docs would make a fine GHOP task.
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071204/0ec7218e/attachment.htm 

From doug.hellmann at gmail.com  Tue Dec  4 16:37:57 2007
From: doug.hellmann at gmail.com (Doug Hellmann)
Date: Tue, 4 Dec 2007 10:37:57 -0500
Subject: [Tutor] Selecting a browser
In-Reply-To: <7528bcdd0712040736o30c2f21cx8f2c20bfade2bdaa@mail.gmail.com>
References: <47500600.3050204@bigfoot.com> <475244A3.10406@groktech.org>
	<47540258.4010204@bigfoot.com> <4754AC7A.6070909@groktech.org>
	<4754DCE8.4070005@bigfoot.com> <47551D94.8070501@timgolden.me.uk>
	<47552E27.3050903@bigfoot.com> <475552CC.6050802@tds.net>
	<47555F99.4090008@timgolden.me.uk> <47556E93.9090801@tds.net>
	<7528bcdd0712040736o30c2f21cx8f2c20bfade2bdaa@mail.gmail.com>
Message-ID: <18DE2A67-E8D8-4841-B0E0-5D7579A7ACD1@gmail.com>

+1

On Dec 4, 2007, at 10:36 AM, Andre Roberge wrote:

> Forwarded to the ghop-discussion list :-)
>
> Thanks Kent for the suggestion.
>
> Andr?
>
> On Dec 4, 2007 11:13 AM, Kent Johnson <kent37 at tds.net> wrote:
> Tim Golden wrote:
> > In addition, for those not following that particular
> > story, the Google Highly Open thingy (GHOP) is seeing
> > a bunch of updates, additions and corrections to the
> > docs being submitted pretty much every day. Which can
> > only be a good thing!
>
> In fact updating the webbrowser docs would make a fine GHOP task.
>
> Kent
> _______________________________________________
> Tutor maillist  -   Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> --~--~---------~--~----~------------~-------~--~----~
> You received this message because you are subscribed to the Google  
> Groups "Python GHOP discussions" group.
> To post to this group, send email to ghop-python at googlegroups.com
> To unsubscribe from this group, send email to ghop-python- 
> unsubscribe at googlegroups.com
> For more options, visit this group at http://groups.google.com/ 
> group/ghop-python?hl=en
> -~----------~----~----~----~------~----~------~--~---
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071204/ba72c5e8/attachment.htm 

From earlylightpublishing at yahoo.com  Tue Dec  4 19:56:26 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Tue, 4 Dec 2007 10:56:26 -0800 (PST)
Subject: [Tutor] Random Number Generator
In-Reply-To: <mailman.17.1196766006.637.tutor@python.org>
Message-ID: <419314.69282.qm@web45106.mail.sp1.yahoo.com>

Hello All,
   
  I'm a bare beginner to python (or indeed) any programming.  I'm helping myself become more proficient by making a text adventure game.  The problem is I need a function (or module) that will generate a random number within a range, say 1-20 for example.  The ability to program this is beyond my meager abilities at the moment but I'd really like to get started.  Would anyone out there be willing to provide me the code for me?  Or at least point me in the right direction for finding it myself?
   
  TYIA
  :-)

       
---------------------------------
Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071204/002d47f9/attachment.htm 

From jason.massey at gmail.com  Tue Dec  4 20:11:41 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Tue, 4 Dec 2007 13:11:41 -0600
Subject: [Tutor] Random Number Generator
In-Reply-To: <419314.69282.qm@web45106.mail.sp1.yahoo.com>
References: <mailman.17.1196766006.637.tutor@python.org>
	<419314.69282.qm@web45106.mail.sp1.yahoo.com>
Message-ID: <7e3eab2c0712041111j36a2e6d3v61f14378c9859cb@mail.gmail.com>

Easy enough.  You'll want to import the random module and use the functions
in it.  Also, http://docs.python.org/lib/lib.html is going to be your best
friend.  You'll notice on that page among many other things is a section on
random number generation.

As to your code:

>>>import random
>>>a = random.randint(1,20)
>>>a
3


On Dec 4, 2007 12:56 PM, earlylight publishing <
earlylightpublishing at yahoo.com> wrote:

> Hello All,
>
> I'm a bare beginner to python (or indeed) any programming.  I'm helping
> myself become more proficient by making a text adventure game.  The problem
> is I need a function (or module) that will generate a random number within a
> range, say 1-20 for example.  The ability to program this is beyond my
> meager abilities at the moment but I'd really like to get started.  Would
> anyone out there be willing to provide me the code for me?  Or at least
> point me in the right direction for finding it myself?
>
> TYIA
> :-)
>
> ------------------------------
> Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See
> how. <http://us.rd.yahoo.com/evt=51732/*http://overview.mail.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/20071204/e0662b91/attachment-0001.htm 

From bhaaluu at gmail.com  Tue Dec  4 20:16:21 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Tue, 4 Dec 2007 14:16:21 -0500
Subject: [Tutor] Random Number Generator
In-Reply-To: <419314.69282.qm@web45106.mail.sp1.yahoo.com>
References: <mailman.17.1196766006.637.tutor@python.org>
	<419314.69282.qm@web45106.mail.sp1.yahoo.com>
Message-ID: <ea979d70712041116v45fae3f0ub747833454b2c1fa@mail.gmail.com>

Greetings,
Take a look at my first Python program for an example:

http://www.geocities.com/ek.bhaaluu/python/paperock.py.txt

That should give you an idea.
Also:
You can use Python itself for getting help:

>>> help('random')

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

On Dec 4, 2007 1:56 PM, earlylight publishing
<earlylightpublishing at yahoo.com> wrote:
> Hello All,
>
> I'm a bare beginner to python (or indeed) any programming.  I'm helping
> myself become more proficient by making a text adventure game.  The problem
> is I need a function (or module) that will generate a random number within a
> range, say 1-20 for example.  The ability to program this is beyond my
> meager abilities at the moment but I'd really like to get started.  Would
> anyone out there be willing to provide me the code for me?  Or at least
> point me in the right direction for finding it myself?
>
> TYIA
> :-)
>
>
>  ________________________________
> Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at btinternet.com  Tue Dec  4 20:29:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 4 Dec 2007 19:29:35 -0000
Subject: [Tutor] Random Number Generator
References: <mailman.17.1196766006.637.tutor@python.org><419314.69282.qm@web45106.mail.sp1.yahoo.com>
	<ea979d70712041116v45fae3f0ub747833454b2c1fa@mail.gmail.com>
Message-ID: <fj49r6$3h4$1@ger.gmane.org>


"bhaaluu" <bhaaluu at gmail.com> wrote 

> You can use Python itself for getting help:
> 
>>>> help('random')

Well, well. I've been busily importing everything I wanted help on, 
not realising I could just quote it!

Now that little insight has probably saved me an hour a year or more!

Thanks for that ;-)

Alan g.


From norman at khine.net  Tue Dec  4 20:20:01 2007
From: norman at khine.net (Norman Khine)
Date: Tue, 04 Dec 2007 20:20:01 +0100
Subject: [Tutor] Time module
Message-ID: <4755A861.9070508@khine.net>

Hello,
I am having difficulties in converting the following to display the 
difference that has passed in hours and seconds in a nice way.

from datetime import datetime
now = datetime.now()
posted = date
difference = now - posted

namespace['date'] = date
namespace['posted'] = difference

when I look at the 'posted' namespace I get

23:08:31.454767

What is the best way to split this so that it will show

'23h 08m 31s' ago

or

1d 23h 08m 31s ago

etc..

Thanks



From kent37 at tds.net  Tue Dec  4 23:21:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 04 Dec 2007 17:21:51 -0500
Subject: [Tutor] Time module
In-Reply-To: <4755A861.9070508@khine.net>
References: <4755A861.9070508@khine.net>
Message-ID: <4755D2FF.2070908@tds.net>

Norman Khine wrote:
> Hello,
> I am having difficulties in converting the following to display the 
> difference that has passed in hours and seconds in a nice way.
> 
> from datetime import datetime
> now = datetime.now()
> posted = date
> difference = now - posted
> 
> namespace['date'] = date
> namespace['posted'] = difference

It would help if you would show complete code - what is date? what is 
namespace? Anyway, guessing that posted is a datetime.datetime, then 
difference is a datetime.timedelta.

> when I look at the 'posted' namespace I get
> 
> 23:08:31.454767
> 
> What is the best way to split this so that it will show
> 
> '23h 08m 31s' ago

You will have to do some work yourself. difference has attributes days, 
seconds and microseconds. You can split the seconds into hours, minutes 
and seconds using % or divmod().

Kent

From ricaraoz at gmail.com  Tue Dec  4 14:22:24 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Tue, 04 Dec 2007 10:22:24 -0300
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <47540A65.9040402@brunson.com>
References: <200711300817.38828.tim@johnsons-web.com>	<Pine.LNX.4.63.0711301433050.3190@cs.wpi.edu>	<4753E186.50705@bigfoot.com>
	<47540A65.9040402@brunson.com>
Message-ID: <47555490.1090407@bigfoot.com>

Eric Brunson wrote:
> Ricardo Ar?oz wrote:
>> Danny Yoo wrote:
>>   
>>>> Hello:
>>>> I'm seeing some strange behavior with lstrip operating
>>>> on string representations of *nix-style file paths
>>>> Example:
>>>>       
>>>>>>> s = '/home/test/'
>>>>>>> s1 = s.lstrip('/home')
>>>>>>> s1
>>>>>>>             
>>>> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
>>>> Any comments or corrective measures are welcome
>>>>       
>>> Hi Tim,
>>>
>>> Here's another example to help you see what's going on:
>>>
>>> ##########################
>>>     
>>>>>> s = '/home/test/'
>>>>>> s1 = s.lstrip('/ehmo')
>>>>>> s1
>>>>>>           
>>> 'test/'
>>> ##########################
>>>
>>> Take a closer look at the documentation of lstrip, and you should see that 
>>> what it takes in isn't treated as a prefix: rather, it'll be treated as a 
>>> set of characters.
>>>
>>>     
>> But then the real bug is why does it not strip the trailing '/' in
>> 'test/' or the 'e' that is in your set?
>>
>>   
> Because it's lstrip(), the "L" meaning "left".  Not strip() or rstrip().
> 

Silly me, should have checked before opening my big mouth. :-)


From ricaraoz at gmail.com  Tue Dec  4 18:05:02 2007
From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=)
Date: Tue, 04 Dec 2007 14:05:02 -0300
Subject: [Tutor] Selecting a browser
In-Reply-To: <47552B77.70204@timgolden.me.uk>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>	<4755271C.50006@bigfoot.com>
	<47552B77.70204@timgolden.me.uk>
Message-ID: <475588BE.60909@bigfoot.com>

Tim Golden wrote:
> Ricardo Ar?oz wrote:
>> These guys have given their free time so that we can enjoy their module, 
>  > hey could have no documentation at all...
>  > That said, my comments about documentation lacking still stand.
> 
> I think the important thing here is that "these guys" is you
> and me. Documentation is exactly one of those areas where less
> experienced people -- or people with less time on their hands --
> can add to the quality of the overall product.
> 
>> I'll check your links as soon as I have some time (right now my use of
>> python is just for the love of the trade) and if I can come up with
>> something to improve the docs I'll send it to these blokes.
> 
> If you don't think you'll be able to get something together within
> a day or two, get back to me and I'll write something up while it's
> still fresh in my mind. It's only a line or two...
> 
> TJG

Ok. Tim, Marty, I think I got it.
My code :

>>> import webbrowser
>>> ff = webbrowser.get(r"S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>> ff.open('http://www.google.com')
False
>>> ff = webbrowser.get("S:/FirefoxPortable/FirefoxPortable.exe %s &")
>>> ff.open('http://www.google.com')
True

So I checked webbrowser module, and there I found that the fault resides
in shlex module or in the way webbrowser uses shlex module.
In function get() defined in line 27 of webbrowser.py, in line 37 you have :
"""
        if '%s' in browser:
            # User gave us a command line, split it into name and args
            browser = shlex.split(browser)
            if browser[-1] == '&':
                return BackgroundBrowser(browser[:-1])
            else:
                return GenericBrowser(browser)
        else:
"""
Notice the & at the end of the command line is handled ok.
And the problem lies in the use of shlex.split(browser) instruction.
This is the problem :

>>> browser = r"S:\FirefoxPortable\FirefoxPortable.exe %s &"
>>> browser
'S:\\FirefoxPortable\\FirefoxPortable.exe %s &'
>>> import shlex
>>> shlex.split(browser)	&& this one does not work
['S:FirefoxPortableFirefoxPortable.exe', '%s', '&']
>>> browser = "S:/FirefoxPortable/FirefoxPortable.exe %s &"
>>> shlex.split(browser)	&& this one works ok.
['S:/FirefoxPortable/FirefoxPortable.exe', '%s', '&']

The point is shlex uses the '\\' as an escape character, that's why it
gets ignored. One fix would be to disable or change the escape character
so instead of shlex.split(browser) it would be :

        if '%s' in browser:
            # User gave us a command line, split it into name and args
#            browser = shlex.split(browser)
            oShlex = shlex.shlex(browser, posix=True)
            oShlex.whitespace_split = True
            oShlex.escape = ''	# or whatever character we wish to be escape
            browser = list(oShlex)
            if browser[-1] == '&':
                return BackgroundBrowser(browser[:-1])
            else:
                return GenericBrowser(browser)
        else:

Did this in my webbrowser.py and then :

>>> import webbrowser
>>> ff = webbrowser.get("S:\FirefoxPortable\FirefoxPortable.exe %s &")
>>> ff.open('http://www.google.com', 2)
True

And the browser opened as expected (note that I didn't have to use raw
strings).

The other way to handle it would be to include in the documentation that
windows paths should have '/' or '\\\\' instead of '\\'.
The choice would depend on whether the authors consider there is a use
for the escape character, and what value that escape character might have.
I've registered in the issue tracker, but got scared and didn't post
anything. Can I be certain the blokes maintaining this module will see
it, or should and try contact them directly? You see, I'm new in this
contribution thingy. Or even better, could you Tim or Marty post the
issue and then let me know where it is so I can take a look and get the
flavor of what is expected in the tracker?

Cheers

Ricardo





From bhaaluu at gmail.com  Tue Dec  4 23:41:57 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Tue, 4 Dec 2007 17:41:57 -0500
Subject: [Tutor] Random Number Generator
In-Reply-To: <fj49r6$3h4$1@ger.gmane.org>
References: <mailman.17.1196766006.637.tutor@python.org>
	<419314.69282.qm@web45106.mail.sp1.yahoo.com>
	<ea979d70712041116v45fae3f0ub747833454b2c1fa@mail.gmail.com>
	<fj49r6$3h4$1@ger.gmane.org>
Message-ID: <ea979d70712041441p58438e8ah5e69ba3ec90777cb@mail.gmail.com>

On Dec 4, 2007 2:29 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "bhaaluu" <bhaaluu at gmail.com> wrote
>
> > You can use Python itself for getting help:
> >
> >>>> help('random')
>
> Well, well. I've been busily importing everything I wanted help on,
> not realising I could just quote it!
>
> Now that little insight has probably saved me an hour a year or more!
>
> Thanks for that ;-)
>
> Alan g.
>

For purposes of pedagogy, perhaps this requires more explanation?

I'm running the Python 2.4.3 interactive interpreter
in a Konsole at a bash prompt:

$ python

>>> help
Type help() for interactive help, or help(object) for help about object.

>>>  help()

Welcome to Python 2.4!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>   <--Note: the prompt has changed! I'm in help() now.
help> 'random'
Help on module random:

NAME
    random - Random variable generators.
[snip]
:     <--Note: Press space bar for next page, or Arrow keys for lines

help> 'quit'

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

>>>    <-- Note: I'm back in the Python interactive interpreter.

>>> [Ctrl-D]  <-- Press 'Ctrl' + 'd' to exit the interactive interpreter.
$  <-- back at the bash prompt

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

From earlylightpublishing at yahoo.com  Wed Dec  5 01:21:22 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Tue, 4 Dec 2007 16:21:22 -0800 (PST)
Subject: [Tutor] Thanks (was Random Number Generator)
In-Reply-To: <mailman.8338.1196795507.13604.tutor@python.org>
Message-ID: <682295.56128.qm@web45101.mail.sp1.yahoo.com>

Thank you everyone for your help!  I have no idea why it never occured to me to Google it.  Thanks for the code.  Now let's see if I can get this sucker to work! 

       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071204/04ed7ed2/attachment.htm 

From oclbdk at gmail.com  Wed Dec  5 01:30:11 2007
From: oclbdk at gmail.com (Johnston Jiaa)
Date: Tue, 4 Dec 2007 19:30:11 -0500
Subject: [Tutor] Button 1 Motion Event
Message-ID: <E82B361D-6ED3-47FE-A14C-8643EF714922@gmail.com>

I'm creating a drawing program, like MS Paint in Tkinter.  I bound  
the <B1-Motion> event to my Canvas object.  The function it's bound  
to creates an oval at the event's x and y attributes.

This works fine if the user is dragging slowly, but if he does a  
sudden dragging motion, the ovals are very far apart.  Is there any  
way to fix this?

Johnston Jiaa

From alan.gauld at btinternet.com  Wed Dec  5 02:05:19 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 5 Dec 2007 01:05:19 -0000
Subject: [Tutor] Button 1 Motion Event
References: <E82B361D-6ED3-47FE-A14C-8643EF714922@gmail.com>
Message-ID: <fj4tgn$6is$1@ger.gmane.org>


"Johnston Jiaa" <oclbdk at gmail.com> wrote

> I'm creating a drawing program, like MS Paint in Tkinter.  I bound
> the <B1-Motion> event to my Canvas object.  The function it's bound
> to creates an oval at the event's x and y attributes.
>
> This works fine if the user is dragging slowly, but if he does a
> sudden dragging motion, the ovals are very far apart.  Is there any
> way to fix this?

Its hard to tell what might be happening without code.

Can you cut your code to a minimum that demonstrates the problem
and post it? Particularly the method that you are using for the B1 
event.

Alan G. 



From rabidpoobear at gmail.com  Wed Dec  5 02:26:05 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 04 Dec 2007 19:26:05 -0600
Subject: [Tutor] Button 1 Motion Event
In-Reply-To: <E82B361D-6ED3-47FE-A14C-8643EF714922@gmail.com>
References: <E82B361D-6ED3-47FE-A14C-8643EF714922@gmail.com>
Message-ID: <4755FE2D.2080809@gmail.com>

Johnston Jiaa wrote:
> I'm creating a drawing program, like MS Paint in Tkinter.  I bound  
> the <B1-Motion> event to my Canvas object.  The function it's bound  
> to creates an oval at the event's x and y attributes.
>
> This works fine if the user is dragging slowly, but if he does a  
> sudden dragging motion, the ovals are very far apart.  Is there any  
> way to fix this?
>
> Johnston Jiaa
>   
Windows (and I assume other GUIs such as X) don't report every single 
location the mouse was, when it's moving quickly.  So you'll have to 
interpolate a line between the two points and draw a series of ovals.  
This can be seen in Paint if you use the pencil tool and then make 
u-shaped motions.  If you do it fast enough, they'll be a series of 
angled lines, rather than one smooth U.  There may be a way to get 
around this, but you might have to go to the driver level (depending on 
where it's leaving off the points.  The mouse itself might only sample 
its location every few milliseconds, and this may be causing the issue, 
in which case you'd have to update your hardware.)
That being said, you should still post your code, because there may be 
something that's causing the mouse events to be delayed for whatever reason.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From keridee at jayco.net  Wed Dec  5 02:29:51 2007
From: keridee at jayco.net (Tiger12506)
Date: Tue, 4 Dec 2007 20:29:51 -0500
Subject: [Tutor] Button 1 Motion Event
References: <E82B361D-6ED3-47FE-A14C-8643EF714922@gmail.com>
Message-ID: <00ab01c836de$58721410$17fce004@jslaptop>

>From your description, it sounds like the number of ovals placed depends 
only on when the B1-Motion even is sent to your Canvas object. If you want 
these a little more even, you might take the drawing code out of the 
function that's bound to the mouse event, so that whenever you process you a 
mouse event, for example, you append the appropriate information to a list, 
where it can be drawn all at once later. That will take the drawing time out 
of the equation, when it comes to how often the mouse event is called. At 
any rate, it is not likely to do you much good. Windows is allowed to 
process events such as WM_MOUSEMOVE whenever it's convenient for Windows. 
One way I can think of doing this (probably not the best way) is to start a 
timer on the mouse down message, and stop it on mouse up. Since the timer is 
sent messages rather evenly, you can poll the current mouse position in that 
function.

----- Original Message ----- 
From: "Johnston Jiaa" <oclbdk at gmail.com>
To: <tutor at python.org>
Sent: Tuesday, December 04, 2007 7:30 PM
Subject: [Tutor] Button 1 Motion Event


> I'm creating a drawing program, like MS Paint in Tkinter.  I bound
> the <B1-Motion> event to my Canvas object.  The function it's bound
> to creates an oval at the event's x and y attributes.
>
> This works fine if the user is dragging slowly, but if he does a
> sudden dragging motion, the ovals are very far apart.  Is there any
> way to fix this?
>
> Johnston Jiaa
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From rabidpoobear at gmail.com  Wed Dec  5 05:49:02 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 04 Dec 2007 22:49:02 -0600
Subject: [Tutor] [Fwd: Re:  Button 1 Motion Event]
Message-ID: <47562DBE.2080904@gmail.com>

Johnston, please reply on-list.  You have to either use "reply-all" or 
type "tutor at python.org" as a recipient, because messages aren't sent to 
tutor at python.org by default when you click "reply".
Thanks,
-Luke
-------------- next part --------------
An embedded message was scrubbed...
From: Johnston Jiaa <oclbdk at gmail.com>
Subject: Re: [Tutor] Button 1 Motion Event
Date: Tue, 4 Dec 2007 20:50:00 -0500
Size: 3865
Url: http://mail.python.org/pipermail/tutor/attachments/20071204/83cfaa29/attachment.eml 

From oclbdk at gmail.com  Wed Dec  5 06:11:06 2007
From: oclbdk at gmail.com (Johnston Jiaa)
Date: Wed, 5 Dec 2007 00:11:06 -0500
Subject: [Tutor] Tkinter Canvas Saving and Opening
Message-ID: <46F5D6EA-4088-49E0-9FDD-62BA172EFF08@gmail.com>

I know that Tkinter's canvas can output its contents into a  
postscript file, but can that file be used in turn to restore the  
image?  How can I implement this file-saving and opening feature?

From norman at khine.net  Tue Dec  4 15:51:27 2007
From: norman at khine.net (Norman Khine)
Date: Tue, 04 Dec 2007 15:51:27 +0100
Subject: [Tutor] Time module
Message-ID: <4755696F.9090901@khine.net>

Hello,
I am having difficulties in converting the following to display the 
difference that has passed in hours and seconds in a nice way.

from datetime import datetime
now = datetime.now()
posted = date
difference = now - posted

namespace['date'] = date
namespace['posted'] = difference

when I look at the 'posted' namespace I get

23:08:31.454767

What is the best way to split this so that it will show

'23h 08m 31s' ago

or

1d 23h 08m 31s ago

etc..

Thanks

From mail at timgolden.me.uk  Wed Dec  5 09:52:27 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 05 Dec 2007 08:52:27 +0000
Subject: [Tutor] Time module
In-Reply-To: <4755D2FF.2070908@tds.net>
References: <4755A861.9070508@khine.net> <4755D2FF.2070908@tds.net>
Message-ID: <475666CB.20403@timgolden.me.uk>

Kent Johnson wrote:
> Norman Khine wrote:
>> Hello,
>> I am having difficulties in converting the following to display the 
>> difference that has passed in hours and seconds in a nice way.
>>
>> from datetime import datetime
>> now = datetime.now()
>> posted = date
>> difference = now - posted
>>
>> namespace['date'] = date
>> namespace['posted'] = difference
> 
> It would help if you would show complete code - what is date? what is 
> namespace? Anyway, guessing that posted is a datetime.datetime, then 
> difference is a datetime.timedelta.
> 
>> when I look at the 'posted' namespace I get
>>
>> 23:08:31.454767
>>
>> What is the best way to split this so that it will show
>>
>> '23h 08m 31s' ago
> 
> You will have to do some work yourself. difference has attributes days, 
> seconds and microseconds. You can split the seconds into hours, minutes 
> and seconds using % or divmod().
> 
> Kent

Not a 100% match, but to show the kind of thing... have a look at this
code fragment (which I posted a while back to c.l.py).

http://groups.google.com/group/comp.lang.python/msg/40a87d00875f2958

TJG

From rdm at rcblue.com  Wed Dec  5 12:31:43 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 05 Dec 2007 03:31:43 -0800
Subject: [Tutor] Random Number Generator
In-Reply-To: <ea979d70712041441p58438e8ah5e69ba3ec90777cb@mail.gmail.com
 >
References: <mailman.17.1196766006.637.tutor@python.org>
	<419314.69282.qm@web45106.mail.sp1.yahoo.com>
	<ea979d70712041116v45fae3f0ub747833454b2c1fa@mail.gmail.com>
	<fj49r6$3h4$1@ger.gmane.org>
	<ea979d70712041441p58438e8ah5e69ba3ec90777cb@mail.gmail.com>
Message-ID: <20071205113647.024971E4030@bag.python.org>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071205/9d04e883/attachment.htm 

From bhaaluu at gmail.com  Wed Dec  5 13:23:15 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 5 Dec 2007 07:23:15 -0500
Subject: [Tutor] Thanks (was Random Number Generator)
In-Reply-To: <682295.56128.qm@web45101.mail.sp1.yahoo.com>
References: <mailman.8338.1196795507.13604.tutor@python.org>
	<682295.56128.qm@web45101.mail.sp1.yahoo.com>
Message-ID: <ea979d70712050423p75235f2bs42b49d3ce111c23e@mail.gmail.com>

On Dec 4, 2007 7:21 PM, earlylight publishing
<earlylightpublishing at yahoo.com> wrote:
> Thank you everyone for your help!  I have no idea why it never occured to me
> to Google it.  Thanks for the code.  Now let's see if I can get this sucker
> to work!
>

1) Wikipedia  <-- learn a basic vocabulary so you can enter keywords into
2) Google  <-- Feeling Lucky? If that doesn't work, sort through the other 200K
3) Python Tutorials  <-- Get up and going quickly, saving the hard parts for
4) Python Documentation and Books....

And then there's the Python Tutor list! 8^D

Best of luck getting your program working.
If you get stuck, show us your code, and error messages, we'll try to help.
(It also helps to add system info as well as Python version, etc.)
Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

From bhaaluu at gmail.com  Wed Dec  5 13:35:59 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 5 Dec 2007 07:35:59 -0500
Subject: [Tutor] Random Number Generator
In-Reply-To: <20071205113647.024971E4030@bag.python.org>
References: <mailman.17.1196766006.637.tutor@python.org>
	<419314.69282.qm@web45106.mail.sp1.yahoo.com>
	<ea979d70712041116v45fae3f0ub747833454b2c1fa@mail.gmail.com>
	<fj49r6$3h4$1@ger.gmane.org>
	<ea979d70712041441p58438e8ah5e69ba3ec90777cb@mail.gmail.com>
	<20071205113647.024971E4030@bag.python.org>
Message-ID: <ea979d70712050435y7ea420cnf771d8d47aee7b8c@mail.gmail.com>

$ python
>>> help()
help> 'topics'
[snip]
CODEOBJECTS         FRAMES              POWER               TUPLES
[snip]
help> 'POWER'
------------------------------------------------------------------------

  5.4 The power operator

  The power operator binds more tightly than unary operators on its left;
  it binds less tightly than unary operators on its right. The syntax is:

        power    ::=     primary[1] ["**" u_expr[2]]

  Download entire grammar as text.[3]
:

It seems to be case-sensitive Mr. Moores!
When I entered 'power' (like you did), I also got:
help> 'power'
no Python documentation found for 'power'

Try entering: 'POWER'  (all caps, just like in the output).

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m


On Dec 5, 2007 6:31 AM, Dick Moores <rdm at rcblue.com> wrote:
>
>  At 02:41 PM 12/4/2007, bhaaluu wrote:
>
> I'm running the Python 2.4.3 interactive interpreter
>  in a Konsole at a bash prompt:
>
>  $ python
>
>  >>> help
>  Type help() for interactive help, or help(object) for help about object.
>  But look what I get with Python 2.5.1 and Win XP:
>
>  =============================================================
>  >>> help('topics')
>
>  Here is a list of available topics.  Enter any topic name to get more help.
>
>  ASSERTION           DEBUGGING           LITERALS
> SEQUENCEMETHODS2
>  ASSIGNMENT          DELETION            LOOPING             SEQUENCES
>  ATTRIBUTEMETHODS    DICTIONARIES        MAPPINGMETHODS      SHIFTING
>  ATTRIBUTES          DICTIONARYLITERALS  MAPPINGS            SLICINGS
>  AUGMENTEDASSIGNMENT DYNAMICFEATURES     METHODS
> SPECIALATTRIBUTES
>  BACKQUOTES          ELLIPSIS            MODULES
> SPECIALIDENTIFIERS
>  BASICMETHODS        EXCEPTIONS          NAMESPACES          SPECIALMETHODS
>  BINARY              EXECUTION           NONE                STRINGMETHODS
>  BITWISE             EXPRESSIONS         NUMBERMETHODS       STRINGS
>  BOOLEAN             FILES               NUMBERS             SUBSCRIPTS
>  CALLABLEMETHODS     FLOAT               OBJECTS             TRACEBACKS
>  CALLS               FORMATTING          OPERATORS           TRUTHVALUE
>  CLASSES             FRAMEOBJECTS        PACKAGES            TUPLELITERALS
>  CODEOBJECTS         FRAMES              POWER               TUPLES
>  COERCIONS           FUNCTIONS           PRECEDENCE          TYPEOBJECTS
>  COMPARISON          IDENTIFIERS         PRINTING            TYPES
>  COMPLEX             IMPORTING           PRIVATENAMES        UNARY
>  CONDITIONAL         INTEGER             RETURNING           UNICODE
>  CONTEXTMANAGERS     LISTLITERALS        SCOPING
>  CONVERSIONS         LISTS               SEQUENCEMETHODS1
>
>  >>> help('power')
>  no Python documentation found for 'power'
>
>  >>> help('lists')
>  no Python documentation found for 'lists'
>
>  >>> help('classes')
>  no Python documentation found for 'classes'
>
>  >>> help('modules')
>
>  Please wait a moment while I gather a list of all available modules...
>
>
>  Traceback (most recent call last):
>    File "<pyshell#7>", line 1, in <module>
>      help('modules')
>    File "E:\Python25\lib\site.py", line 346, in __call__
>      return pydoc.help(*args, **kwds)
>    File "E:\Python25\lib\pydoc.py", line 1645, in __call__
>      self.help(request)
>    File "E:\Python25\lib\pydoc.py", line 1682, in help
>      elif request == 'modules': self.listmodules()
>    File "E:\Python25\lib\pydoc.py", line 1803, in listmodules
>      ModuleScanner().run(callback)
>    File "E:\Python25\lib\pydoc.py", line 1854, in run
>      for importer, modname, ispkg in pkgutil.walk_packages():
>    File "E:\Python25\lib\pkgutil.py", line 110, in walk_packages
>      __import__(name)
>    File
> "E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg\dmath\__init__.py", line
> 343, in <module>
>  NameError: name 'context' is not defined
>  >>>
>  ============================================================
>  However, getting help for things like random, random.uniform, math, list,
> tuple, works fine.
>
>  For example,
>
>  ============================================
>  >>> help('random.uniform')
>  Help on method uniform in random:
>
>  random.uniform = uniform(self, a, b) method of random.Random instance
>      Get a random number in the range [a, b).
>  >>>
>  ==============================================
>
>  Dick Moores
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From rdm at rcblue.com  Wed Dec  5 13:50:47 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 05 Dec 2007 04:50:47 -0800
Subject: [Tutor] Random Number Generator
In-Reply-To: <ea979d70712050435y7ea420cnf771d8d47aee7b8c@mail.gmail.com>
References: <mailman.17.1196766006.637.tutor@python.org>
	<419314.69282.qm@web45106.mail.sp1.yahoo.com>
	<ea979d70712041116v45fae3f0ub747833454b2c1fa@mail.gmail.com>
	<fj49r6$3h4$1@ger.gmane.org>
	<ea979d70712041441p58438e8ah5e69ba3ec90777cb@mail.gmail.com>
	<20071205113647.024971E4030@bag.python.org>
	<ea979d70712050435y7ea420cnf771d8d47aee7b8c@mail.gmail.com>
Message-ID: <20071205125049.D588D1E4031@bag.python.org>

At 04:35 AM 12/5/2007, bhaaluu wrote:
>It seems to be case-sensitive Mr. Moores!
>When I entered 'power' (like you did), I also got:
>help> 'power'
>no Python documentation found for 'power'
>
>Try entering: 'POWER'  (all caps, just like in the output).

Thanks! I should have tried that.

Dick Moores



From bhaaluu at gmail.com  Wed Dec  5 14:11:33 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 5 Dec 2007 08:11:33 -0500
Subject: [Tutor] This is the online help utility [tutorial].
Message-ID: <ea979d70712050511n66f63070v25077c2d8b3bd628@mail.gmail.com>

Greetings,
Recently a thread about Python's online help utility was buried
within another thread with a different Subject. So I thought I'd
try to summarize that thread within a thread in a thread of its own.
It would be helpful for those running different versions of Python
on differnet systems to contribute their online help experiences
if they differ from what I'm posting. I'm running Python 2.4.3 in
bash, in a Konsole (KDE) running on the Linux 2.6.15 kernel.

1) Starting the Python Interactive Interpreter:

$ python
Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

It says to type "help", so that's what I type:

>>> "help"
'help'

Oops! That doesn't work very well now, does it?

>>> help
Type help() for interactive help, or help(object) for help about object.

Ahhhh! That's better. If I'm new to Python, I probably won't know what
'object' means
in help(object), so maybe 'help()' will be a good start?

 >>> help()

Welcome to Python 2.4!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>

OK! The first thing I notice is that the interactive prompt has changed from
'>>>' to 'help>'.  There is some VERY USEFUL INFORMATION in the splash
text. For example, to get out of the help utility, and return to the
interpreter,
I need to type "quit" <-- it can be typed WITHOUT the quotes!

Three other words are suggested for use here: modules, keywords, and topics.
So now I have four words I can use at the 'help>' prompt to get help:
quit, topics, modules, and keywords.

help> keywords
Here is a list of the Python keywords.  Enter any keyword to get more help.

and                 else                import              raise
assert              except              in                  return
break               exec                is                  try
class               finally             lambda              while
continue            for                 not                 yield
def                 from                or
del                 global              pass
elif                if                  print

help> pass
------------------------------------------------------------------------

  6.4 The pass statement

        pass_stmt        ::=     "pass"

  Download entire grammar as text.[1]
[snip]

On my machine, when the help has ended, END is displayed, and I must
type a "q" to get back to the help prompt.

help> modules

Please wait a moment while I gather a list of all available modules...

ArgImagePlugin      UserList            fpectl              qtxml
ArrayPrinter        UserString          fpformat            quopri
BaseHTTPServer      WalImageFile        ftplib              random
[snip]
Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

help> modules random

Here is a list of matching modules.  Enter any module name to get more help.

random - Random variable generators.
whrandom - Wichman-Hill random number generator.
_random
RNG (package) - x=CreateGenerator(seed) creates an random number
generator stream
RandomArray

Here again, when at the help> prompt, no quotes are necessary around
the words entered.

help> topics
 topics

Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DELETION            LOOPING             SEQUENCES
ASSIGNMENT          DICTIONARIES        MAPPINGMETHODS      SHIFTING
ATTRIBUTEMETHODS    DICTIONARYLITERALS  MAPPINGS            SLICINGS
ATTRIBUTES          DYNAMICFEATURES     METHODS             SPECIALATTRIBUTES
[snip]

help> POWER
------------------------------------------------------------------------

  5.4 The power operator

  The power operator binds more tightly than unary operators on its left;
  it binds less tightly than unary operators on its right. The syntax is:

        power    ::=     primary[1] ["**" u_expr[2]]

  Download entire grammar as text.[3]
[snip]
:

The colon means I can type SPACE for another page, or ARROW key to move a line.
At the end, or at any time, I can type a "q" to return to the help> prompt.

help> quit

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

>>>  Ctrl-D
$

When I quit help(), I'm returned to the Python interpreter's interactive prompt.
The ending message has some useful information in it! Read it!

Ctrl-D returns me to the bash prompt.

I think this summarizes what has been discussed so far?
Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

From hopebassist at yahoo.com  Wed Dec  5 16:30:09 2007
From: hopebassist at yahoo.com (jeff witt)
Date: Wed, 5 Dec 2007 07:30:09 -0800 (PST)
Subject: [Tutor] info, help, guidence,...
Message-ID: <663181.84552.qm@web39815.mail.mud.yahoo.com>

Hello, 
i have some questions about programming in general and python,.. 
my brother (who is a programmer) guides me to ".net" languages,  and i am not too sure why, however, he is getting sick of me pestering him with my questions,..
i like the little i know about python, it seems to be user friendly, however,  i am not finding clear answers about what it does compared to ".net" for example. 
 I really know nothing about programming (which i am sure is obvious) so ANY info would be helpful, ... 

here are a few questions that go through my head...
 how does python get applied to a GUI?  why dont universities teach it? is there an online class i can take for it?  training certificates?   is it accepted in the world of programming professionally?  ( i am interested in a career too, as well as a new hobby),.
  i use linux, and python seems to be everywhere for linux,.. and i read that it works on windows too but is it accepted in "those" circles?  
what is pythons strengths and weaknesses, IE. web/Internet, or program development, operating system things,...   what would you (or you guys) recomend for the first language?  or like my brother says, "just learn something and stop asking me questions"
if python was released in 1991 how long will it remain a current or a applicable language? or i guess i am asking, what is the normal life of a programming language before it is obsolete?

well, like i mentioned, any help or info would be greatly appreciated,   i have been to some of the beginner sites and tried the whole "hello world" thing, and i unfortunately realize i am years from actually contributing to any open source project,  (especially since i am still struggling with the file system in linux [only been using it for 8or9 months])

God bless you  guys, and thank you for your site and willingness to share and help!

jeff






      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071205/907dc8a4/attachment-0001.htm 

From bhaaluu at gmail.com  Wed Dec  5 18:00:02 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 5 Dec 2007 12:00:02 -0500
Subject: [Tutor] info, help, guidence,...
In-Reply-To: <663181.84552.qm@web39815.mail.mud.yahoo.com>
References: <663181.84552.qm@web39815.mail.mud.yahoo.com>
Message-ID: <ea979d70712050900v6cf465d9rf7310e46a707fa0b@mail.gmail.com>

Greetings,

On Dec 5, 2007 10:30 AM, jeff witt <hopebassist at yahoo.com> wrote:
>
> Hello,
> i have some questions about programming in general and python,..
> my brother (who is a programmer) guides me to ".net" languages,  and i am
> not too sure why, however, he is getting sick of me pestering him with my
> questions,..
> i like the little i know about python, it seems to be user friendly,
> however, i am not finding clear answers about what it does compared to
> ".net" for example.
>  I really know nothing about programming (which i am sure is obvious) so ANY
> info would be helpful, ...
>
> here are a few questions that go through my head...
>  how does python get applied to a GUI?

http://wiki.python.org/moin/GuiProgramming
TkInter is Python's "standard" GUI library

> why dont universities teach it? is
> there an online class i can take for it?  training certificates?   is it
> accepted in the world of programming professionally?  ( i am interested in a
> career too, as well as a new hobby),.

Some universities do use Python to teach Computer Science topics.
There are several online tutorials to get you started, for example:
http://docs.python.org/tut/
is the 'official' Python tutorial

>   i use linux, and python seems to be everywhere for linux,.. and i read
> that it works on windows too but is it accepted in "those" circles?
> what is pythons strengths and weaknesses, IE. web/Internet, or program
> development, operating system things,...   what would you (or you guys)
> recomend for the first language?  or like my brother says, "just learn
> something and stop asking me questions"

Python is an excellent first programming language.
The Tutor list is for learning Python as a first programming language.
There seem to be an equal number of Tutors who use Linux or Windows.

> if python was released in 1991 how long will it remain a current or a
> applicable language? or i guess i am asking, what is the normal life of a
> programming language before it is obsolete?

That's a good question!

>
> well, like i mentioned, any help or info would be greatly appreciated,   i
> have been to some of the beginner sites and tried the whole "hello world"
> thing, and i unfortunately realize i am years from actually contributing to
> any open source project,  (especially since i am still struggling with the
> file system in linux [only been using it for 8or9 months])
>
> God bless you  guys, and thank you for your site and willingness to share
> and help!
>
> jeff

There are several excellent tutorials and books online for free.
You'll have to check them out and see which ones 'click' for you.
Each person learns stuff differently, and each writer has a different
'style' of writing, so you might find two tutorials that cover the same
things, but you'll like one better than the other.

This is a good place to ask questions!
Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

From tim at johnsons-web.com  Wed Dec  5 18:01:06 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 5 Dec 2007 08:01:06 -0900
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <002201c8360c$3e1b8ec0$94fce004@jslaptop>
References: <200711300817.38828.tim@johnsons-web.com>
	<4753E186.50705@bigfoot.com>
	<002201c8360c$3e1b8ec0$94fce004@jslaptop>
Message-ID: <200712050801.06957.tim@johnsons-web.com>

On Monday 03 December 2007, Tiger12506 wrote:
> >> ##########################
> >>
> >>>>> s = '/home/test/'
> >>>>> s1 = s.lstrip('/ehmo')
> >>>>> s1
> >>
> >> 'test/'
> >> ##########################
I've been having some problems posting to this list,
so this is also a kind of test:
I just wrote a global lstring
def lstrip(S,chars):
	if S.startswith(chars):
		return S[len(chars):]
	else: return S

It begs for a extension of the string object I guess,
but this (and a corollary rstrip) works for me.
Tim

From taserian at gmail.com  Wed Dec  5 18:49:26 2007
From: taserian at gmail.com (taserian)
Date: Wed, 5 Dec 2007 12:49:26 -0500
Subject: [Tutor] info, help, guidence,...
In-Reply-To: <ea979d70712050900v6cf465d9rf7310e46a707fa0b@mail.gmail.com>
References: <663181.84552.qm@web39815.mail.mud.yahoo.com>
	<ea979d70712050900v6cf465d9rf7310e46a707fa0b@mail.gmail.com>
Message-ID: <70dbc4d40712050949y2a7644a0yeba1b3f0a720b04d@mail.gmail.com>

Sorry if this isn't the right place for it, but today's xkcd comic strip is
very apropos for the newly illuminated in all things Python.

http://www.xkcd.com/

Tony R.

On Dec 5, 2007 12:00 PM, bhaaluu <bhaaluu at gmail.com> wrote:

> Greetings,
>
> On Dec 5, 2007 10:30 AM, jeff witt <hopebassist at yahoo.com> wrote:
> >
> > Hello,
> > i have some questions about programming in general and python,..
> > my brother (who is a programmer) guides me to ".net" languages,  and i
> am
> > not too sure why, however, he is getting sick of me pestering him with
> my
> > questions,..
> > i like the little i know about python, it seems to be user friendly,
> > however, i am not finding clear answers about what it does compared to
> > ".net" for example.
> >  I really know nothing about programming (which i am sure is obvious) so
> ANY
> > info would be helpful, ...
> >
> > here are a few questions that go through my head...
> >  how does python get applied to a GUI?
>
> http://wiki.python.org/moin/GuiProgramming
> TkInter is Python's "standard" GUI library
>
> > why dont universities teach it? is
> > there an online class i can take for it?  training certificates?   is it
> > accepted in the world of programming professionally?  ( i am interested
> in a
> > career too, as well as a new hobby),.
>
> Some universities do use Python to teach Computer Science topics.
> There are several online tutorials to get you started, for example:
> http://docs.python.org/tut/
> is the 'official' Python tutorial
>
> >   i use linux, and python seems to be everywhere for linux,.. and i read
> > that it works on windows too but is it accepted in "those" circles?
> > what is pythons strengths and weaknesses, IE. web/Internet, or program
> > development, operating system things,...   what would you (or you guys)
> > recomend for the first language?  or like my brother says, "just learn
> > something and stop asking me questions"
>
> Python is an excellent first programming language.
> The Tutor list is for learning Python as a first programming language.
> There seem to be an equal number of Tutors who use Linux or Windows.
>
> > if python was released in 1991 how long will it remain a current or a
> > applicable language? or i guess i am asking, what is the normal life of
> a
> > programming language before it is obsolete?
>
> That's a good question!
>
> >
> > well, like i mentioned, any help or info would be greatly appreciated,
> i
> > have been to some of the beginner sites and tried the whole "hello
> world"
> > thing, and i unfortunately realize i am years from actually contributing
> to
> > any open source project,  (especially since i am still struggling with
> the
> > file system in linux [only been using it for 8or9 months])
> >
> > God bless you  guys, and thank you for your site and willingness to
> share
> > and help!
> >
> > jeff
>
> There are several excellent tutorials and books online for free.
> You'll have to check them out and see which ones 'click' for you.
> Each person learns stuff differently, and each writer has a different
> 'style' of writing, so you might find two tutorials that cover the same
> things, but you'll like one better than the other.
>
> This is a good place to ask questions!
> Happy Programming!
> --
> b h a a l u u at g m a i l dot c o m
> http://www.geocities.com/ek.bhaaluu/python/index.html
> _______________________________________________
> 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/20071205/5e5b8e0a/attachment.htm 

From tim at johnsons-web.com  Tue Dec  4 20:36:23 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Tue, 4 Dec 2007 10:36:23 -0900
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <002201c8360c$3e1b8ec0$94fce004@jslaptop>
References: <200711300817.38828.tim@johnsons-web.com>
	<4753E186.50705@bigfoot.com>
	<002201c8360c$3e1b8ec0$94fce004@jslaptop>
Message-ID: <200712041036.23382.tim@johnsons-web.com>

On Monday 03 December 2007, Tiger12506 wrote:
> >> ##########################
> >>
> >>>>> s = '/home/test/'
> >>>>> s1 = s.lstrip('/ehmo')
> >>>>> s1
> >>
> >> 'test/'
> >> ##########################
I've been having some problems posting to this list,
so this is also a kind of test:
I just wrote a global lstring
def lstrip(S,chars):
	if S.startswith(chars):
		return S[len(chars):]
	else: return S

It begs for a extension of the string object I guess,
but this (and a corollary rstrip) works for me.
Tim

From kent37 at tds.net  Wed Dec  5 19:44:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 05 Dec 2007 13:44:55 -0500
Subject: [Tutor] Selecting a browser
In-Reply-To: <475588BE.60909@bigfoot.com>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>	<4755271C.50006@bigfoot.com>	<47552B77.70204@timgolden.me.uk>
	<475588BE.60909@bigfoot.com>
Message-ID: <4756F1A7.4080409@tds.net>

Ricardo Ar?oz wrote:
> The other way to handle it would be to include in the documentation that
> windows paths should have '/' or '\\\\' instead of '\\'.
> The choice would depend on whether the authors consider there is a use
> for the escape character, and what value that escape character might have.

Yes, without any docs it's hard to know whether this is a bug or a feature.

> I've registered in the issue tracker, but got scared and didn't post
> anything. Can I be certain the blokes maintaining this module will see
> it, or should and try contact them directly?

The issue tracker is the best way I know to contact the maintainers.

You might want to post two issues - one for the lack of documentation 
and one for the problem with \. It's very helpful to include any 
suggested fix.

Kent

From kent37 at tds.net  Wed Dec  5 19:59:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 05 Dec 2007 13:59:48 -0500
Subject: [Tutor] info, help, guidence,...
In-Reply-To: <663181.84552.qm@web39815.mail.mud.yahoo.com>
References: <663181.84552.qm@web39815.mail.mud.yahoo.com>
Message-ID: <4756F524.2090607@tds.net>

jeff witt wrote:

> here are a few questions that go through my head...
>  how does python get applied to a GUI?  

There are many possibilities, see
http://wiki.python.org/moin/CategoryPyGUI

Also you can use native window toolkits on Windows and Mac.

> is 
> it accepted in the world of programming professionally?  ( i am 
> interested in a career too, as well as a new hobby),.

Yes.
http://jobsearch.monster.com/Search.aspx?q=python&fn=&lid=&re=130&cy=us&brd=1&JSNONREG=1

>   i use linux, and python seems to be everywhere for linux,.. and i read 
> that it works on windows too but is it accepted in "those" circles? 

Yes

> what is pythons strengths and weaknesses, IE. web/Internet, or program 
> development, operating system things,... 

Pretty much anything except operating systems, device drivers and 
real-time programs:
http://www.python.org/about/apps/

>  what would you (or you guys) 
> recomend for the first language?  or like my brother says, "just learn 
> something and stop asking me questions"

Python, of course!

> if python was released in 1991 how long will it remain a current or a 
> applicable language? or i guess i am asking, what is the normal life of 
> a programming language before it is obsolete?

Python popularity is increasing, by some measures at least:
http://www.tiobe.com/tpci.htm
http://radar.oreilly.com/archives/2007/05/state_of_the_co_10.html

> well, like i mentioned, any help or info would be greatly appreciated,   
> i have been to some of the beginner sites and tried the whole "hello 
> world" thing, and i unfortunately realize i am years from actually 
> contributing to any open source project,  (especially since i am still 
> struggling with the file system in linux [only been using it for 8or9 
> months])

There are quite a few good Python tutorials for non-programmers:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

A good book for a beginner is Dawson's "Python Programming for the 
absolute beginner".

Kent

From brian.wisti at gmail.com  Wed Dec  5 20:18:27 2007
From: brian.wisti at gmail.com (Brian Wisti)
Date: Wed, 5 Dec 2007 11:18:27 -0800
Subject: [Tutor] info, help, guidence,...
In-Reply-To: <663181.84552.qm@web39815.mail.mud.yahoo.com>
References: <663181.84552.qm@web39815.mail.mud.yahoo.com>
Message-ID: <d5506a9f0712051118u3d2468fbx1588a9cbe1a21719@mail.gmail.com>

Hi Jeff,

On Dec 5, 2007 7:30 AM, jeff witt <hopebassist at yahoo.com> wrote:
>
> Hello,
> i have some questions about programming in general and python,..

Welcome! You have a lot of great questions. Tell your brother to relax.

First off, Python is a great first language because it was written
with an eye towards being consistent and easy to learn. It is also a
very powerful language that will continue to be useful for you as your
needs and knowledge expand. I've been using Python since 2000 and it
is still an important part of my development toolkit.

Now for your questions ...

> here are a few questions that go through my head...
>  how does python get applied to a GUI?

Python itself is just a language, and uses libraries for GUI applications.

    * Tkinter [http://www.pythonware.com/library/tkinter/introduction/]
comes with the standard Python distribution, which makes it the
official GUI library.
    * WxPython [http://www.wxpython.org] is a very popular
cross-platform GUI library. It's an extra download, and maybe a little
advanced for somebody who is *just* starting out with programming. But
hey, don't let that stop you.
    * IronPython
[http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython] is
actually a different version of Python written specifically for the
.NET environment. Most of the language features are the same as
CPython (the standard Python you would get from python.org), and in
addition it has full access to the .NET framework including Windows
Forms. It's very powerful, and I've had a lot of fun with it.
    * Jython [http://jython.org] is a version of Python written in
Java. It's a little behind CPython on features, but has full access to
the Java API including Swing.

IronPython and Jython require a bit of setup to get started with, so
they might not be the best choices for your first day. Play with
Tkinter and maybe WxPython for the moment, the other two will be there
when you're interested.

> why dont universities teach it?

They do. MIT is a high profile example. They recently incorporated
Python into their courses.

> is there an online class i can take for it?

Probably, but save your money and go to Google with the phrase "Python
tutorial". You'll be overwhelmed with the amount of instructional
material. Python is fun to write about.

> training certificates?

Yes, but I am not aware of any organizations that care about Python
certification. I've always been asked to show what I know, but never
about certification.

> is it accepted in the world of programming professionally?  ( i am interested in a
> career too, as well as a new hobby),.

Oh my yes. Python is used by companies all over the world. Google and
NASA are especially impressive-sounding examples of organizations that
use Python. Check http://www.python.org/about/success/ for a very long
list of organizations using Python.

>   i use linux, and python seems to be everywhere for linux,.. and i read
> that it works on windows too but is it accepted in "those" circles?

Absolutely. The set of Python users crosses a huge number of operating
systems, including Windows.

> what is pythons strengths and weaknesses, IE. web/Internet, or program
> development, operating system things,...

Python is a very high level language with great library support, and
has been useful for me in every problem domain. A Python application
normally runs slower than an application built in C/C++, so it usually
isn't the first choice for time-critical applications where somebody
could *die*. There are many ways to speed up your Python applications,
though, and it can be used by a knowledgeable developer to create
those time-critical apps.

> what would you (or you guys) recomend for the first language?

Perl! No, that was just a joke. You are asking the Python tutor list
about the best starting language. I think you can guess what the
answer is going to be.

> or like my brother says, "just learn something and stop asking me questions"

Man, tell that guy to switch to decaf. I'd say "just learn something
and keep asking questions"

> if python was released in 1991 how long will it remain a current or a applicable language? or i guess i am asking, what is the normal life of a programming language before it is obsolete?

For a very long time indeed. C is over 30 years old and still being
used for creating new applications. COBOL is about 4 million years old
(give or take a few million) and people still make good money using
it. The Python team has done an excellent job of keeping pace with the
needs of the day, and I don't think Python is going away any time
soon.

>
> well, like i mentioned, any help or info would be greatly appreciated,   i
> have been to some of the beginner sites and tried the whole "hello world"
> thing, and i unfortunately realize i am years from actually contributing to
> any open source project,  (especially since i am still struggling with the
> file system in linux [only been using it for 8or9 months])

Build your knowledge. Search on the Web. Skim the Python docs, even if
you don't understand them at first. I discovered that constantly
exposing myself to Python code made me smarter, even when I didn't
know what the code was doing at the time.

A lot of the questions you will have at this stage can be answered by
two acronyms:

    RTFM: Read The ... umm ... *Fine* Manual
    TIAS: Try It And See!

You can usually answer your "what happens if I do X in Python?"
questions by opening up a Python shell and trying it out. It's helpful
and harmless, as long as you apply a little common sense (don't see
what happens if you delete your home directory, for example). Don't be
timid, be bold. Try It And See!

You can usually answer your "how do I do Y in Python?" questions by
reading the manual or asking a search engine. That happy truth is that
roughly 99% of all questions you will come up with in the next year
have already been asked. If you don't understand the answer you find,
even after applying TIAS, then you find yourself some nice folks (like
this mailing list). Tell them what you were trying to do, and *why*
you were trying to do it (that way people can tell you if there is a
better solution).

>
> God bless you  guys, and thank you for your site and willingness to share
> and help!
>
> jeff

I think you'll find that the folks on this mailing list are incredibly
helpful and patient. You made a great choice by picking Python to
learn and this group to help you.

Kind Regards,

Brian Wisti
http://coolnamehere.com/

From tim at johnsons-web.com  Mon Dec  3 23:51:24 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Mon, 3 Dec 2007 13:51:24 -0900
Subject: [Tutor] Problems with List Server?
In-Reply-To: <200712031316.37287.tim@johnsons-web.com>
References: <200712031316.37287.tim@johnsons-web.com>
Message-ID: <200712031351.24449.tim@johnsons-web.com>

On Monday 03 December 2007, Tim Johnson wrote:
> I appear to be having a weird problem with the List Server.
> At first, email sent to this address did not appear at
> all.
> After contacting the ML maintainers only one email from
> me to this address go through. When I replied to the
> thread which the email started, it was not delivered.
>
> This is a very frustrating turn of events and I am hoping
> that it will be corrected soon. I wonder if anyone else is
> having similar problems?
>
> I suspect that this email will be delivered, but I might not
> be able to send another on the same thread.
>
> Any ideas?
> tim
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

If this is not delivered to the ML, then the problem
persists.
thanks
Tim

From tim at johnsons-web.com  Mon Dec  3 19:29:17 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Mon, 3 Dec 2007 09:29:17 -0900
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <47504A9F.7030704@brunson.com>
References: <200711300817.38828.tim@johnsons-web.com>
	<47504A9F.7030704@brunson.com>
Message-ID: <200712030929.17376.tim@johnsons-web.com>

Trying this again. This list has not be receiving all
of my emails......
==================================
On Friday 30 November 2007, Eric Brunson wrote:
> Tim Johnson wrote:
> > Hello:
> > I'm seeing some strange behavior with lstrip operating
> > on string representations of *nix-style file paths
> >
> > Example:
> >>>> s = '/home/test/'
> >>>> s1 = s.lstrip('/home')
> >>>> s1
> >
> > 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
>
 Hi Folks:
 I actually resent this as a test because I've had problems contacting
 this list. The understanding of it percolated up to my wee little brain
 shortly after the first send (which didn't arrive).
I wrote the following as a solution:
def lstrip(S,chars):
	if S.startswith(chars):
		return S[len(chars):]
	else: return S
and a global rstrip would be an easy corrolary.
Thanks
 

From alan.gauld at btinternet.com  Wed Dec  5 20:37:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 5 Dec 2007 19:37:34 -0000
Subject: [Tutor] info, help, guidence,...
References: <663181.84552.qm@web39815.mail.mud.yahoo.com>
Message-ID: <fj6um9$dvf$1@ger.gmane.org>

"jeff witt" <hopebassist at yahoo.com> wrote

> my brother (who is a programmer) guides me to ".net" languages,

OK, Python is a .NET language too.

> and i am not too sure why,

.NET is the new Microsoft standard and their counter attack on Java.
It offers a language neutral runtime environment that allows you to
write the GUI(user interface) in VB.Net, the database intrerface in
Managed C++ and the algorithms in C# and then link them all
together in a single program. That used to be very hard to do.
.NET offers some other bits too but thats the main advantage IMHO.
(Wikipedia is your friend for all things IT related - try looking up
.NET there)

> i like the little i know about python, it seems to be user friendly,
> however,  i am not finding clear answers about what it does
> compared to ".net" for example.

They are two different things. .NET is an environment for running
programs, rather like a virtual operating system, that runs on the
Windows platform. You can use multiple programming languages
within .NET, including Python.

> here are a few questions that go through my head...
> how does python get applied to a GUI?

Thee are several GUI toolkits, the standard one(ie comes with python)
is Tkinter which in turn is a Python wrapper around the long standing
Tc;/Tk GUI toolkit (Tk=Toolkit). But there are others including the
.NET GUI and Java GUIs(via Jython).

> why dont universities teach it?

Several do, and even more colleges and high schools.
Universities tend to prefer Java because it is more like classical
programming languages and enforces a stricter style of programming
which fits (arguably) better to the University curriculum.

> is there an online class i can take for it?

There are many online tutorials (including mine) and you will find
a list of links on the Python web site under the Non programmers
section.

> training certificates?

Not sure on that one, maybe...

> is it accepted in the world of programming professionally?

Yes there are many companies who use Python - see the python
web site for examples. Google is perhaps the best known but there
are plenty others. It falls under the general heading of scripting
languages and is considered to be on a par with Perl, Tcl, JavaScript,
Lisp and others.

> ( i am interested in a career too, as well as a new hobby),.

Several of the people on this list use Python in their day jobs.
And for some Python is their day job!

>  i use linux, and python seems to be everywhere for linux,..
> and i read that it works on windows too

Yes, Python workls on a multitude of platforms incliuding
the "big three": Unix, Windows, MacOS but also on VAX VMS,
MVS, and several more obscure OS.

> but is it accepted in "those" circles?

Yes, especially by the people who use it there! :-)

> what is pythons strengths and weaknesses,

It is a general purpose scripting language that is easy to learn
and easy to maintain and yet extensible and powerful. Read
the Python web site for a fuller story.

> IE. web/Internet, or program development, operating system
> things,...

I wouldn't write an OS nor anything too close to the hardware
(graphics driver say), but otherwise it can do all of those things
and if you read the archives of this group you will find relative
novices doing all of them.

> what would you (or you guys) recomend for the first language?

Python obviously! :-)

> or like my brother says, "just learn something and stop
> asking me questions"

And to some extent he is right. Once you learn any programming
language its relatively easy to convert to another. The hard bit is
the concepts involved in programming not the details of any
one language.

> if python was released in 1991 how long will it remain a current
> or a applicable language? or i guess i am asking, what is the
> normal life of a programming language before it is obsolete?

COBOL, Lisp, BASIC and ForTran were all invented before 1963
and are all still in regular use. Smalltalk started in 1973 and 
"finalised"
in 1980 and is still a highly influential language. C was invented in
the mid 70's and is still king of OS programming. Java was 1994(?)
and is the current "mainstream" leader.

But I could point to many languages which have come and gone
in the same period: CHILL, Coral, Snoball, PL/1, Modula2, Oberon.
You can still get tools for all of  these but the job market is
vanishingly small. Yet in their day all were mainstream or seen as
rising stars.

So how long depends on how good the language is, how well
it is marketed, and fashion amongst other factors.

> i am years from actually contributing to any open source
> project,

You probably could contribute as a tester or documentation
writer within a few weeks or months. You could be at the stage
of fixing bugs in less than a year. It depends on how much time
you commit...

HTH,


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



From mahesh.mach at gmail.com  Wed Dec  5 22:01:00 2007
From: mahesh.mach at gmail.com (Mahesh N)
Date: Thu, 6 Dec 2007 02:31:00 +0530
Subject: [Tutor] how to accept an integer?
Message-ID: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>

I dun understand the mistake. My aim is to accept an integer number. The
python lookup in IDLE asks for a string object but the interpreter returns
with the following error message. Some one pls explain.
Thank You

PS : I understand that i can do type conversion after getting input thru
raw_input(). But how does input() function work?

>>> prompt="temme a number\n"
>>> speed =input(prompt)

Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    speed =input(prompt)
TypeError: 'str' object is not callable
>>> speed =input("temme a number\n")

Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    speed =input("temme a number\n")
TypeError: 'str' object is not callable
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/efe837b1/attachment.htm 

From brunson at brunson.com  Wed Dec  5 22:07:14 2007
From: brunson at brunson.com (Eric Brunson)
Date: Wed, 05 Dec 2007 14:07:14 -0700
Subject: [Tutor] how to accept an integer?
In-Reply-To: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
Message-ID: <47571302.10905@brunson.com>

Mahesh N wrote:
> I dun understand the mistake. My aim is to accept an integer number. 
> The python lookup in IDLE asks for a string object but the interpreter 
> returns with the following error message. Some one pls explain.
> Thank You
>
> PS : I understand that i can do type conversion after getting input 
> thru raw_input(). But how does input() function work?

Did you read this?

http://docs.python.org/lib/built-in-funcs.html#l2h-40

What do you not understand about it?

>
> >>> prompt="temme a number\n"
> >>> speed =input(prompt)
>
> Traceback (most recent call last):
>   File "<pyshell#56>", line 1, in <module>
>     speed =input(prompt)
> TypeError: 'str' object is not callable
> >>> speed =input("temme a number\n")
>
> Traceback (most recent call last):
>   File "<pyshell#57>", line 1, in <module>
>     speed =input("temme a number\n")
> TypeError: 'str' object is not callable
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From mahesh.mach at gmail.com  Wed Dec  5 22:20:06 2007
From: mahesh.mach at gmail.com (Mahesh N)
Date: Thu, 6 Dec 2007 02:50:06 +0530
Subject: [Tutor] how to accept an integer?
In-Reply-To: <47571302.10905@brunson.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
	<47571302.10905@brunson.com>
Message-ID: <fc1d32f20712051320q2609c152j9fc75135dd9d3f2@mail.gmail.com>

On Dec 6, 2007 2:37 AM, Eric Brunson <brunson at brunson.com> wrote:

> Mahesh N wrote:
> > I dun understand the mistake. My aim is to accept an integer number.
> > The python lookup in IDLE asks for a string object but the interpreter
> > returns with the following error message. Some one pls explain.
> > Thank You
> >
> > PS : I understand that i can do type conversion after getting input
> > thru raw_input(). But how does input() function work?
>
> Did you read this?
>
> http://docs.python.org/lib/built-in-funcs.html#l2h-40
>
> What do you not understand about it?
>
> >
> > >>> prompt="temme a number\n"
> > >>> speed =input(prompt)
> >
> > Traceback (most recent call last):
> >   File "<pyshell#56>", line 1, in <module>
> >     speed =input(prompt)
> > TypeError: 'str' object is not callable
> > >>> speed =input("temme a number\n")
> >
> > Traceback (most recent call last):
> >   File "<pyshell#57>", line 1, in <module>
> >     speed =input("temme a number\n")
> > TypeError: 'str' object is not callable
> >
> >
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
sorry i dint go thru the docs. i thought i will delve into it once i felt
comfortable with the language.
is the new line character not allowed in input() statement ???
cuz i tried it without the new line character and it works fine.
More over i find python to be a little sluggish after having worked with C
and Java. But one thing's for sure. Its damn powerful and a lovely language.
can someone temme where python is most applicable?
server side scripting? am i guessing it right?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/92762aa2/attachment.htm 

From malaclypse2 at gmail.com  Wed Dec  5 22:16:46 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Wed, 5 Dec 2007 16:16:46 -0500
Subject: [Tutor] how to accept an integer?
In-Reply-To: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
Message-ID: <16651e80712051316v682c1b28v206186c3f6ef6d5a@mail.gmail.com>

On Dec 5, 2007 4:01 PM, Mahesh N <mahesh.mach at gmail.com> wrote:
> I dun understand the mistake. My aim is to accept an integer number. The
> python lookup in IDLE asks for a string object but the interpreter returns
> with the following error message. Some one pls explain.
> Thank You
>
>  PS : I understand that i can do type conversion after getting input thru
> raw_input(). But how does input() function work?
>
> >>> prompt="temme a number\n"
> >>> speed =input(prompt)
>
>  Traceback (most recent call last):
>   File "<pyshell#56>", line 1, in <module>
>     speed =input(prompt)
> TypeError: 'str' object is not callable

You have code that you haven't shown us.  My crystal ball tells me
that somewhere above this point you did input = "Some String", thus
shadowing the builtin input function.  Start a new interpreter and try
again and you should find that it works as expected.

As I'm sure you'll hear from others, it really is best to use
raw_input instead.  If you want an integer instead of a string, do
something like this:

speed = int(raw_input(prompt))

That way whatever the user types isn't run as python code, just read
in as a string and then converted into an integer.

-- 
Jerry

From kent37 at tds.net  Wed Dec  5 22:24:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 05 Dec 2007 16:24:48 -0500
Subject: [Tutor] how to accept an integer?
In-Reply-To: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
Message-ID: <47571720.20603@tds.net>

Mahesh N wrote:
> I dun understand the mistake. My aim is to accept an integer number. The 
> python lookup in IDLE asks for a string object but the interpreter 
> returns with the following error message. Some one pls explain.
> Thank You
> 
> PS : I understand that i can do type conversion after getting input thru 
> raw_input(). But how does input() function work?
> 
>  >>> prompt="temme a number\n"
>  >>> speed =input(prompt)
> 
> Traceback (most recent call last):
>   File "<pyshell#56>", line 1, in <module>
>     speed =input(prompt)
> TypeError: 'str' object is not callable
>  >>> speed =input("temme a number\n")

It looks like you have named a string 'input'; this hides the built-in 
'input' function and causes the error you are seeing. Restart IDLE and 
input() should work correctly.

A safer way to accept an integer is to use raw_input() and convert the 
result yourself:

try:
   speed = int(raw_input(prompt))
except ValueError:
   print 'You did not enter an integer'

Kent

From mahesh.mach at gmail.com  Wed Dec  5 22:33:09 2007
From: mahesh.mach at gmail.com (Mahesh N)
Date: Thu, 6 Dec 2007 03:03:09 +0530
Subject: [Tutor] how to accept an integer?
In-Reply-To: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
Message-ID: <fc1d32f20712051333i18df30efqaeff082d7dc77f71@mail.gmail.com>

On Dec 6, 2007 2:31 AM, Mahesh N <mahesh.mach at gmail.com> wrote:

> I dun understand the mistake. My aim is to accept an integer number. The
> python lookup in IDLE asks for a string object but the interpreter returns
> with the following error message. Some one pls explain.
> Thank You
>
> PS : I understand that i can do type conversion after getting input thru
> raw_input(). But how does input() function work?
>
> >>> prompt="temme a number\n"
> >>> speed =input(prompt)
>
> Traceback (most recent call last):
>   File "<pyshell#56>", line 1, in <module>
>     speed =input(prompt)
> TypeError: 'str' object is not callable
> >>> speed =input("temme a number\n")
>
> Traceback (most recent call last):
>   File "<pyshell#57>", line 1, in <module>
>     speed =input("temme a number\n")
> TypeError: 'str' object is not callable
>
>
>
>
absolutely, i went up the shell and found out that i had declared a variable
named input and it was shadowing the input() function. i restarted the shell
and now everything's fine.
Thanks Everyone.




-- 
The Place where I Come from,
We Face our Enemies,
If our enemy is Unarmed,
We Offer our SWORD!!!


Courtesy "Warrior Within"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/c19634b8/attachment.htm 

From bryan.fodness at gmail.com  Wed Dec  5 22:46:20 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Wed, 5 Dec 2007 16:46:20 -0500
Subject: [Tutor] how to accept an integer?
In-Reply-To: <16651e80712051316v682c1b28v206186c3f6ef6d5a@mail.gmail.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
	<16651e80712051316v682c1b28v206186c3f6ef6d5a@mail.gmail.com>
Message-ID: <fbf64d2b0712051346g66bdbf1en2da0af82f55eb76c@mail.gmail.com>

On Dec 5, 2007 4:16 PM, Jerry Hill <malaclypse2 at gmail.com> wrote:

> On Dec 5, 2007 4:01 PM, Mahesh N <mahesh.mach at gmail.com> wrote:
> > I dun understand the mistake. My aim is to accept an integer number. The
> > python lookup in IDLE asks for a string object but the interpreter
> returns
> > with the following error message. Some one pls explain.
> > Thank You
> >
> >  PS : I understand that i can do type conversion after getting input
> thru
> > raw_input(). But how does input() function work?
> >
> > >>> prompt="temme a number\n"
> > >>> speed =input(prompt)
> >
> >  Traceback (most recent call last):
> >   File "<pyshell#56>", line 1, in <module>
> >     speed =input(prompt)
> > TypeError: 'str' object is not callable
>
> You have code that you haven't shown us.  My crystal ball tells me
> that somewhere above this point you did input = "Some String", thus
> shadowing the builtin input function.  Start a new interpreter and try
> again and you should find that it works as expected.
>
> As I'm sure you'll hear from others, it really is best to use
> raw_input instead.  If you want an integer instead of a string, do
> something like this:
>
> speed = int(raw_input(prompt))


Is this how ALL known integers should be input?


>
>
> That way whatever the user types isn't run as python code, just read
> in as a string and then converted into an integer.
>
> --
> Jerry
>  _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071205/ea462d57/attachment.htm 

From kent37 at tds.net  Wed Dec  5 22:58:33 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 05 Dec 2007 16:58:33 -0500
Subject: [Tutor] how to accept an integer?
In-Reply-To: <fbf64d2b0712051346g66bdbf1en2da0af82f55eb76c@mail.gmail.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>	<16651e80712051316v682c1b28v206186c3f6ef6d5a@mail.gmail.com>
	<fbf64d2b0712051346g66bdbf1en2da0af82f55eb76c@mail.gmail.com>
Message-ID: <47571F09.3010603@tds.net>

Bryan Fodness wrote:
>     speed = int(raw_input(prompt))
> 
>  
> Is this how ALL known integers should be input?

Yes, with probably a try/except block and a while loop around it to 
handle invalid input.

There are two good reasons for doing this instead of using input:
- it guarantees that the input is in fact an integer (raises ValueError 
otherwise)
- it protects against malicious input (you can do a lot of damage in an 
input(), whatever you type is eval'ed)

For input of unknown integers, you are on your own, Python does not have 
anything built-in for that ;-)

Kent

From malaclypse2 at gmail.com  Wed Dec  5 22:58:42 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Wed, 5 Dec 2007 16:58:42 -0500
Subject: [Tutor] how to accept an integer?
In-Reply-To: <fbf64d2b0712051346g66bdbf1en2da0af82f55eb76c@mail.gmail.com>
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
	<16651e80712051316v682c1b28v206186c3f6ef6d5a@mail.gmail.com>
	<fbf64d2b0712051346g66bdbf1en2da0af82f55eb76c@mail.gmail.com>
Message-ID: <16651e80712051358i6ffad57fsa52fc2e0b53f94ec@mail.gmail.com>

On Dec 5, 2007 4:46 PM, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> On Dec 5, 2007 4:16 PM, Jerry Hill <malaclypse2 at gmail.com> wrote:
> > speed = int(raw_input(prompt))
>
>
> Is this how ALL known integers should be input?

I don't think I understand the question.  If you are prompting your
user to enter an integer from the console, then yes, this is the
general way you should do it, probably wrapped in a try/except block.

You certainly don't have to do it all in one line like that.  Instead,
you could split it up into component parts, like this:

prompt = "Please enter a number between 1 and 10:\n"
user_input = raw_input(prompt)
try:
    user_number = int(user_input)
except ValueError:
    print "You did not enter a number."

-- 
Jerry

From geek_show at dsl.pipex.com  Wed Dec  5 23:43:20 2007
From: geek_show at dsl.pipex.com (andy)
Date: Wed, 05 Dec 2007 22:43:20 +0000
Subject: [Tutor] Best way of learning
Message-ID: <47572988.6000403@dsl.pipex.com>

Dear Pythonistas

Over a year ago I dabbled in learning Python, working my way through a 
few tutorials, the Deitel's  "How to program in Python" and Hetland's 
"Practical Python", until I came across the OOP sections. My mind just 
froze up, and I found myself wondering if I had really understood 
anything at all. In addition to which I didn't have any "itch" that I 
needed to scratch so was trying to learn something without any purpose. 
So I stopped.

In the interim however I did have a few occasions to write programs and 
scripts for my GNU/Linux system to do the odd thing here and there, a 
few conversion programs and calculators. I found myself going back to 
the books and trying to figure it out again, and am proud to say that I 
have a few programs now that are probably not elegant nor the most 
efficient or stylish, but do the job.

This has re-awakened my interest in programming and as I am going back 
to basics again I am conscious that I want to approach the matter 
differently. I *don't* work in a programming environment, nor am I 
likely to ever get into development, although would be interested in 
learning ethical hacking (the idea just interests me - too many 
espionage movies as a kid I guess).

I am happy to read, and have done a fair amount, but am concerned about 
getting too overwhelmed and confused again. I acknowledge and realise 
the value of practising by scripting programs and enjoy the intellectual 
challenge of the debugging process, and trying to think through the 
trick of a particular way of cracking a problem.

So, after this long-winded introduction, I was hoping to pick the wisdom 
of this list to get some pointers of what to do/not to do to make the 
most effective use of the few hours I have to learn how to program using 
Python. So, any advice for someone in their mid-40s who would like to 
learn Python in a more methodical and effective manner?

Thanks in anticipation.

Andy


-- 

"If they can get you asking the wrong questions, they don't have to worry about the answers." - Thomas Pynchon, "Gravity's Rainbow"


From kent37 at tds.net  Wed Dec  5 14:03:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 05 Dec 2007 08:03:05 -0500
Subject: [Tutor] xkcd on Python
Message-ID: <4756A189.3020700@tds.net>

http://xkcd.com/353/

:-)

Kent


From alan.gauld at btinternet.com  Thu Dec  6 00:41:57 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 5 Dec 2007 23:41:57 -0000
Subject: [Tutor] how to accept an integer?
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com>
Message-ID: <fj7d0d$hr$1@ger.gmane.org>


"Mahesh N" <mahesh.mach at gmail.com> wrote


> PS : I understand that i can do type conversion after getting input 
> thru
> raw_input(). But how does input() function work?
>
>>>> prompt="temme a number\n"
>>>> speed =input(prompt)
>
> Traceback (most recent call last):
>  File "<pyshell#56>", line 1, in <module>
>    speed =input(prompt)
> TypeError: 'str' object is not callable

This suggests that you have a variable somewhere called input
that is hiding the function. Try doing del(input)
and try it again.

As to what input does; it evaluates whatever string you give
to it so if your user types in some malicious Python code
input will execute it. For that reason input is usually frowned
on as a security risk and int(raw_input()) is preferred.

HTH,

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



From bhaaluu at gmail.com  Thu Dec  6 00:50:04 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 5 Dec 2007 18:50:04 -0500
Subject: [Tutor] Best way of learning
In-Reply-To: <47572988.6000403@dsl.pipex.com>
References: <47572988.6000403@dsl.pipex.com>
Message-ID: <ea979d70712051550j3339607bib59c17889a8d44cf@mail.gmail.com>

On Dec 5, 2007 5:43 PM, andy <geek_show at dsl.pipex.com> wrote:
> Dear Pythonistas
>
[snip]
>
> So, after this long-winded introduction, I was hoping to pick the wisdom
> of this list to get some pointers of what to do/not to do to make the
> most effective use of the few hours I have to learn how to program using
> Python. So, any advice for someone in their mid-40s who would like to
> learn Python in a more methodical and effective manner?
>
> Thanks in anticipation.
>
> Andy

It sounds to me like a good book or two would be just the thing for you.
May I suggest:
Learning Python by Mark Lutz
and
Programming Python Third Edition by the same author.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

From alan.gauld at btinternet.com  Thu Dec  6 00:51:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 5 Dec 2007 23:51:59 -0000
Subject: [Tutor] how to accept an integer?
References: <fc1d32f20712051301p1917c7cema6fa45fd6c7b8e5d@mail.gmail.com><47571302.10905@brunson.com>
	<fc1d32f20712051320q2609c152j9fc75135dd9d3f2@mail.gmail.com>
Message-ID: <fj7dj7$27h$1@ger.gmane.org>

"Mahesh N" <mahesh.mach at gmail.com> wrote

> More over i find python to be a little sluggish after having worked 
> with C
> and Java.

If you translate C or Java code into python you will usually
get a less than optimal implementation. Python should be
barely slower than Java and often faster. Compared to
C - yes there is a slow-down.

But even in C you can use tools like Psycho and Pyrex to
speed up critical sections to near C speeds if the problem fits.
Or rewrite the critical section in C and wrap it as a module
using SWIG. Thats how most of the performance ritical modules
in the library are written. Where the major bottleneck is I/O
work like database disk access or GUI or network sockets
then you should find Python fast enough.

> can someone temme where python is most applicable?
> server side scripting? am i guessing it right?

Python has been used in almost every form of programming
from image processing and database manipulation to games
programming and web server development. Do a search on
Source Forge for projects using Python for an example of
the variety.

I'd avoid operating systems, device drivers and hard real-time
applications though.


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



From ricaraoz at gmail.com  Thu Dec  6 03:09:05 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 05 Dec 2007 23:09:05 -0300
Subject: [Tutor] Mail? What's that?
Message-ID: <475759C1.4010507@bigfoot.com>

So I eventually got to sending mail with python.
Some articles, trying and google led me to this script:

import smtplib
import time

date = time.ctime(time.time( ))
>From = 'mymail at gmail.com'
To = ['othermail at hotmail.com', 'YetOtherMail at yahoo.com']
Subj = 'Hi'
text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n'
                         % (From, ';'.join(To), date, Subj))

s = smtplib.SMTP('smtp.gmail.com')
s.set_debuglevel(1)
s.ehlo()
s.starttls()
s.ehlo()
s.login('foo', 'bar')
s.sendmail(From, To, text)
s.close()


So, if there's someone who really knows this stuff in the neighborhood
I'd like to ask a couple of questions.
What is ehlo and why do I have to call it twice? And set_debuglevel?
If I where to connect through other smtp server the sequence would be
the exactly the same, say yahoo or hotmail?
Are From: To: Date: and Subject: mandatory in the contents of the
email(text)?  Do I have to put "real" address in  From when calling
sendmail()? And in the contents?
Ok, if someone can answer these I'll be grateful.

TIA

Ricardo



From rabidpoobear at gmail.com  Thu Dec  6 06:38:39 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 05 Dec 2007 23:38:39 -0600
Subject: [Tutor] Button 1 Motion Event
In-Reply-To: <13E13535-E238-4CDE-B18F-E1BDFB324A5F@gmail.com>
References: <E82B361D-6ED3-47FE-A14C-8643EF714922@gmail.com>
	<4755FE2D.2080809@gmail.com>
	<88BD3626-5136-4424-9FC7-DCB511C383CC@gmail.com>
	<47562D7E.8070300@gmail.com>
	<13E13535-E238-4CDE-B18F-E1BDFB324A5F@gmail.com>
Message-ID: <47578ADF.40108@gmail.com>

Johnston Jiaa wrote:
>
>> Just don't distinguish between quick and slow drags.  Just keep a 
>> temporary variable that has the previous mouse position, and draw 
>> ovals from there to the current mouse position every time your 
>> function is called.
>
> I now have the variable with the previous mouse position.  How would I 
> draw ovals from the current mouse position to that previous mouse 
> position?  I tried reasoning it out with a for-loop, but I couldn't 
> figure out how to do it.
Well, try reasoning it out with mathematics.
Suppose we have the points (0,0) and (100,100).
What's the slope between these two points?
well, delta-Y is 100 and delta-X is 100, and 100/100 == 1.
This is also the same as 1/1.
Therefore, for every new point we want to get, we'll add 1 to the x 
value and 1 to the y value.

Now assume we have the points (23, 45) and (45, 80).
This slope would be:
80 - 45
---------
45 - 23
or  35 / 22.
So as you can see, the number on the top is larger than the number on 
the bottom, so our Y-value is increasing more quickly.
But it doesn't really matter which value is bigger, the numerator or the 
denominator.
All we care about is the slope.  Because slope tells us: this is the 
change in Y for every change in X.
The reason slope tells us this is because slope is the ratio between the 
change in Y between our 2 points
and the change in X between our 2 points.
Because it's a ratio, it can be applied to any measure, even to 
deltaX=1, which gives us what deltaY is.
Since we don't care about any X-coordinates between integers, we don't 
care about any other deltaX measurement.

So you'd do something like this:
x = 23.0 # our first points
y = 45.0 # they're float so we can add partial amounts to them.
slope = 35/22.0 # this is float to force float division.
for deltax in range(23, 45):
    x += deltax
    y += slope

So in this case, each time through the loop, X will move 1 over, and Y 
will move slightly more than 1 up.

This still has a problem if the slope is very great in the Y-direction.
Given the case of the points (0,0) and (1,100),
we get a slope of 100.  Thus, we will draw points at 0,0 and at 1,100 
and none in-between,
when realistically we'd like at least a vertical line between them, or 
preferably one that shifts one pixel over halfway-up.

Note that the poitns (0,0) and (100, 1) would not create a problem.  
This is because our delta-x is changing at a set rate,
and our deltay is a smaller number.  It would work in this case.

What's creating the problem is that our slope is greater than 1, and 
we're using delta-x as a fixed amount.
If we add the condition that we affix delta-x to the value 1 for slopes 
less than 1, and delta-y to 1 when slopes are greater than 1,
then everything should work out perfectly.  The case of slope == 1 will 
be correctly handled in either case, just make sure to include it in one 
of them.

Thusly, our code would look something like this:

point1x, point1y = raw_input("please input the first pair of coordinates 
separated by a space: ").split(' ')
point2x, point2y = raw_input("please input the second pair of 
coordinates separated by a space: ").split(' ')

slope = (point2y - point1y) / (float(point2x - point1x))
if slope > 1:
    deltax = 1 / slope # i assume we invert slope here?
    deltay = 1
else:
    deltax = 1
    deltay = slope

currentx = float(point1x)
currenty = float(point1y)
for x in range(max((point2y - point1y), (point2x - point1x)) ):
    #we choose our range as the larger of the two lengths.
    #thus if delta-x is only 1px and delta-y is 100px, we'll
    #still draw all those points in between.

    # ..........
    #  draw the currentx, currenty point here
    # .........
    currentx += deltax
    currenty += deltay

# and draw the point one more time here, to get your ending point.




Note that I don't profess that either my code or my math is correct; I 
didn't test any of this, it's more to give you an idea of how to 
approach Computer Science problems.

>
> Also, I need to be able to save the canvas drawing.  Would it be 
> possible to write some sort of data to a file that could be used to 
> load the previously saved drawing back onto the canvas?
You can just keep a cache of all points and redraw them on load, or you 
can dump it out to an image file.  I believe TKInter supports that, but 
I haven't used that library in a long time.

Again, _please reply on-list_ unless you want a discussion to be 
private, in which case specify in the e-mail so we know it wasn't an 
accident.
-Luke


From earlylightpublishing at yahoo.com  Thu Dec  6 06:44:09 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Wed, 5 Dec 2007 21:44:09 -0800 (PST)
Subject: [Tutor] While Loops and Modules
In-Reply-To: <mailman.8588.1196898157.13604.tutor@python.org>
Message-ID: <555764.37796.qm@web45105.mail.sp1.yahoo.com>

Hello again to all the wonderfully helpful folks on this list.  Today I did my Google homework and I found this neat bit of code for a countdown timer.
   
  import time
import threading
class Timer(threading.Thread):
    def __init__(self, seconds):
        self.runTime = seconds
        threading.Thread.__init__(self)
    def run(self):
        time.sleep(self.runTime)
        print "Buzzz!!! Time's up!"
  t = Timer(30)
t.start()
   
  I don't understand large chunks of it (don't know what threading, self, or __init__ mean) but that's not important at the moment.  It works and I will learn the vocab eventually.
   
  I also wrote this bit of code for a math challenge which comes in the next part of my game.
   
  import random
startNum = random.choice(range(1, 9))
newNum = startNum + 7
score = 0
print 'Start with the number ', startNum, '.  Then continuously add 7 to that number until the timer runs out.  You have 30 seconds.'
        
answer = int(raw_input('Enter your answer: '))
  if newNum == answer:
    print 'That is correct!  Keep going.'
    score = score + 5
    print 'Your score is ', score
else:
    print 'That is incorrect.  Please try again.'
   
  I understand this part just fine 'cause I actually wrote it myself.  
   
  What I need to do now is put these two parts together so that the player will keep adding 7 to the starting number for 30 seconds then the loop breaks.  I know I need a loop of some sort and I'm guessing it's a 'while' sort of thing.  I couldn't find what I was looking for when I Googled.  I'm not even sure I knew the right search terms.  Does anyone know how I'd combine these two modules to make it work?

       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071205/e265b7d9/attachment.htm 

From rabidpoobear at gmail.com  Thu Dec  6 06:47:32 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 05 Dec 2007 23:47:32 -0600
Subject: [Tutor] Mail? What's that?
In-Reply-To: <475759C1.4010507@bigfoot.com>
References: <475759C1.4010507@bigfoot.com>
Message-ID: <47578CF4.4040609@gmail.com>

Ricardo Ar?oz wrote:
> So I eventually got to sending mail with python.
> Some articles, trying and google led me to this script:
>
> import smtplib
> import time
>
> date = time.ctime(time.time( ))
> >From = 'mymail at gmail.com'
> To = ['othermail at hotmail.com', 'YetOtherMail at yahoo.com']
> Subj = 'Hi'
> text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n'
>                          % (From, ';'.join(To), date, Subj))
>
> s = smtplib.SMTP('smtp.gmail.com')
> s.set_debuglevel(1)
> s.ehlo()
> s.starttls()
> s.ehlo()
> s.login('foo', 'bar')
> s.sendmail(From, To, text)
> s.close()
>
>
> So, if there's someone who really knows this stuff in the neighborhood
> I'd like to ask a couple of questions.
> What is ehlo and why do I have to call it twice? And set_debuglevel?
> If I where to connect through other smtp server the sequence would be
> the exactly the same, say yahoo or hotmail?
> Are From: To: Date: and Subject: mandatory in the contents of the
> email(text)?  Do I have to put "real" address in  From when calling
> sendmail()? And in the contents?
> Ok, if someone can answer these I'll be grateful.
>
> TIA
>
> Ricardo
>   
Ricardo -
I say this in the nicest way possible, but did you RTFM? :)
Python has built-in help support on modules.
You should start there, do some Googling, and if you're stumped, get 
some help.  Not for any other reason than it'll probably get you 1) more 
experience at navigating the docs, and 2) a quicker, probably more 
detailed response.

So using Help, we get:


 >>> import smtplib
 >>> help(smtplib)
Help on module smtplib:

NAME
    smtplib - SMTP/ESMTP client class.

FILE
    c:\python24\lib\smtplib.py

[snip 10 pages of documentation]


 >>> help(smtplib.SMTP.set_debuglevel)
Help on method set_debuglevel in module smtplib:

set_debuglevel(self, debuglevel) unbound smtplib.SMTP method
    Set the debug output level.
   
    A non-false value results in debug messages for connection and for all
    messages sent to and received from the server.

 >>> help(smtplib.SMTP.ehlo)
Help on method ehlo in module smtplib:

ehlo(self, name='') unbound smtplib.SMTP method
    SMTP 'ehlo' command.
    Hostname to send for this command defaults to the FQDN of the local
    host.

 >>> help(smtplib.SMTP.sendmail)
Help on method sendmail in module smtplib:

sendmail(self, from_addr, to_addrs, msg, mail_options=[], 
rcpt_options=[]) unbound smtplib.SMTP method
    This command performs an entire mail transaction.
   
    The arguments are:
        - from_addr    : The address sending this mail.
        - to_addrs     : A list of addresses to send this mail to.  A bare
                         string will be treated as a list with 1 address.
        - msg          : The message to send.
        - mail_options : List of ESMTP options (such as 8bitmime) for the
                         mail command.
        - rcpt_options : List of ESMTP options (such as DSN commands) for
                         all the rcpt commands.
   
    If there has been no previous EHLO or HELO command this session, this
    method tries ESMTP EHLO first.  If the server does ESMTP, message size
    and each of the specified options will be passed to it.  If EHLO
    fails, HELO will be tried and ESMTP options suppressed.
   
    This method will return normally if the mail is accepted for at least
    one recipient.  It returns a dictionary, with one entry for each
    recipient that was refused.  Each entry contains a tuple of the SMTP
    error code and the accompanying error message sent by the server.
   
    This method may raise the following exceptions:
   
     SMTPHeloError          The server didn't reply properly to
                            the helo greeting.
     SMTPRecipientsRefused  The server rejected ALL recipients
                            (no mail was sent).
     SMTPSenderRefused      The server didn't accept the from_addr.
     SMTPDataError          The server replied with an unexpected
                            error code (other than a refusal of
                            a recipient).
   
    Note: the connection will be open even after an exception is raised.
   
    Example:
   
     >>> import smtplib
     >>> s=smtplib.SMTP("localhost")
     >>> 
tolist=["one at one.org","two at two.org","three at three.org","four at four.org"]
     >>> msg = '''\
     ... From: Me at my.org
     ... Subject: testin'...
     ...
     ... This is a test '''
     >>> s.sendmail("me at my.org",tolist,msg)
     { "three at three.org" : ( 550 ,"User unknown" ) }
     >>> s.quit()
   
    In the above example, the message was accepted for delivery to three
    of the four addresses, and one was rejected, with the error code
    550.  If all addresses are accepted, then the method will return an
    empty dictionary.

 >>>




So mess around in the built-in docs, then check python.org's docs, and 
let us know what you find :)
Also, try experimenting! pass it stuff that you don't think will work 
just to see if maybe it does :D
-Luke

From remco at gerlich.nl  Thu Dec  6 10:15:02 2007
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 6 Dec 2007 10:15:02 +0100
Subject: [Tutor] Best way of learning
In-Reply-To: <47572988.6000403@dsl.pipex.com>
References: <47572988.6000403@dsl.pipex.com>
Message-ID: <7ae3ca10712060115r34a7fa33q32a5902fdd0af1b@mail.gmail.com>

On Dec 5, 2007 11:43 PM, andy <geek_show at dsl.pipex.com> wrote:

> So, after this long-winded introduction, I was hoping to pick the wisdom
> of this list to get some pointers of what to do/not to do to make the
> most effective use of the few hours I have to learn how to program using
> Python. So, any advice for someone in their mid-40s who would like to
> learn Python in a more methodical and effective manner?
>

In my opinion, the best way to learn _anything_ is to try to do it, and then
look around for tips every now and then in the mean time. You'll connect
much more easily with the information when it's something you've recently
struggled with. And practice is the most important part of any learning
anyway.

So, what do you want to do with Python? Any other hobbies you can connect it
with? Perhaps ideas for a dynamic web site or something?

In my experience, learning something just for abstract knowledge can be fun
for a while, but it's hard to stay committed. And there's nothing wrong with
that, there's only so many hours in a day, and the things you actually use
in life should probably take precedence :-)

So if you've written small tools, feel like expanding them? Used modules in
them that you don't entirely understand yet, perhaps dive into their docs?

Perhaps the Python Challenge ( http://www.pythonchallenge.com/ ) is
something for you? It's at least sideways a little into the hacking spirit,
it's fun, and it's a tour of what Python can do - but you'll have to find
the way yourself :-)

Remco Gerlich
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/8eafc022/attachment-0001.htm 

From remco at gerlich.nl  Thu Dec  6 10:18:04 2007
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 6 Dec 2007 10:18:04 +0100
Subject: [Tutor] Problems with List Server?
In-Reply-To: <200712031351.24449.tim@johnsons-web.com>
References: <200712031316.37287.tim@johnsons-web.com>
	<200712031351.24449.tim@johnsons-web.com>
Message-ID: <7ae3ca10712060118x4d5024cdpdbd90d26bb3e2767@mail.gmail.com>

It arrived.

Since you appear to be the only one reporting the problem, perhaps it's
something on your end?

Remco Gerlich

On Dec 3, 2007 11:51 PM, Tim Johnson <tim at johnsons-web.com> wrote:

> On Monday 03 December 2007, Tim Johnson wrote:
> > I appear to be having a weird problem with the List Server.
> > At first, email sent to this address did not appear at
> > all.
> > After contacting the ML maintainers only one email from
> > me to this address go through. When I replied to the
> > thread which the email started, it was not delivered.
> >
> > This is a very frustrating turn of events and I am hoping
> > that it will be corrected soon. I wonder if anyone else is
> > having similar problems?
> >
> > I suspect that this email will be delivered, but I might not
> > be able to send another on the same thread.
> >
> > Any ideas?
> > tim
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> If this is not delivered to the ML, then the problem
> persists.
> thanks
> Tim
> _______________________________________________
> 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/20071206/d550884f/attachment.htm 

From mail at timgolden.me.uk  Thu Dec  6 11:07:23 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 06 Dec 2007 10:07:23 +0000
Subject: [Tutor] Selecting a browser
In-Reply-To: <475588BE.60909@bigfoot.com>
References: <47500600.3050204@bigfoot.com>	<475244A3.10406@groktech.org>	<47540258.4010204@bigfoot.com>	<4754AC7A.6070909@groktech.org>	<4754DCE8.4070005@bigfoot.com>	<47551D94.8070501@timgolden.me.uk>	<4755271C.50006@bigfoot.com>	<47552B77.70204@timgolden.me.uk>
	<475588BE.60909@bigfoot.com>
Message-ID: <4757C9DB.8090401@timgolden.me.uk>

Ricardo Ar?oz wrote:
> I've registered in the issue tracker, but got scared and didn't post
> anything. 

Don't be scared: just post up what you think is wrong as clearly
as possible. If you can reasonably provide a patch, do so. Otherwise,
just make it clear what's going on. Even if no-one picks it up, at
least you've done what you should have. (Sometimes these things wait
years until someone comes along who has the time, knowledge and
inclination to fix it!).

If you do post, I'll take a look and make sure it makes sense.
(If I have time, I'll provide a patch but I may not be able to).

TJG

From ricaraoz at gmail.com  Thu Dec  6 12:12:39 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 06 Dec 2007 08:12:39 -0300
Subject: [Tutor] Mail? What's that?
In-Reply-To: <47578CF4.4040609@gmail.com>
References: <475759C1.4010507@bigfoot.com> <47578CF4.4040609@gmail.com>
Message-ID: <4757D927.9060103@bigfoot.com>

Luke Paireepinart wrote:
> Ricardo Ar?oz wrote:
>> So I eventually got to sending mail with python.
>> Some articles, trying and google led me to this script:
>>
>> import smtplib
>> import time
>>
>> date = time.ctime(time.time( ))
>> >From = 'mymail at gmail.com'
>> To = ['othermail at hotmail.com', 'YetOtherMail at yahoo.com']
>> Subj = 'Hi'
>> text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n'
>>                          % (From, ';'.join(To), date, Subj))
>>
>> s = smtplib.SMTP('smtp.gmail.com')
>> s.set_debuglevel(1)
>> s.ehlo()
>> s.starttls()
>> s.ehlo()
>> s.login('foo', 'bar')
>> s.sendmail(From, To, text)
>> s.close()
>>
>>
>> So, if there's someone who really knows this stuff in the neighborhood
>> I'd like to ask a couple of questions.
>> What is ehlo and why do I have to call it twice? And set_debuglevel?
>> If I where to connect through other smtp server the sequence would be
>> the exactly the same, say yahoo or hotmail?
>> Are From: To: Date: and Subject: mandatory in the contents of the
>> email(text)?  Do I have to put "real" address in  From when calling
>> sendmail()? And in the contents?
>> Ok, if someone can answer these I'll be grateful.
>>
>> TIA
>>
>> Ricardo
>>   
> Ricardo -
> I say this in the nicest way possible, but did you RTFM? :)

LOL, my apologies Luke. You see, I was bloody tired last night, had just
found out how to do it and didn?t have it in me to google for it or
RTFM, so I said "let's ask the guys". Sorry, and thanks a lot for taking
the time to answer me. I'm just rushing out to work so I'll take a look
tonight and see if I get it, I'm net impaired you see, and when they
start with all those acronyms my brain stops :-)
Thanks again.

Ricardo

> Python has built-in help support on modules.
> You should start there, do some Googling, and if you're stumped, get
> some help.  Not for any other reason than it'll probably get you 1) more
> experience at navigating the docs, and 2) a quicker, probably more
> detailed response.
> 
> So using Help, we get:
> 
> 
>>>> import smtplib
>>>> help(smtplib)
> Help on module smtplib:
> 
> NAME
>    smtplib - SMTP/ESMTP client class.
> 
> FILE
>    c:\python24\lib\smtplib.py
> 
> [snip 10 pages of documentation]
> 
> 
>>>> help(smtplib.SMTP.set_debuglevel)
> Help on method set_debuglevel in module smtplib:
> 
> set_debuglevel(self, debuglevel) unbound smtplib.SMTP method
>    Set the debug output level.
>      A non-false value results in debug messages for connection and for all
>    messages sent to and received from the server.
> 
>>>> help(smtplib.SMTP.ehlo)
> Help on method ehlo in module smtplib:
> 
> ehlo(self, name='') unbound smtplib.SMTP method
>    SMTP 'ehlo' command.
>    Hostname to send for this command defaults to the FQDN of the local
>    host.
> 
>>>> help(smtplib.SMTP.sendmail)
> Help on method sendmail in module smtplib:
> 
> sendmail(self, from_addr, to_addrs, msg, mail_options=[],
> rcpt_options=[]) unbound smtplib.SMTP method
>    This command performs an entire mail transaction.
>      The arguments are:
>        - from_addr    : The address sending this mail.
>        - to_addrs     : A list of addresses to send this mail to.  A bare
>                         string will be treated as a list with 1 address.
>        - msg          : The message to send.
>        - mail_options : List of ESMTP options (such as 8bitmime) for the
>                         mail command.
>        - rcpt_options : List of ESMTP options (such as DSN commands) for
>                         all the rcpt commands.
>      If there has been no previous EHLO or HELO command this session, this
>    method tries ESMTP EHLO first.  If the server does ESMTP, message size
>    and each of the specified options will be passed to it.  If EHLO
>    fails, HELO will be tried and ESMTP options suppressed.
>      This method will return normally if the mail is accepted for at least
>    one recipient.  It returns a dictionary, with one entry for each
>    recipient that was refused.  Each entry contains a tuple of the SMTP
>    error code and the accompanying error message sent by the server.
>      This method may raise the following exceptions:
>       SMTPHeloError          The server didn't reply properly to
>                            the helo greeting.
>     SMTPRecipientsRefused  The server rejected ALL recipients
>                            (no mail was sent).
>     SMTPSenderRefused      The server didn't accept the from_addr.
>     SMTPDataError          The server replied with an unexpected
>                            error code (other than a refusal of
>                            a recipient).
>      Note: the connection will be open even after an exception is raised.
>      Example:
>       >>> import smtplib
>     >>> s=smtplib.SMTP("localhost")
>     >>>
> tolist=["one at one.org","two at two.org","three at three.org","four at four.org"]
>     >>> msg = '''\
>     ... From: Me at my.org
>     ... Subject: testin'...
>     ...
>     ... This is a test '''
>     >>> s.sendmail("me at my.org",tolist,msg)
>     { "three at three.org" : ( 550 ,"User unknown" ) }
>     >>> s.quit()
>      In the above example, the message was accepted for delivery to three
>    of the four addresses, and one was rejected, with the error code
>    550.  If all addresses are accepted, then the method will return an
>    empty dictionary.
> 
>>>>
> 
> 
> 
> 
> So mess around in the built-in docs, then check python.org's docs, and
> let us know what you find :)
> Also, try experimenting! pass it stuff that you don't think will work
> just to see if maybe it does :D
> -Luke
> 


From phpmoonlighter at yahoo.com  Thu Dec  6 09:48:56 2007
From: phpmoonlighter at yahoo.com (ted b)
Date: Thu, 6 Dec 2007 00:48:56 -0800 (PST)
Subject: [Tutor] How to iterate and update subseqent items in list
Message-ID: <595529.21524.qm@web58801.mail.re1.yahoo.com>

Can you suggest a good way to iterate through the
remainder of list and update them?

Ex:
Thing1.value = 0
Thing2.value = 1
Thing3.value = 0
Thing4.value = 0

Things = [Thing1, Thing2, Thing3, Thing4]

I want to iterate through 'Things' and if
'Thing.value' > 0, then I want to set all values for
that and the subsequent 'Things' in the list to 2

So that i'd end up with

Thing1.value = 0
Thing2.value = 2
Thing3.value = 2
Thing4.value = 2


      ____________________________________________________________________________________
Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 


From bhaaluu at gmail.com  Thu Dec  6 14:19:42 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 6 Dec 2007 08:19:42 -0500
Subject: [Tutor] While Loops and Modules
In-Reply-To: <555764.37796.qm@web45105.mail.sp1.yahoo.com>
References: <mailman.8588.1196898157.13604.tutor@python.org>
	<555764.37796.qm@web45105.mail.sp1.yahoo.com>
Message-ID: <ea979d70712060519x1c5583eaja03ebb41fa70125c@mail.gmail.com>

Greetings,

On Dec 6, 2007 12:44 AM, earlylight publishing
<earlylightpublishing at yahoo.com> wrote:
> Hello again to all the wonderfully helpful folks on this list.  Today I did
> my Google homework and I found this neat bit of code for a countdown timer.
>
> import time
> import threading
> class Timer(threading.Thread):
>     def __init__(self, seconds):
>         self.runTime = seconds
>         threading.Thread.__init__(self)
>     def run(self):
>         time.sleep(self.runTime)
>         print "Buzzz!!! Time's up!"
> t = Timer(30)
> t.start()
>
> I don't understand large chunks of it (don't know what threading, self, or
> __init__ mean) but that's not important at the moment.  It works and I will
> learn the vocab eventually.

That is a good start! Get it working first, then figure it out later. 8^D

>
> I also wrote this bit of code for a math challenge which comes in the next
> part of my game.
>
> import random
> startNum = random.choice(range(1, 9))
> newNum = startNum + 7
> score = 0
> print 'Start with the number ', startNum, '.  Then continuously add 7 to
> that number until the timer runs out.  You have 30 seconds.'
>
> answer = int(raw_input('Enter your answer: '))
> if newNum == answer:
>     print 'That is correct!  Keep going.'
>     score = score + 5
>     print 'Your score is ', score
> else:
>     print 'That is incorrect.  Please try again.'
>
> I understand this part just fine 'cause I actually wrote it myself.
>

A couple of things which may help you when you're testing/debugging
your programs:

type(object)
dir(object)

Play with those in the interactive interpreter to see what they do, for example:
>>> a = 7
>>> type(a)
<<type 'int'>
>>> a = "time"
>>> type(a)
<type 'str'>
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill',
'_BuiltinMethodType', '_MethodType', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '_acos', '_cos', '_e', '_exp',
'_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt',
'_test', '_test_generator', '_urandom', '_warn', 'betavariate',
'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits',
'getstate', 'jumpahead', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']

etc.

Another little trick I use to watch the values of variables and set breakpoints:

print variable_Name
raw_input("Pause")

I just insert those two lines after each variable I want to watch (perhaps
to see if it is actually doing what I think it is supposed to be doing?).


> What I need to do now is put these two parts together so that the player
> will keep adding 7 to the starting number for 30 seconds then the loop
> breaks.  I know I need a loop of some sort and I'm guessing it's a 'while'
> sort of thing.  I couldn't find what I was looking for when I Googled.  I'm
> not even sure I knew the right search terms.  Does anyone know how I'd
> combine these two modules to make it work?
>

while True: or while 1: do the same thing, and they are a generic infinite loop.
You can use the keyword break somewhere inside the loop to break out of it.

When you figure out what condition  must be met to quit the while loop,
you can replace the True or 1 with your condition.

For example, working with the snippet you supplied:
import random
import time
import threading

class Timer(threading.Thread):
    def __init__(self, seconds):
        self.runTime = seconds
        threading.Thread.__init__(self)
    def run(self):
        time.sleep(self.runTime)
        print "Buzzz!!! Time's up!"
t = Timer(30)
startNum = random.choice(range(1, 9))
newNum = startNum + 7
score = 0
t.start()
print 'Start with the number ', startNum, '. Then continuously add 7
to that number until the timer runs out.  You have 30 seconds.'
while 1:
    answer = int(raw_input('Enter your answer: '))
    if newNum == answer:
        print 'That is correct!  Keep going.'
        score = score + 5
        print 'Your score is ', score
        newNum += 7
    else:
        print 'That is incorrect.  Please try again.'

That isn't quite working as it should, but I only added a couple of lines
and did the requisite indentation for the while loop. It might be enough
to keep you going for a wee bit?

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

From richardbwest at gmail.com  Thu Dec  6 14:38:26 2007
From: richardbwest at gmail.com (richard west)
Date: Thu, 6 Dec 2007 22:38:26 +0900
Subject: [Tutor] Loops and modules
Message-ID: <da6b8ceb0712060538j28deaf0en35d20aa9a9c78f59@mail.gmail.com>

 heres a partial solution. theres no error checking on the Raw Input and you
have to type in you last number and press return, before the loop will
break, but its a start!

#!/usr/bin/python
# Filename : math_test.py

import time
import threading
class Timer(threading.Thread):
    def __init__(self, seconds):
               self.runTime = seconds
               threading.Thread.__init__(self)
    def run(self):
        global running
        time.sleep(self.runTime)
        print " "
        print "Buzzz!!! Time's up!"
        running = False
t = Timer(30)
t.start()

import random
startNum = random.choice(range(1, 9))
newNum = startNum + 7 # im assuming you want the first number the user to
type as the startnum +7,its not too clear.
score = 0
running = True

print 'Start with the number ', startNum, '.  Then continuously add 7 to
that number until the timer runs out.  You have 30 seconds.'

while running:
    print running
    answer = int(raw_input('Enter your answer: '))
    if running == True:
         if answer == newNum:
               print 'That is correct!  Keep going.'
               score = score + 5
            newNum = newNum+7
               print 'Your score is ', score
        else:
               print 'That is incorrect.  Please try again.'
print ' '
print 'you total score was ', score

On Dec 6, 2007 6:15 PM, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: Best way of learning (bhaaluu)
>   2. Re: how to accept an integer? (Alan Gauld)
>   3. Mail? What's that? (Ricardo Ar?oz)
>   4. Re: Button 1 Motion Event (Luke Paireepinart)
>   5. While Loops and Modules (earlylight publishing)
>   6. Re: Mail? What's that? (Luke Paireepinart)
>   7. Re: Best way of learning (Remco Gerlich)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Wed, 5 Dec 2007 18:50:04 -0500
> From: bhaaluu <bhaaluu at gmail.com>
> Subject: Re: [Tutor] Best way of learning
> To: andy <geek_show at dsl.pipex.com>
> Cc: tutor at python.org
> Message-ID:
>        <ea979d70712051550j3339607bib59c17889a8d44cf at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> On Dec 5, 2007 5:43 PM, andy <geek_show at dsl.pipex.com> wrote:
> > Dear Pythonistas
> >
> [snip]
> >
> > So, after this long-winded introduction, I was hoping to pick the wisdom
> > of this list to get some pointers of what to do/not to do to make the
> > most effective use of the few hours I have to learn how to program using
> > Python. So, any advice for someone in their mid-40s who would like to
> > learn Python in a more methodical and effective manner?
> >
> > Thanks in anticipation.
> >
> > Andy
>
> It sounds to me like a good book or two would be just the thing for you.
> May I suggest:
> Learning Python by Mark Lutz
> and
> Programming Python Third Edition by the same author.
>
> Happy Programming!
> --
> b h a a l u u at g m a i l dot c o m
> http://www.geocities.com/ek.bhaaluu/python/index.html
>
>
> ------------------------------
>
> Message: 2
> Date: Wed, 5 Dec 2007 23:51:59 -0000
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] how to accept an integer?
> To: tutor at python.org
> Message-ID: <fj7dj7$27h$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>        reply-type=original
>
> "Mahesh N" <mahesh.mach at gmail.com> wrote
>
> > More over i find python to be a little sluggish after having worked
> > with C
> > and Java.
>
> If you translate C or Java code into python you will usually
> get a less than optimal implementation. Python should be
> barely slower than Java and often faster. Compared to
> C - yes there is a slow-down.
>
> But even in C you can use tools like Psycho and Pyrex to
> speed up critical sections to near C speeds if the problem fits.
> Or rewrite the critical section in C and wrap it as a module
> using SWIG. Thats how most of the performance ritical modules
> in the library are written. Where the major bottleneck is I/O
> work like database disk access or GUI or network sockets
> then you should find Python fast enough.
>
> > can someone temme where python is most applicable?
> > server side scripting? am i guessing it right?
>
> Python has been used in almost every form of programming
> from image processing and database manipulation to games
> programming and web server development. Do a search on
> Source Forge for projects using Python for an example of
> the variety.
>
> I'd avoid operating systems, device drivers and hard real-time
> applications though.
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> ------------------------------
>
> Message: 3
> Date: Wed, 05 Dec 2007 23:09:05 -0300
> From: Ricardo Ar?oz <ricaraoz at gmail.com>
> Subject: [Tutor] Mail? What's that?
> To: tutor at python.org
> Message-ID: <475759C1.4010507 at bigfoot.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> So I eventually got to sending mail with python.
> Some articles, trying and google led me to this script:
>
> import smtplib
> import time
>
> date = time.ctime(time.time( ))
> >From = 'mymail at gmail.com'
> To = ['othermail at hotmail.com', 'YetOtherMail at yahoo.com']
> Subj = 'Hi'
> text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n'
>                         % (From, ';'.join(To), date, Subj))
>
> s = smtplib.SMTP('smtp.gmail.com')
> s.set_debuglevel(1)
> s.ehlo()
> s.starttls()
> s.ehlo()
> s.login('foo', 'bar')
> s.sendmail(From, To, text)
> s.close()
>
>
> So, if there's someone who really knows this stuff in the neighborhood
> I'd like to ask a couple of questions.
> What is ehlo and why do I have to call it twice? And set_debuglevel?
> If I where to connect through other smtp server the sequence would be
> the exactly the same, say yahoo or hotmail?
> Are From: To: Date: and Subject: mandatory in the contents of the
> email(text)?  Do I have to put "real" address in  From when calling
> sendmail()? And in the contents?
> Ok, if someone can answer these I'll be grateful.
>
> TIA
>
> Ricardo
>
>
>
>
> ------------------------------
>
> Message: 4
> Date: Wed, 05 Dec 2007 23:38:39 -0600
> From: Luke Paireepinart <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] Button 1 Motion Event
> To: Johnston Jiaa <oclbdk at gmail.com>, Tutor <tutor at python.org>
> Message-ID: <47578ADF.40108 at gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Johnston Jiaa wrote:
> >
> >> Just don't distinguish between quick and slow drags.  Just keep a
> >> temporary variable that has the previous mouse position, and draw
> >> ovals from there to the current mouse position every time your
> >> function is called.
> >
> > I now have the variable with the previous mouse position.  How would I
> > draw ovals from the current mouse position to that previous mouse
> > position?  I tried reasoning it out with a for-loop, but I couldn't
> > figure out how to do it.
> Well, try reasoning it out with mathematics.
> Suppose we have the points (0,0) and (100,100).
> What's the slope between these two points?
> well, delta-Y is 100 and delta-X is 100, and 100/100 == 1.
> This is also the same as 1/1.
> Therefore, for every new point we want to get, we'll add 1 to the x
> value and 1 to the y value.
>
> Now assume we have the points (23, 45) and (45, 80).
> This slope would be:
> 80 - 45
> ---------
> 45 - 23
> or  35 / 22.
> So as you can see, the number on the top is larger than the number on
> the bottom, so our Y-value is increasing more quickly.
> But it doesn't really matter which value is bigger, the numerator or the
> denominator.
> All we care about is the slope.  Because slope tells us: this is the
> change in Y for every change in X.
> The reason slope tells us this is because slope is the ratio between the
> change in Y between our 2 points
> and the change in X between our 2 points.
> Because it's a ratio, it can be applied to any measure, even to
> deltaX=1, which gives us what deltaY is.
> Since we don't care about any X-coordinates between integers, we don't
> care about any other deltaX measurement.
>
> So you'd do something like this:
> x = 23.0 # our first points
> y = 45.0 # they're float so we can add partial amounts to them.
> slope = 35/22.0 # this is float to force float division.
> for deltax in range(23, 45):
>    x += deltax
>    y += slope
>
> So in this case, each time through the loop, X will move 1 over, and Y
> will move slightly more than 1 up.
>
> This still has a problem if the slope is very great in the Y-direction.
> Given the case of the points (0,0) and (1,100),
> we get a slope of 100.  Thus, we will draw points at 0,0 and at 1,100
> and none in-between,
> when realistically we'd like at least a vertical line between them, or
> preferably one that shifts one pixel over halfway-up.
>
> Note that the poitns (0,0) and (100, 1) would not create a problem.
> This is because our delta-x is changing at a set rate,
> and our deltay is a smaller number.  It would work in this case.
>
> What's creating the problem is that our slope is greater than 1, and
> we're using delta-x as a fixed amount.
> If we add the condition that we affix delta-x to the value 1 for slopes
> less than 1, and delta-y to 1 when slopes are greater than 1,
> then everything should work out perfectly.  The case of slope == 1 will
> be correctly handled in either case, just make sure to include it in one
> of them.
>
> Thusly, our code would look something like this:
>
> point1x, point1y = raw_input("please input the first pair of coordinates
> separated by a space: ").split(' ')
> point2x, point2y = raw_input("please input the second pair of
> coordinates separated by a space: ").split(' ')
>
> slope = (point2y - point1y) / (float(point2x - point1x))
> if slope > 1:
>    deltax = 1 / slope # i assume we invert slope here?
>    deltay = 1
> else:
>    deltax = 1
>    deltay = slope
>
> currentx = float(point1x)
> currenty = float(point1y)
> for x in range(max((point2y - point1y), (point2x - point1x)) ):
>    #we choose our range as the larger of the two lengths.
>    #thus if delta-x is only 1px and delta-y is 100px, we'll
>    #still draw all those points in between.
>
>    # ..........
>    #  draw the currentx, currenty point here
>    # .........
>    currentx += deltax
>    currenty += deltay
>
> # and draw the point one more time here, to get your ending point.
>
>
>
>
> Note that I don't profess that either my code or my math is correct; I
> didn't test any of this, it's more to give you an idea of how to
> approach Computer Science problems.
>
> >
> > Also, I need to be able to save the canvas drawing.  Would it be
> > possible to write some sort of data to a file that could be used to
> > load the previously saved drawing back onto the canvas?
> You can just keep a cache of all points and redraw them on load, or you
> can dump it out to an image file.  I believe TKInter supports that, but
> I haven't used that library in a long time.
>
> Again, _please reply on-list_ unless you want a discussion to be
> private, in which case specify in the e-mail so we know it wasn't an
> accident.
> -Luke
>
>
>
> ------------------------------
>
> Message: 5
> Date: Wed, 5 Dec 2007 21:44:09 -0800 (PST)
> From: earlylight publishing <earlylightpublishing at yahoo.com>
> Subject: [Tutor] While Loops and Modules
> To: tutor at python.org
> Message-ID: <555764.37796.qm at web45105.mail.sp1.yahoo.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hello again to all the wonderfully helpful folks on this list.  Today I
> did my Google homework and I found this neat bit of code for a countdown
> timer.
>
>  import time
> import threading
> class Timer(threading.Thread):
>    def __init__(self, seconds):
>        self.runTime = seconds
>        threading.Thread.__init__(self)
>    def run(self):
>        time.sleep(self.runTime)
>        print "Buzzz!!! Time's up!"
>  t = Timer(30)
> t.start()
>
>  I don't understand large chunks of it (don't know what threading, self,
> or __init__ mean) but that's not important at the moment.  It works and I
> will learn the vocab eventually.
>
>  I also wrote this bit of code for a math challenge which comes in the
> next part of my game.
>
>  import random
> startNum = random.choice(range(1, 9))
> newNum = startNum + 7
> score = 0
> print 'Start with the number ', startNum, '.  Then continuously add 7 to
> that number until the timer runs out.  You have 30 seconds.'
>
> answer = int(raw_input('Enter your answer: '))
>  if newNum == answer:
>    print 'That is correct!  Keep going.'
>    score = score + 5
>    print 'Your score is ', score
> else:
>    print 'That is incorrect.  Please try again.'
>
>  I understand this part just fine 'cause I actually wrote it myself.
>
>  What I need to do now is put these two parts together so that the player
> will keep adding 7 to the starting number for 30 seconds then the loop
> breaks.  I know I need a loop of some sort and I'm guessing it's a 'while'
> sort of thing.  I couldn't find what I was looking for when I Googled.  I'm
> not even sure I knew the right search terms.  Does anyone know how I'd
> combine these two modules to make it work?
>
>
> ---------------------------------
> Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it
> now.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20071205/e265b7d9/attachment-0001.htm
>
> ------------------------------
>
> Message: 6
> Date: Wed, 05 Dec 2007 23:47:32 -0600
> From: Luke Paireepinart <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] Mail? What's that?
> To: raraoz at bigfoot.com
> Cc: tutor at python.org
> Message-ID: <47578CF4.4040609 at gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Ricardo Ar?oz wrote:
> > So I eventually got to sending mail with python.
> > Some articles, trying and google led me to this script:
> >
> > import smtplib
> > import time
> >
> > date = time.ctime(time.time( ))
> > >From = 'mymail at gmail.com'
> > To = ['othermail at hotmail.com', 'YetOtherMail at yahoo.com']
> > Subj = 'Hi'
> > text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n'
> >                          % (From, ';'.join(To), date, Subj))
> >
> > s = smtplib.SMTP('smtp.gmail.com')
> > s.set_debuglevel(1)
> > s.ehlo()
> > s.starttls()
> > s.ehlo()
> > s.login('foo', 'bar')
> > s.sendmail(From, To, text)
> > s.close()
> >
> >
> > So, if there's someone who really knows this stuff in the neighborhood
> > I'd like to ask a couple of questions.
> > What is ehlo and why do I have to call it twice? And set_debuglevel?
> > If I where to connect through other smtp server the sequence would be
> > the exactly the same, say yahoo or hotmail?
> > Are From: To: Date: and Subject: mandatory in the contents of the
> > email(text)?  Do I have to put "real" address in  From when calling
> > sendmail()? And in the contents?
> > Ok, if someone can answer these I'll be grateful.
> >
> > TIA
> >
> > Ricardo
> >
> Ricardo -
> I say this in the nicest way possible, but did you RTFM? :)
> Python has built-in help support on modules.
> You should start there, do some Googling, and if you're stumped, get
> some help.  Not for any other reason than it'll probably get you 1) more
> experience at navigating the docs, and 2) a quicker, probably more
> detailed response.
>
> So using Help, we get:
>
>
>  >>> import smtplib
>  >>> help(smtplib)
> Help on module smtplib:
>
> NAME
>    smtplib - SMTP/ESMTP client class.
>
> FILE
>    c:\python24\lib\smtplib.py
>
> [snip 10 pages of documentation]
>
>
>  >>> help(smtplib.SMTP.set_debuglevel)
> Help on method set_debuglevel in module smtplib:
>
> set_debuglevel(self, debuglevel) unbound smtplib.SMTP method
>    Set the debug output level.
>
>    A non-false value results in debug messages for connection and for all
>    messages sent to and received from the server.
>
>  >>> help(smtplib.SMTP.ehlo)
> Help on method ehlo in module smtplib:
>
> ehlo(self, name='') unbound smtplib.SMTP method
>    SMTP 'ehlo' command.
>    Hostname to send for this command defaults to the FQDN of the local
>    host.
>
>  >>> help(smtplib.SMTP.sendmail)
> Help on method sendmail in module smtplib:
>
> sendmail(self, from_addr, to_addrs, msg, mail_options=[],
> rcpt_options=[]) unbound smtplib.SMTP method
>    This command performs an entire mail transaction.
>
>    The arguments are:
>        - from_addr    : The address sending this mail.
>        - to_addrs     : A list of addresses to send this mail to.  A bare
>                         string will be treated as a list with 1 address.
>        - msg          : The message to send.
>        - mail_options : List of ESMTP options (such as 8bitmime) for the
>                         mail command.
>        - rcpt_options : List of ESMTP options (such as DSN commands) for
>                         all the rcpt commands.
>
>    If there has been no previous EHLO or HELO command this session, this
>    method tries ESMTP EHLO first.  If the server does ESMTP, message size
>    and each of the specified options will be passed to it.  If EHLO
>    fails, HELO will be tried and ESMTP options suppressed.
>
>    This method will return normally if the mail is accepted for at least
>    one recipient.  It returns a dictionary, with one entry for each
>    recipient that was refused.  Each entry contains a tuple of the SMTP
>    error code and the accompanying error message sent by the server.
>
>    This method may raise the following exceptions:
>
>     SMTPHeloError          The server didn't reply properly to
>                            the helo greeting.
>     SMTPRecipientsRefused  The server rejected ALL recipients
>                            (no mail was sent).
>     SMTPSenderRefused      The server didn't accept the from_addr.
>     SMTPDataError          The server replied with an unexpected
>                            error code (other than a refusal of
>                            a recipient).
>
>    Note: the connection will be open even after an exception is raised.
>
>    Example:
>
>     >>> import smtplib
>     >>> s=smtplib.SMTP("localhost")
>     >>>
> tolist=["one at one.org","two at two.org","three at three.org","four at four.org"]
>     >>> msg = '''\
>     ... From: Me at my.org
>     ... Subject: testin'...
>     ...
>     ... This is a test '''
>     >>> s.sendmail("me at my.org",tolist,msg)
>     { "three at three.org" : ( 550 ,"User unknown" ) }
>     >>> s.quit()
>
>    In the above example, the message was accepted for delivery to three
>    of the four addresses, and one was rejected, with the error code
>    550.  If all addresses are accepted, then the method will return an
>    empty dictionary.
>
>  >>>
>
>
>
>
> So mess around in the built-in docs, then check python.org's docs, and
> let us know what you find :)
> Also, try experimenting! pass it stuff that you don't think will work
> just to see if maybe it does :D
> -Luke
>
>
> ------------------------------
>
> Message: 7
> Date: Thu, 6 Dec 2007 10:15:02 +0100
> From: "Remco Gerlich" <remco at gerlich.nl>
> Subject: Re: [Tutor] Best way of learning
> To: andy <geek_show at dsl.pipex.com>
> Cc: tutor at python.org
> Message-ID:
>        <7ae3ca10712060115r34a7fa33q32a5902fdd0af1b at mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
> On Dec 5, 2007 11:43 PM, andy <geek_show at dsl.pipex.com> wrote:
>
> > So, after this long-winded introduction, I was hoping to pick the wisdom
> > of this list to get some pointers of what to do/not to do to make the
> > most effective use of the few hours I have to learn how to program using
> > Python. So, any advice for someone in their mid-40s who would like to
> > learn Python in a more methodical and effective manner?
> >
>
> In my opinion, the best way to learn _anything_ is to try to do it, and
> then
> look around for tips every now and then in the mean time. You'll connect
> much more easily with the information when it's something you've recently
> struggled with. And practice is the most important part of any learning
> anyway.
>
> So, what do you want to do with Python? Any other hobbies you can connect
> it
> with? Perhaps ideas for a dynamic web site or something?
>
> In my experience, learning something just for abstract knowledge can be
> fun
> for a while, but it's hard to stay committed. And there's nothing wrong
> with
> that, there's only so many hours in a day, and the things you actually use
> in life should probably take precedence :-)
>
> So if you've written small tools, feel like expanding them? Used modules
> in
> them that you don't entirely understand yet, perhaps dive into their docs?
>
> Perhaps the Python Challenge ( http://www.pythonchallenge.com/ ) is
> something for you? It's at least sideways a little into the hacking
> spirit,
> it's fun, and it's a tour of what Python can do - but you'll have to find
> the way yourself :-)
>
> Remco Gerlich
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20071206/8eafc022/attachment.htm
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 46, Issue 15
> *************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/e6fff891/attachment-0001.htm 

From remco at gerlich.nl  Thu Dec  6 15:58:20 2007
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 6 Dec 2007 15:58:20 +0100
Subject: [Tutor] How to iterate and update subseqent items in list
In-Reply-To: <595529.21524.qm@web58801.mail.re1.yahoo.com>
References: <595529.21524.qm@web58801.mail.re1.yahoo.com>
Message-ID: <7ae3ca10712060658y615feef8y827a00cdd188aafe@mail.gmail.com>

Hi,

In this case, I'd go for the simple old fashioned for loop with a boolean:

found = False
for thing in Things:
    if thing.value > 0:
        found = True
    if found:
        thing.value = 2

Remco Gerlich

On Dec 6, 2007 9:48 AM, ted b <phpmoonlighter at yahoo.com> wrote:

> Can you suggest a good way to iterate through the
> remainder of list and update them?
>
> Ex:
> Thing1.value = 0
> Thing2.value = 1
> Thing3.value = 0
> Thing4.value = 0
>
> Things = [Thing1, Thing2, Thing3, Thing4]
>
> I want to iterate through 'Things' and if
> 'Thing.value' > 0, then I want to set all values for
> that and the subsequent 'Things' in the list to 2
>
> So that i'd end up with
>
> Thing1.value = 0
> Thing2.value = 2
> Thing3.value = 2
> Thing4.value = 2
>
>
>
>  ____________________________________________________________________________________
> Be a better friend, newshound, and
> know-it-all with Yahoo! Mobile.  Try it now.
> http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ
>
> _______________________________________________
> 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/20071206/fde1f23b/attachment.htm 

From bhaaluu at gmail.com  Thu Dec  6 16:19:00 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 6 Dec 2007 10:19:00 -0500
Subject: [Tutor] Loops and modules
In-Reply-To: <da6b8ceb0712060538j28deaf0en35d20aa9a9c78f59@mail.gmail.com>
References: <da6b8ceb0712060538j28deaf0en35d20aa9a9c78f59@mail.gmail.com>
Message-ID: <ea979d70712060719t6fbad75csa103dd58dfcc1814@mail.gmail.com>

On Dec 6, 2007 8:38 AM, richard west <richardbwest at gmail.com> wrote:
>  heres a partial solution. theres no error checking on the Raw Input and you
> have to type in you last number and press return, before the loop will
> break, but its a start!

And modifying  your modifications makes it work even a little better:
#######################################
#!/usr/bin/python

import random
import time
import threading

class Timer(threading.Thread):
    def __init__(self, seconds):
               self.runTime = seconds
               threading.Thread.__init__(self)
    def run(self):
        global running
        time.sleep(self.runTime)
        print " "
        print "Buzzz!!! Time's up!"
        running = False

t = Timer(30)
t.start()
startNum = random.choice(range(1, 9))
newNum = startNum + 7
score = 0
running = True
print 'Start with the number ', startNum, '.  Then continuously add 7
to that number until the timer runs out.  You have 30 seconds.'

while running:
    if running == True:
         answer = int(raw_input('Enter your answer: '))
         if answer == newNum:
               print 'That is correct!  Keep going.'
               score = score + 5
               newNum = newNum + 7
               print 'Your score is ', score
         else:
               print 'That is incorrect.  Please try again.'
    else:
        answer = 0
print ' '
print 'Your total score was: ', score
#######################################

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

> #!/usr/bin/python
> # Filename : math_test.py
>
> import time
> import threading
> class Timer(threading.Thread):
>     def __init__(self, seconds):
>                self.runTime = seconds
>                threading.Thread.__init__(self)
>     def run(self):
>         global running
>         time.sleep(self.runTime)
>         print " "
>         print "Buzzz!!! Time's up!"
>         running = False
> t = Timer(30)
> t.start()
>
> import random
> startNum = random.choice(range(1, 9))
> newNum = startNum + 7 # im assuming you want the first number the user to
> type as the startnum +7,its not too clear.
> score = 0
> running = True
>
> print 'Start with the number ', startNum, '.  Then continuously add 7 to
> that number until the timer runs out.  You have 30 seconds.'
>
> while running:
>     print running
>     answer = int(raw_input('Enter your answer: '))
>     if running == True:
>          if answer == newNum:
>                print 'That is correct!  Keep going.'
>                score = score + 5
>             newNum = newNum+7
>                print 'Your score is ', score
>         else:
>                print 'That is incorrect.  Please try again.'
> print ' '
> print 'you total score was ', score
>
> On Dec 6, 2007 6:15 PM, <tutor-request at python.org> wrote:
> > Send Tutor mailing list submissions to
> >        tutor at python.org
> >
> > To subscribe or unsubscribe via the World Wide Web, visit
> >         http://mail.python.org/mailman/listinfo/tutor
> > or, via email, send a message with subject or body 'help' to
> >        tutor-request at python.org
> >
> > You can reach the person managing the list at
> >        tutor-owner at python.org
> >
> > When replying, please edit your Subject line so it is more specific
> > than "Re: Contents of Tutor digest..."
> >

From tim at johnsons-web.com  Thu Dec  6 16:42:19 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Thu, 6 Dec 2007 06:42:19 -0900
Subject: [Tutor] Problems with List Server?
In-Reply-To: <7ae3ca10712060118x4d5024cdpdbd90d26bb3e2767@mail.gmail.com>
References: <200712031316.37287.tim@johnsons-web.com>
	<200712031351.24449.tim@johnsons-web.com>
	<7ae3ca10712060118x4d5024cdpdbd90d26bb3e2767@mail.gmail.com>
Message-ID: <200712060642.19438.tim@johnsons-web.com>

On Thursday 06 December 2007, you wrote:
> It arrived.
>
> Since you appear to be the only one reporting the problem, perhaps it's
> something on your end?
 It was the domain hoster. It has now been corrected.
thanks
tim

From justin.cardinal at exbsolutions.com  Thu Dec  6 16:42:20 2007
From: justin.cardinal at exbsolutions.com (Justin Cardinal)
Date: Thu, 6 Dec 2007 09:42:20 -0600
Subject: [Tutor]  Mail? What's that?
Message-ID: <003b01c8381e$97316430$a001a8c0@exbspider>


Ricardo Ar?oz wrote:
>Are From: To: Date: and Subject: mandatory in the contents of the

>email(text)?  Do I have to put "real" address in  From when calling

>sendmail()? And in the contents?
Here's the page I used to learn on this subject.
http://www.thinkspot.net/sheila/article.php?story=20040822174141155
 
I'm definitely not a pro in this area, so what comes next are merely
assumptions made after toying around a bit.
I don't believe the From, To, Date, Subject are required, but if you play
around sending some test messages to yourself, you'll see that excluding
them makes the message look very suspicious. As far as using your real
address, that might depend on your email server...but yes, you can most
likely spoof other addresses. Please use this for good, not evil.
 
-Justin Cardinal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/6658166b/attachment.htm 

From marc.tompkins at gmail.com  Thu Dec  6 18:12:59 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 6 Dec 2007 09:12:59 -0800
Subject: [Tutor] Questions about wxEvents
Message-ID: <40af687b0712060912i257fa657icdbac862e4677eb0@mail.gmail.com>

I have a specific question - how can I generalize a
FileBrowseButtonWithHistory - and I realized, as I was trying to word my
question, that my real question is a bit more generic.

First, the specific question:  The FileBrowseButtonWithHistory requires a
callback override and some custom code to straighten out handling the
history.  So far, so good.  However, I wish to use more than one FBBWH on my
form, and I can't figure out how to re-use the custom callback so it will
work for both controls.  (It makes me sick to my stomach when I look at my
code and see duplicate blocks!)   Don't get me wrong - it's working right
now, it's just that my code is fugly and I want to clean it up.

In more general terms, how can I set more than one control to use the same
block of code as a custom callback, and figure out at runtime which control
I'm responding to?  Doesn't the Event or CommandEvent carry any information
about itself?
I've tried this:

        [snip]
        self.fp1 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
size=(300, -1),
            labelText='', fileMask='*.*', fileMode=wx.OPEN,
            dialogTitle='Select the file containing UCF claims',
changeCallback=self.fp1Callback)
        self.fp2 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
size=(300, -1),
            labelText='', fileMask='FI*.*', fileMode=wx.OPEN,
            dialogTitle='Select the form-image file - generally starts with
FI', changeCallback=self.fp2Callback)
        [snip]
    def fp1Callback(self, evt):
        print evt.__dict__
        print help(evt)
        value = evt.GetString()
        [snip]
    def fp2Callback(self, evt):
        print evt.__dict__
        print help(evt)
        value = evt.GetString()
        [snip]

All I get from "print evt.__dict__" is: {'_string':
u'E:\\ultrahld\\report\\FILE'}

and all I get from help is:
Help on instance of LocalEvent in module
wx.lib.filebrowsebuttonobject:class instance(object)
 |  instance(class[, dict])
 |
 |  Create an instance without calling its __init__() method.
 |  The class must be a classic class.
 |  If present, dict must be a dictionary or None.
 |
 |  Methods defined here:
 |
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |
...  in other words, I might as well have typed "help(object)".
I only know that the method "evt.GetString()" exists because the example in
the demo uses it.
I've Googled, and Gmaned, and read the wx docs (such as they are), but I'm
not seeing anything I can use.

I know that this is a wxPython question, and that this is the Python list...
but y'all have answered some wx questions in the past, and I hate to join
another list for one question.   If I must, I will... but thanks in advance
for any light you can shed.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/63fcab3b/attachment.htm 

From jeff at drinktomi.com  Thu Dec  6 18:38:55 2007
From: jeff at drinktomi.com (Jeff Younker)
Date: Thu, 6 Dec 2007 09:38:55 -0800
Subject: [Tutor] Questions about wxEvents
In-Reply-To: <40af687b0712060912i257fa657icdbac862e4677eb0@mail.gmail.com>
References: <40af687b0712060912i257fa657icdbac862e4677eb0@mail.gmail.com>
Message-ID: <21A0AFB8-45D3-4294-8E17-DD34E70A4F1E@drinktomi.com>

While I can't help you with the wx specific part of the question, I can
offer help with the reuse question.     Here is one approach.  Add an
controller identifier to fpCallback.  Then use lambda expressions for  
the
actual callback, where the lambda expressions pass in a fixed value  
for the
identifier.

Modified code:

         self.fp1 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,  
size=(300, -1),
             labelText='', fileMask='*.*', fileMode=wx.OPEN,
             dialogTitle='Select the file containing UCF claims',
             changeCallback= lambda x: self.fpCallback('fp1', x)
         )
         self.fp2 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,  
size=(300, -1),
             labelText='', fileMask='FI*.*', fileMode=wx.OPEN,
             dialogTitle='Select the form-image file - generally  
starts with FI',
             changeCallback= lambda x: self.fpCallback('fp2', x)
         )
         [snip]
     def fpCallback(self, controlID, evt):
         print evt.__dict__
         print help(evt)
         value = evt.GetString()
         [snip]



- Jeff Younker - jeff at drinktomi.com -


On Dec 6, 2007, at 9:12 AM, Marc Tompkins wrote:

> I have a specific question - how can I generalize a  
> FileBrowseButtonWithHistory - and I realized, as I was trying to  
> word my question, that my real question is a bit more generic.
>
> First, the specific question:  The FileBrowseButtonWithHistory  
> requires a callback override and some custom code to straighten out  
> handling the history.  So far, so good.  However, I wish to use more  
> than one FBBWH on my form, and I can't figure out how to re-use the  
> custom callback so it will work for both controls.  (It makes me  
> sick to my stomach when I look at my code and see duplicate  
> blocks!)   Don't get me wrong - it's working right now, it's just  
> that my code is fugly and I want to clean it up.
>
> In more general terms, how can I set more than one control to use  
> the same block of code as a custom callback, and figure out at  
> runtime which control I'm responding to?  Doesn't the Event or  
> CommandEvent carry any information about itself?
> I've tried this:
>
>         [snip]
>         self.fp1 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,  
> size=(300, -1),
>             labelText='', fileMask='*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the file containing UCF claims',  
> changeCallback= self.fp1Callback)
>         self.fp2 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,  
> size=(300, -1),
>             labelText='', fileMask='FI*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the form-image file - generally  
> starts with FI', changeCallback= self.fp2Callback)
>         [snip]
>     def fp1Callback(self, evt):
>         print evt.__dict__
>         print help(evt)
>         value = evt.GetString()
>         [snip]
>     def fp2Callback(self, evt):
>         print evt.__dict__
>         print help(evt)
>         value = evt.GetString()
>         [snip]
>
> All I get from "print evt.__dict__" is: {'_string': u'E:\\ultrahld\ 
> \report\\FILE'}
>
> and all I get from help is:
> Help on instance of LocalEvent in module wx.lib.filebrowsebutton  
> object:class instance(object)
>  |  instance(class[, dict])
>  |
>  |  Create an instance without calling its __init__() method.
>  |  The class must be a classic class.
>  |  If present, dict must be a dictionary or None.
>  |
>  |  Methods defined here:
>  |
>  |  __abs__(...)
>  |      x.__abs__() <==> abs(x)
>  |
> ...  in other words, I might as well have typed "help(object)".
> I only know that the method "evt.GetString()" exists because the  
> example in the demo uses it.
> I've Googled, and Gmaned, and read the wx docs (such as they are),  
> but I'm not seeing anything I can use.
>
> I know that this is a wxPython question, and that this is the Python  
> list... but y'all have answered some wx questions in the past, and I  
> hate to join another list for one question.   If I must, I will...  
> but thanks in advance for any light you can shed.
>
> -- 
> www.fsrtechnologies.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/20071206/c7bee703/attachment-0001.htm 

From tiagosaboga at terra.com.br  Thu Dec  6 18:45:39 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Thu, 6 Dec 2007 15:45:39 -0200
Subject: [Tutor] Questions about wxEvents
In-Reply-To: <40af687b0712060912i257fa657icdbac862e4677eb0@mail.gmail.com>
References: <40af687b0712060912i257fa657icdbac862e4677eb0@mail.gmail.com>
Message-ID: <20071206174539.GC7730@localdomain>

On Thu, Dec 06, 2007 at 09:12:59AM -0800, Marc Tompkins wrote:
> I have a specific question - how can I generalize a
> FileBrowseButtonWithHistory - and I realized, as I was trying to word my
> question, that my real question is a bit more generic.
> 
> First, the specific question:  The FileBrowseButtonWithHistory requires a
> callback override and some custom code to straighten out handling the
> history.  So far, so good.  However, I wish to use more than one FBBWH on my
> form, and I can't figure out how to re-use the custom callback so it will
> work for both controls.  (It makes me sick to my stomach when I look at my
> code and see duplicate blocks!)   Don't get me wrong - it's working right
> now, it's just that my code is fugly and I want to clean it up.
> 
> In more general terms, how can I set more than one control to use the same
> block of code as a custom callback, and figure out at runtime which control
> I'm responding to?  Doesn't the Event or CommandEvent carry any information
> about itself?
> I've tried this:
> 
>         [snip]
>         self.fp1 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
> size=(300, -1),
>             labelText='', fileMask='*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the file containing UCF claims',
> changeCallback=self.fp1Callback)
>         self.fp2 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
> size=(300, -1),
>             labelText='', fileMask='FI*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the form-image file - generally starts with
> FI', changeCallback=self.fp2Callback)
>         [snip]
>     def fp1Callback(self, evt):
>         print evt.__dict__
>         print help(evt)
>         value = evt.GetString()
>         [snip]
>     def fp2Callback(self, evt):
>         print evt.__dict__
>         print help(evt)
>         value = evt.GetString()
>         [snip]

I have never used wx, but I faced the same question with the qt
toolkit, and I solved it with a function that returns a function. In
my case, I have several widgets to connect to a single function
(setValue), and in some cases they have to be connected also with a
particular function (always named set_AttributeName).

Here's my snippet:

self.connect(widget, QtCore.SIGNAL(signal),
             self.get_setValue_func(option))
[...]
def get_setValue_func(self, option):
    def setIt(value):
       try:
           method = self.__getattribute__("set_%s" % option)
           method(value)
       except AttributeError:
           pass
    self.setValue(option, value)
return setIt
	
Tiago.

From marc.tompkins at gmail.com  Thu Dec  6 19:03:32 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 6 Dec 2007 10:03:32 -0800
Subject: [Tutor] Questions about wxEvents
In-Reply-To: <21A0AFB8-45D3-4294-8E17-DD34E70A4F1E@drinktomi.com>
References: <40af687b0712060912i257fa657icdbac862e4677eb0@mail.gmail.com>
	<21A0AFB8-45D3-4294-8E17-DD34E70A4F1E@drinktomi.com>
Message-ID: <40af687b0712061003v5de2b4deq253d7a55526a95c4@mail.gmail.com>

Hot diggety!  Exactly what I was trying to come up with.  Thank you!

On Dec 6, 2007 9:38 AM, Jeff Younker <jeff at drinktomi.com> wrote:

> While I can't help you with the wx specific part of the question, I canoffer
> help with the reuse question.     Here is one approach.  Add an
> controller identifier to fpCallback.  Then use lambda expressions for the
> actual callback, where the lambda expressions pass in a fixed value for
> the
> identifier.
>
> Modified code:
>
>         self.fp1 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
> size=(300, -1),
>             labelText='', fileMask='*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the file containing UCF claims',
>             changeCallback= lambda x: self.fpCallback('fp1', x)
>         )
>         self.fp2 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
> size=(300, -1),
>             labelText='', fileMask='FI*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the form-image file - generally starts
> with FI',
>             changeCallback= lambda x: self.fpCallback('fp2', x)
>         )
>         [snip]
>     def fpCallback(self, controlID, evt):
>         print evt.__dict__
>         print help(evt)
>         value = evt.GetString()
>         [snip]
>
>
>
> - Jeff Younker - jeff at drinktomi.com -
>
>
> On Dec 6, 2007, at 9:12 AM, Marc Tompkins wrote:
>
> I have a specific question - how can I generalize a
> FileBrowseButtonWithHistory - and I realized, as I was trying to word my
> question, that my real question is a bit more generic.
>
> First, the specific question:  The FileBrowseButtonWithHistory requires a
> callback override and some custom code to straighten out handling the
> history.  So far, so good.  However, I wish to use more than one FBBWH on my
> form, and I can't figure out how to re-use the custom callback so it will
> work for both controls.  (It makes me sick to my stomach when I look at my
> code and see duplicate blocks!)   Don't get me wrong - it's working right
> now, it's just that my code is fugly and I want to clean it up.
>
> In more general terms, how can I set more than one control to use the same
> block of code as a custom callback, and figure out at runtime which control
> I'm responding to?  Doesn't the Event or CommandEvent carry any information
> about itself?
> I've tried this:
>
>         [snip]
>         self.fp1 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
> size=(300, -1),
>             labelText='', fileMask='*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the file containing UCF claims',
> changeCallback= self.fp1Callback)
>         self.fp2 = filebrowse.FileBrowseButtonWithHistory(pnl, -1,
> size=(300, -1),
>             labelText='', fileMask='FI*.*', fileMode=wx.OPEN,
>             dialogTitle='Select the form-image file - generally starts
> with FI', changeCallback= self.fp2Callback)
>         [snip]
>     def fp1Callback(self, evt):
>         print evt.__dict__
>         print help(evt)
>         value = evt.GetString()
>         [snip]
>     def fp2Callback(self, evt):
>         print evt.__dict__
>         print help(evt)
>         value = evt.GetString()
>         [snip]
>
> All I get from "print evt.__dict__" is: {'_string':
> u'E:\\ultrahld\\report\\FILE'}
>
> and all I get from help is:
> Help on instance of LocalEvent in module wx.lib.filebrowsebuttonobject:class instance(object)
>  |  instance(class[, dict])
>  |
>  |  Create an instance without calling its __init__() method.
>  |  The class must be a classic class.
>  |  If present, dict must be a dictionary or None.
>  |
>  |  Methods defined here:
>  |
>  |  __abs__(...)
>  |      x.__abs__() <==> abs(x)
>  |
> ...  in other words, I might as well have typed "help(object)".
> I only know that the method "evt.GetString()" exists because the example
> in the demo uses it.
> I've Googled, and Gmaned, and read the wx docs (such as they are), but I'm
> not seeing anything I can use.
>
> I know that this is a wxPython question, and that this is the Python
> list... but y'all have answered some wx questions in the past, and I hate to
> join another list for one question.   If I must, I will... but thanks in
> advance for any light you can shed.
>
> --
> www.fsrtechnologies.com _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/7c278548/attachment.htm 

From mahesh.mach at gmail.com  Thu Dec  6 20:01:23 2007
From: mahesh.mach at gmail.com (Mahesh N)
Date: Fri, 7 Dec 2007 00:31:23 +0530
Subject: [Tutor] PIDA Issue
Message-ID: <fc1d32f20712061101n6a186dafl1028e1da2bda8cad@mail.gmail.com>

I have installed pida succesfully using the command
python setup.py install
Installation was successful i.e. no errors but when i launch pida, it says
some module is missing. wat could be the problem??? i am posting the result
of installation and of launching the program.


maggi:~/Desktop/PIDA-0.5.1#python setup.py install
.
.
.
.
running install_scripts
copying build/scripts-2.4/pida -> /usr/bin
copying build/scripts-2.4/pida-remote -> /usr/bin
changing mode of /usr/bin/pida to 755
changing mode of /usr/bin/pida-remote to 755
maggi:~/Desktop/PIDA-0.5.1# pida
Traceback (most recent call last):
  File "/usr/bin/pida", line 28, in ?
    from pida.core.application import main
  File "/usr/lib/python2.4/site-packages/pida/core/__init__.py", line 3, in
?
    import pida.core.environment
  File "/usr/lib/python2.4/site-packages/pida/core/environment.py", line 4,
in ?    from kiwi.environ import Library, environ
ImportError: No module named kiwi.environ


I need an IDE badly.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071207/9d45289f/attachment.htm 

From bgailer at alum.rpi.edu  Thu Dec  6 20:43:31 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 06 Dec 2007 14:43:31 -0500
Subject: [Tutor] How to iterate and update subseqent items in list
In-Reply-To: <595529.21524.qm@web58801.mail.re1.yahoo.com>
References: <595529.21524.qm@web58801.mail.re1.yahoo.com>
Message-ID: <475850E3.6080509@alum.rpi.edu>

ted b wrote:
> Can you suggest a good way to iterate through the
> remainder of list and update them?
>
> Ex:
> Thing1.value = 0
> Thing2.value = 1
> Thing3.value = 0
> Thing4.value = 0
>
> Things = [Thing1, Thing2, Thing3, Thing4]
>
> I want to iterate through 'Things' and if
> 'Thing.value' > 0, then I want to set all values for
> that and the subsequent 'Things' in the list to 2
>
> So that i'd end up with
>
> Thing1.value = 0
> Thing2.value = 2
> Thing3.value = 2
> Thing4.value = 2
>
>   
import itertools
for thing in itertools.dropwhile(lambda x: x.value <= 0):
    thing.value = 2

This may appear less clear at first, but understanding itertools can be 
a great benefit for addressing a multitude of problems of this nature.

I suggest looking at the itertools module documentation, and wading thru 
dropwhile to understand it. Of course I also introduced lambda here, 
which is a shortcut to defining an anonymous function.

From trey at opmstech.org  Thu Dec  6 22:23:45 2007
From: trey at opmstech.org (Trey Keown)
Date: Thu, 6 Dec 2007 15:23:45 -0600 (CST)
Subject: [Tutor] Best way of learning
In-Reply-To: <47572988.6000403@dsl.pipex.com>
References: <47572988.6000403@dsl.pipex.com>
Message-ID: <16455.207.157.127.254.1196976225.squirrel@webmail.opmstech.org>

The way I learned python was through this wikibook:
http://en.wikibooks.org/wiki/Python_Programming

I found it very easy to understand and very helpful.


From walksloud at gmail.com  Thu Dec  6 23:05:08 2007
From: walksloud at gmail.com (Andre Walker-Loud)
Date: Thu, 6 Dec 2007 17:05:08 -0500
Subject: [Tutor] python precision output?
In-Reply-To: <16455.207.157.127.254.1196976225.squirrel@webmail.opmstech.org>
References: <47572988.6000403@dsl.pipex.com>
	<16455.207.157.127.254.1196976225.squirrel@webmail.opmstech.org>
Message-ID: <10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>

Hi there,

I am using python to do some scripting.  In particular, I am using it  
to run some jobs which require precision inputs.  I do this by having  
python write an input file, which I then feed to some other program.

The problem I am having is getting python to write number into this  
input file, keeping 16 digits of precision.  I have played around  
interactively, and see that python default prints 17 digits of  
precision to the screen, but when I use a replace command to write  
into the input file, it only prints 12 digits of precision.  The  
relevant snipit of my script is

value = float( int(ai) * 6 * math.pi / (int(L)*int(T))
replace = {'VALUE':str(value)}
ini_file = open('generic_ini').read()
f=open('my_input.xml','w')
f.write(ini_file % replace)
f.close()

where, "ai", "L" and "T" are process dependent numbers defined in my  
script, and the output "my_input.xml", is just an xml file I later  
feed to another program, and this is why I replace 'VALUE' with a  
string.

To reiterate, I need str(value) to be written to my file with 16  
digits of precision...???


Thanks,
Andre

From brunson at brunson.com  Thu Dec  6 23:21:35 2007
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 06 Dec 2007 15:21:35 -0700
Subject: [Tutor] python precision output?
In-Reply-To: <10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>
References: <47572988.6000403@dsl.pipex.com>	<16455.207.157.127.254.1196976225.squirrel@webmail.opmstech.org>
	<10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>
Message-ID: <475875EF.1040608@brunson.com>

Andre Walker-Loud wrote:
> Hi there,
>   

Hi Andre,

First of all, please don't start a new thread by replying to an existing 
thread, RFC compliant email readers will thread your post along with the 
original posting based on headers other than the Subject.  :-)

I don't think you'll ever get satisfactory precision using binary 
floating point (the default for python's float type).  Take a look at 
the decimal module, I believe it will give you much better results for 
your requirements.

Here is the module documentation:  
http://docs.python.org/lib/module-decimal.html

And an example of it's usage:

>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal("0.142857")
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal("0.1428571428571428571428571429")


Please post back if that doesn't help you out.

Sincerely,
e.

> I am using python to do some scripting.  In particular, I am using it  
> to run some jobs which require precision inputs.  I do this by having  
> python write an input file, which I then feed to some other program.
>
> The problem I am having is getting python to write number into this  
> input file, keeping 16 digits of precision.  I have played around  
> interactively, and see that python default prints 17 digits of  
> precision to the screen, but when I use a replace command to write  
> into the input file, it only prints 12 digits of precision.  The  
> relevant snipit of my script is
>
> value = float( int(ai) * 6 * math.pi / (int(L)*int(T))
> replace = {'VALUE':str(value)}
> ini_file = open('generic_ini').read()
> f=open('my_input.xml','w')
> f.write(ini_file % replace)
> f.close()
>
> where, "ai", "L" and "T" are process dependent numbers defined in my  
> script, and the output "my_input.xml", is just an xml file I later  
> feed to another program, and this is why I replace 'VALUE' with a  
> string.
>
> To reiterate, I need str(value) to be written to my file with 16  
> digits of precision...???
>
>
> Thanks,
> Andre
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From wescpy at gmail.com  Thu Dec  6 23:26:44 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 6 Dec 2007 14:26:44 -0800
Subject: [Tutor] python precision output?
In-Reply-To: <10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>
References: <47572988.6000403@dsl.pipex.com>
	<16455.207.157.127.254.1196976225.squirrel@webmail.opmstech.org>
	<10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>
Message-ID: <78b3a9580712061426j21a0cd25hd4a0de47ca6a6ac4@mail.gmail.com>

> The problem I am having is getting python to write number into this
> input file, keeping 16 digits of precision.  I have played around
> interactively, and see that python default prints 17 digits of
> precision to the screen, but when I use a replace command to write
> into the input file, it only prints 12 digits of precision.  The
> relevant snipit of my script is
>        :
> To reiterate, I need str(value) to be written to my file with 16
> digits of precision...???

if you want accuracy and are willing to sacrifice the total range of
numbers that Python's IEEE754 double-precision floats give you, then
use the decimal.Decimal class instead -- better precision, smaller
range.

however, if you wish to stick with floats, use the string format
operator and tell it you want 17 places after the decimal point:

>>> x=7./13
>>> x
0.53846153846153844
>>> str(x)
'0.538461538462'
>>> '%.17f' % x
'0.53846153846153844'

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

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

From wescpy at gmail.com  Thu Dec  6 23:48:08 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 6 Dec 2007 14:48:08 -0800
Subject: [Tutor] Best way of learning
In-Reply-To: <47572988.6000403@dsl.pipex.com>
References: <47572988.6000403@dsl.pipex.com>
Message-ID: <78b3a9580712061448w7edb8272r33947ead3faa035a@mail.gmail.com>

> Over a year ago I dabbled in learning Python, working my way through a
> few tutorials, the Deitel's  "How to program in Python" and Hetland's
> "Practical Python", until I came across the OOP sections. My mind just
> froze up, and I found myself wondering if I had really understood
> anything at all.
>        :
> I am happy to read, and have done a fair amount, but am concerned about
> getting too overwhelmed and confused again. I acknowledge and realise
> the value of practising by scripting programs and enjoy the intellectual
> challenge of the debugging process, and trying to think through the
> trick of a particular way of cracking a problem.
>
> So, after this long-winded introduction, I was hoping to pick the wisdom
> of this list to get some pointers of what to do/not to do to make the
> most effective use of the few hours I have to learn how to program using
> Python. So, any advice for someone in their mid-40s who would like to
> learn Python in a more methodical and effective manner?


hi there, and a belated welcome to Python.  the fact that you have
some coding under your belt really helps.  without being too much of a
shameless plug, you are a member of the target audience i wrote "Core
Python Programming" for:
you have some programming skills and want to learn Python quickly and
effectively.  the book has lots of small snippets that you should be
able to easily follow, plus there are both short and long, easy and
more difficult, exercises at the end of every chapter. check out the
philosophy behind the book (plus all kinds of reviews!) at the book's
website http://corepython.com

you can also find a link to downloading a free chapter on the
left-hand side too. as a programmer myself with over 10 years of
Python, i know what newbies need to know in order to become effective
in their new favorite language. :-) my goal as an instructor is to be
able to explain things in a simple enough manner that things are
clear, with the minimal amount of confusion, including the OOP
chapter. finally, my goal as the author is to merge all of this
together in an easy-to-swallow and conversational format along with
practical examples to solidify your newfound knowledge.  should i
mention i'm in your age group too?  ;-)

best of luck to you, and again, welcome to Python!
-- 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 walksloud at gmail.com  Thu Dec  6 23:50:02 2007
From: walksloud at gmail.com (Andre Walker-Loud)
Date: Thu, 6 Dec 2007 17:50:02 -0500
Subject: [Tutor] python precision output?
In-Reply-To: <78b3a9580712061426j21a0cd25hd4a0de47ca6a6ac4@mail.gmail.com>
References: <47572988.6000403@dsl.pipex.com>
	<16455.207.157.127.254.1196976225.squirrel@webmail.opmstech.org>
	<10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>
	<78b3a9580712061426j21a0cd25hd4a0de47ca6a6ac4@mail.gmail.com>
Message-ID: <EA2FF439-54B5-469B-AB78-28E2F916CBD7@gmail.com>

> if you want accuracy and are willing to sacrifice the total range of
> numbers that Python's IEEE754 double-precision floats give you, then
> use the decimal.Decimal class instead -- better precision, smaller
> range.
>
> however, if you wish to stick with floats, use the string format
> operator and tell it you want 17 places after the decimal point:
>
>>>> x=7./13
>>>> x
> 0.53846153846153844
>>>> str(x)
> '0.538461538462'
>>>> '%.17f' % x
> '0.53846153846153844'
>
> hope this helps!

This did the trick!  thanks,

Andre




> -- 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  Thu Dec  6 23:55:30 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 06 Dec 2007 17:55:30 -0500
Subject: [Tutor] python precision output?
In-Reply-To: <10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>
References: <47572988.6000403@dsl.pipex.com>	<16455.207.157.127.254.1196976225.squirrel@webmail.opmstech.org>
	<10231EDF-CBAF-4009-AF59-6CA20C0F656D@gmail.com>
Message-ID: <47587DE2.5000003@tds.net>

Andre Walker-Loud wrote:
> To reiterate, I need str(value) to be written to my file with 16  
> digits of precision...???

You can use string formatting to specify exactly how many decimal places 
to include:

In [1]: v=1.0/7
In [2]: v
Out[2]: 0.14285714285714285
In [3]: str(v)
Out[3]: '0.142857142857'
In [4]: '%.16f' % v
Out[4]: '0.1428571428571428'

Kent

From ricaraoz at gmail.com  Thu Dec  6 23:58:40 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 06 Dec 2007 19:58:40 -0300
Subject: [Tutor] Mail? What's that?
In-Reply-To: <003b01c8381e$97316430$a001a8c0@exbspider>
References: <003b01c8381e$97316430$a001a8c0@exbspider>
Message-ID: <47587EA0.5000700@bigfoot.com>

Justin Cardinal wrote:
> Ricardo Ar?oz wrote:
> 
>>Are From: To: Date: and Subject: mandatory in the contents of the
>>email(text)?  Do I have to put "real" address in  From when calling
>>sendmail()? And in the contents?
> 
> Here's the page I used to learn on this subject.
> http://www.thinkspot.net/sheila/article.php?story=20040822174141155
>  
> I'm definitely not a pro in this area, so what comes next are merely
> assumptions made after toying around a bit.
> I don't believe the From, To, Date, Subject are required, but if you
> play around sending some test messages to yourself, you'll see that
> excluding them makes the message look very suspicious. As far as using
> your real address, that might depend on your email server...but yes, you
> can most likely spoof other addresses. Please use this for good, not evil.
>  
> -Justin Cardinal

Thanks Justin.


From ds-python-tutor at sidorof.com  Fri Dec  7 00:05:44 2007
From: ds-python-tutor at sidorof.com (DS)
Date: Thu, 06 Dec 2007 15:05:44 -0800
Subject: [Tutor] commands module
Message-ID: <47588048.8020603@sidorof.com>

I've been trying to do something that I thought was going to be
relatively straight-forward, but so far I haven't found a good solution.

What I'm trying to do is discover a pid on a process and kill it.  The
way that I thought that I could do it is something along the lines of:

import commands

program = "someprogram"

a = commands.getoutput('ps ax|grep %s ' % (program))

Then, I'd parse the returned info get the pid and kill it, probably via
another command.

However, what happens is that the "ps ax" portion truncates the listing
at 158 characters.  It just so happens that the unique name that I need
in the list comes after that.  So, works from the bash shell, but
doesn't work using getoutput.

I have also tried variations on a theme.  For example, I created a shell
file and tried to route into a file:
ps ax|grep my_program_name > ps.output

No luck.

Do you have any suggestions?




From evert.rol at gmail.com  Fri Dec  7 00:31:46 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 6 Dec 2007 23:31:46 +0000
Subject: [Tutor] commands module
In-Reply-To: <47588048.8020603@sidorof.com>
References: <47588048.8020603@sidorof.com>
Message-ID: <9A6E89D0-F26A-4A97-BAAB-315D7AF005BC@gmail.com>

> I've been trying to do something that I thought was going to be
> relatively straight-forward, but so far I haven't found a good  
> solution.
>
> What I'm trying to do is discover a pid on a process and kill it.  The
> way that I thought that I could do it is something along the lines of:
>
> import commands
>
> program = "someprogram"
>
> a = commands.getoutput('ps ax|grep %s ' % (program))
>
> Then, I'd parse the returned info get the pid and kill it, probably  
> via
> another command.
>
> However, what happens is that the "ps ax" portion truncates the  
> listing
> at 158 characters.  It just so happens that the unique name that I  
> need
> in the list comes after that.  So, works from the bash shell, but
> doesn't work using getoutput.

What's the result of getoutput(); ie, what is a?
Note that bash and commands.getoutput() are not the same, since the  
latter executes 'sh -c', which is slightly different. I don't expect  
that'll solve your problem.
Does the -w option help? I'm guessing it won't, since the truncation  
seem to be due to some odd character causing an EOF or something (I  
tried myself here, both on Linux & OS X, without problems).

   Evert


From ds-python-tutor at sidorof.com  Fri Dec  7 02:58:58 2007
From: ds-python-tutor at sidorof.com (ds)
Date: Thu, 06 Dec 2007 17:58:58 -0800
Subject: [Tutor] commands module (Forwarded back to list)
Message-ID: <4758A8E2.10604@sidorof.com>

Evert Rol wrote:

>> >> I've been trying to do something that I thought was going to be
>> >> relatively straight-forward, but so far I haven't found a good solution.
>> >>
>> >> What I'm trying to do is discover a pid on a process and kill it.  The
>> >> way that I thought that I could do it is something along the lines of:
>> >>
>> >> import commands
>> >>
>> >> program = "someprogram"
>> >>
>> >> a = commands.getoutput('ps ax|grep %s ' % (program))
>> >>
>> >> Then, I'd parse the returned info get the pid and kill it, probably via
>> >> another command.
>> >>
>> >> However, what happens is that the "ps ax" portion truncates the listing
>> >> at 158 characters.  It just so happens that the unique name that I need
>> >> in the list comes after that.  So, works from the bash shell, but
>> >> doesn't work using getoutput.
>>     
> >
> > What's the result of getoutput(); ie, what is a?
> > Note that bash and commands.getoutput() are not the same, since the
> > latter executes 'sh -c', which is slightly different. I don't expect
> > that'll solve your problem.
> > Does the -w option help? I'm guessing it won't, since the truncation
> > seem to be due to some odd character causing an EOF or something (I
> > tried myself here, both on Linux & OS X, without problems).
> >
> >   Evert
>   


I accidentally sent this directly rather than to the list:

Thanks for your reply.  When I said 158 characters I was trying to say
each _line_ of the shell command "ps ax" was truncated to 158
characters, not that the _total_ returned was 158. 

Your question got me thinking about it, and I found in my set variables:
COLUMNS=158, which corresponds pretty well.
So, I tried setting COLUMNS equal to 500 (arbitrarily large) prior to
going into python.  It seems to change back to 158 automatically however.
For example, when I go into python, import commands, and execute
commands.getoutput('set') I find that COLUMNS is back to 158.  So, I
think my problem is that I don't know how to alter the set variable so
that it will stick long enough for the "ps ax" command to execute properly.


==========================
End of forwarded message part.


Finally, I have solved the problem, because I discovered a width option on the ps command, which I hadn't been aware of before.

For example:

commands.getstatusoutput('ps ax -l --width 500')

works very well by over-riding any defaults.

Thanks for your help.

ds





From evert.rol at gmail.com  Fri Dec  7 04:09:44 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 7 Dec 2007 03:09:44 +0000
Subject: [Tutor] commands module (Forwarded back to list)
In-Reply-To: <4758A8E2.10604@sidorof.com>
References: <4758A8E2.10604@sidorof.com>
Message-ID: <CC0A7439-5704-4D01-90C0-906524255D0E@gmail.com>

> So, I tried setting COLUMNS equal to 500 (arbitrarily large) prior to
> going into python.  It seems to change back to 158 automatically  
> however.
> For example, when I go into python, import commands, and execute
> commands.getoutput('set') I find that COLUMNS is back to 158.  So, I
> think my problem is that I don't know how to alter the set variable so
> that it will stick long enough for the "ps ax" command to execute  
> properly.

I've had this problem before (setting/altering shell variables when  
executing a command from Python, albeit using os.system() instead).  
What I'd use is:
commands.getoutput('COLUMNS=500 ps ax')
or similar. In your case, you've been able to solve in another way  
(and better, since environment independent, though still shell/ps- 
variant dependent), but sometimes one may need to set/change shell  
variables, like paths to dynamic libraries. The above should work  
(for more variables, just specify them all before the actual command,  
whitespace separated).



From no.spam.keep.this at ntlworld.com  Fri Dec  7 05:42:19 2007
From: no.spam.keep.this at ntlworld.com (John Merritt)
Date: Fri, 7 Dec 2007 04:42:19 -0000
Subject: [Tutor] unsubscribe
Message-ID: <000001c8388b$8e78a520$ab69ef60$@spam.keep.this@ntlworld.com>

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071207/bfb88b87/attachment.htm 

From earlylightpublishing at yahoo.com  Fri Dec  7 06:11:42 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Thu, 6 Dec 2007 21:11:42 -0800 (PST)
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <mailman.8882.1196992748.13604.tutor@python.org>
Message-ID: <961777.86332.qm@web45116.mail.sp1.yahoo.com>

Hello all,
   
  I now have my bit of code in while loop form and it works!  It's great but not exactly what I wanted to do.  I've been googling my heart out and I find lots of info on while loops and lots of info on timers that will execute an action AFTER a given interval but nothing on a timer that will execute an action DURING a given interval.  What I'd really like to do at this point in my game is have the player execute the loop for 30 seconds then have it print the final score and break.  Does anyone out there have any code that'll do that?
   
  Here's what I've got.  I'm sure it ain't pretty and I'm happy to hear suggestions on cleaning it up as well.  I know it needs some def's in there and possibly a class too.
   
  import random
  startNum = random.choice(range(1, 9))
print 'Start with the number ', startNum,'.  Then continuously add 7 to that number until the timer runs out.  You have 30 seconds.'
score = 0
answer = int(raw_input('Enter your answer: '))
while (score < 50):
    startNum = startNum + 7
    if startNum == answer:
        print 'That is correct!'
        score = score + 5
        print 'Your score is ', score
        
        answer = int(raw_input('Enter your answer: '))
    else:
        print 'That is incorrect.  Game over. Your final score is ', score
        break
else:
    print 'You win! Your final score is ', score

   
   

       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/80f190f4/attachment.htm 

From ds-python-tutor at sidorof.com  Fri Dec  7 07:24:10 2007
From: ds-python-tutor at sidorof.com (ds)
Date: Thu, 06 Dec 2007 22:24:10 -0800
Subject: [Tutor] commands module
In-Reply-To: <CC0A7439-5704-4D01-90C0-906524255D0E@gmail.com>
References: <4758A8E2.10604@sidorof.com>
	<CC0A7439-5704-4D01-90C0-906524255D0E@gmail.com>
Message-ID: <4758E70A.3090906@sidorof.com>

Evert Rol wrote:
>> So, I tried setting COLUMNS equal to 500 (arbitrarily large) prior to
>> going into python.  It seems to change back to 158 automatically
>> however.
>> For example, when I go into python, import commands, and execute
>> commands.getoutput('set') I find that COLUMNS is back to 158.  So, I
>> think my problem is that I don't know how to alter the set variable so
>> that it will stick long enough for the "ps ax" command to execute
>> properly.
>
> I've had this problem before (setting/altering shell variables when
> executing a command from Python, albeit using os.system() instead).
> What I'd use is:
> commands.getoutput('COLUMNS=500 ps ax')
> or similar. In your case, you've been able to solve in another way
> (and better, since environment independent, though still
> shell/ps-variant dependent), but sometimes one may need to set/change
> shell variables, like paths to dynamic libraries. The above should
> work (for more variables, just specify them all before the actual
> command, whitespace separated).
>
>
Thank you for mentioning that.  I'm pretty weak on bash, and had
monkeyed around with such things as set COLUMNS=500 on the previous line
in the shell program version, but hadn't actually looked up that syntax
yet, when I stumbled across the ps parameter that eventually I selected.

Thanks again.

ds

From wtfwhoami at gmail.com  Fri Dec  7 12:42:31 2007
From: wtfwhoami at gmail.com (Guess?!?)
Date: Fri, 7 Dec 2007 03:42:31 -0800
Subject: [Tutor] Python N00bi - Tough Cookie
Message-ID: <8c64f3990712070342g3465ad95i8e557441e424bff6@mail.gmail.com>

Hello All,

I want trying to write a program that searches all the files (recursively)
under a given directory in the filesystem for phone
 numbers in the form of (626) 674-5901 and  and then outputting all phone
numbers found in a unique format 626-674


(If several numbers have the same office code, there should be only one line
of output for that office code.)

There are following requirments
1> Search for a pattern in all files in a directory
2> Outputing the result with a unique format ( (626) 674-5901 -> 626-674 )
3> if the result has new office code (which I am guessing first 3 digits --
626) -- add to new line
   if the result has office code already in the list then append


~~~~~~~~

I have generated the regular expression for the pattern ....  and have
tested it also....

\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}

>>> import re
>>> p = re.compile('\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}')
>>> p = re.compile('\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}')
>>> p
<_sre.SRE_Pattern object at 0x00C400B8>
>>> p
<_sre.SRE_Pattern object at 0x00C400B8>
>>> print p.match("")
None
>>> print p.match('(619) 223-1212')
<_sre.SRE_Match object at 0x00A3F678>

I need options to proceed after finding the match in the files.....

++++++++++++++++++++++++++++++++
I was thinking to find all filenames in the directory using something like
....

import os
path="C:\\somedirectory"  # insert the path to the directory of interest
here
dirList=os.listdir(path)
for fname in dirList:
    print fname

Am I thinking correct ???

~Thanks
Geo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071207/b4fdd313/attachment.htm 

From kent37 at tds.net  Fri Dec  7 15:32:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 07 Dec 2007 09:32:43 -0500
Subject: [Tutor] Python N00bi - Tough Cookie
In-Reply-To: <8c64f3990712070342g3465ad95i8e557441e424bff6@mail.gmail.com>
References: <8c64f3990712070342g3465ad95i8e557441e424bff6@mail.gmail.com>
Message-ID: <4759598B.5010103@tds.net>

Guess?!? wrote:
> Hello All,
>  
> I want trying to write a program that searches all the files ( 
> recursively) under a given directory in the filesystem

> There are following requirments
> 1> Search for a pattern in all files in a directory
> 2> Outputing the result with a unique format ( (626) 674-5901 -> 626-674 )
> 3> if the result has new office code (which I am guessing first 3 digits 
> -- 626) -- add to new line
>    if the result has office code already in the list then append
>  
>  
> ~~~~~~~~
>  
> I have generated the regular expression for the pattern ....  and have 
> tested it also....
>  
> \([0-9]{3}\)\s[0-9]{3}-[0-9]{4}
>  
>> >> import re
>> >> p = re.compile('\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}')
>> >> p = re.compile('\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}')
>> >> p
> <_sre.SRE_Pattern object at 0x00C400B8>
>> >> p
> <_sre.SRE_Pattern object at 0x00C400B8>
>> >> print p.match("")
> None
>> >> print p.match('(619) 223-1212')
> <_sre.SRE_Match object at 0x00A3F678>
>  
> I need options to proceed after finding the match in the files.....

You can replace text using p.sub() (re.sub)

> ++++++++++++++++++++++++++++++++
> I was thinking to find all filenames in the directory using something 
> like ....
>  
> import os
> path="C:\\somedirectory"  # insert the path to the directory of interest
> here
> dirList=os.listdir(path)
> for fname in dirList:
>     print fname
>  
> Am I thinking correct ???

Yes, did you try this code? It looks good to me.

To open the file you have to construct the full path, e.g.
fpath = os.path.join(path, fname)
f = open(fpath)
data = f.read()
f.close()

Then you can process the data with your regex and write it back out.

Kent

From bgailer at alum.rpi.edu  Fri Dec  7 16:41:30 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 07 Dec 2007 10:41:30 -0500
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <961777.86332.qm@web45116.mail.sp1.yahoo.com>
References: <961777.86332.qm@web45116.mail.sp1.yahoo.com>
Message-ID: <475969AA.3080509@alum.rpi.edu>

earlylight publishing wrote:
> Hello all,
>  
> I now have my bit of code in while loop form and it works!  It's great 
> but not exactly what I wanted to do.  I've been googling my heart out 
> and I find lots of info on while loops and lots of info on timers that 
> will execute an action AFTER a given interval but nothing on a timer 
> that will execute an action DURING a given interval.  What I'd really 
> like to do at this point in my game is have the player execute the 
> loop for 30 seconds then have it print the final score and break.  
> Does anyone out there have any code that'll do that?
import time
start = time.time()
raw_input("Wait a few seconds, then press enter to continue.")
print time.time() - start

Does that give you a hint?

You don't need a timer, unless you want to interrupt the user if he is 
not entering anything.


From bhaaluu at gmail.com  Fri Dec  7 17:31:16 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Fri, 7 Dec 2007 11:31:16 -0500
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <475969AA.3080509@alum.rpi.edu>
References: <961777.86332.qm@web45116.mail.sp1.yahoo.com>
	<475969AA.3080509@alum.rpi.edu>
Message-ID: <ea979d70712070831i73af316dl6a5f3ed731654ec@mail.gmail.com>

On Dec 7, 2007 10:41 AM, bob gailer <bgailer at alum.rpi.edu> wrote:
> earlylight publishing wrote:
> > Hello all,
> >
> > I now have my bit of code in while loop form and it works!  It's great
> > but not exactly what I wanted to do.  I've been googling my heart out
> > and I find lots of info on while loops and lots of info on timers that
> > will execute an action AFTER a given interval but nothing on a timer
> > that will execute an action DURING a given interval.  What I'd really
> > like to do at this point in my game is have the player execute the
> > loop for 30 seconds then have it print the final score and break.
> > Does anyone out there have any code that'll do that?

> import time
> start = time.time()
> raw_input("Wait a few seconds, then press enter to continue.")
> print time.time() - start
>
> Does that give you a hint?
>
> You don't need a timer, unless you want to interrupt the user if he is
> not entering anything.

Cool snippet! So if the player is entering numbers to an adding game,
and he has to continue entering numbers for 30 seconds, then it could
be accomplished with something similar to this, right?

import time
start = time.time()
while 1:
    raw_input("Press <Enter> Now!")
    if time.time() - start < 30.0:
        print time.time() - start
    else: break

Thanks! 8^D
Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

From bgailer at alum.rpi.edu  Fri Dec  7 19:20:44 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 07 Dec 2007 13:20:44 -0500
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <ea979d70712070831i73af316dl6a5f3ed731654ec@mail.gmail.com>
References: <961777.86332.qm@web45116.mail.sp1.yahoo.com>	<475969AA.3080509@alum.rpi.edu>
	<ea979d70712070831i73af316dl6a5f3ed731654ec@mail.gmail.com>
Message-ID: <47598EFC.1060803@alum.rpi.edu>

bhaaluu wrote:
> On Dec 7, 2007 10:41 AM, bob gailer <bgailer at alum.rpi.edu> wrote:
>   
>> earlylight publishing wrote:
>>     
>>> Hello all,
>>>
>>> I now have my bit of code in while loop form and it works!  It's great
>>> but not exactly what I wanted to do.  I've been googling my heart out
>>> and I find lots of info on while loops and lots of info on timers that
>>> will execute an action AFTER a given interval but nothing on a timer
>>> that will execute an action DURING a given interval.  What I'd really
>>> like to do at this point in my game is have the player execute the
>>> loop for 30 seconds then have it print the final score and break.
>>> Does anyone out there have any code that'll do that?
>>>       
>
>   
>> import time
>> start = time.time()
>> raw_input("Wait a few seconds, then press enter to continue.")
>> print time.time() - start
>>
>> Does that give you a hint?
>>
>> You don't need a timer, unless you want to interrupt the user if he is
>> not entering anything.
>>     
>
> Cool snippet! So if the player is entering numbers to an adding game,
> and he has to continue entering numbers for 30 seconds, then it could
> be accomplished with something similar to this, right?
>
> import time
> start = time.time()
> while 1:
>     raw_input("Press <Enter> Now!")
>     if time.time() - start < 30.0:
>         print time.time() - start
>     else: break
>   
Even simpler?

import time
start = time.time()
while time.time() - start < 30.0:
    raw_input("Press <Enter> Now!")
    print time.time() - start




From bhaaluu at gmail.com  Fri Dec  7 20:54:23 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Fri, 7 Dec 2007 14:54:23 -0500
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <4759A0B4.4090507@signalmtnlodge.com>
References: <961777.86332.qm@web45116.mail.sp1.yahoo.com>
	<475969AA.3080509@alum.rpi.edu>
	<ea979d70712070831i73af316dl6a5f3ed731654ec@mail.gmail.com>
	<47598EFC.1060803@alum.rpi.edu> <4759A0B4.4090507@signalmtnlodge.com>
Message-ID: <ea979d70712071154v6b2973b3g5c942bcbc9a39a78@mail.gmail.com>

On Dec 7, 2007 2:36 PM, Scottie Hotchkiss <shotchkiss at signalmtnlodge.com> wrote:
> Disclaimer: I can't test this while I'm at work, but using
>
> "while 1:"
>
> instead of
>
> "while time.time() - start < 30.0"
>
> would be better.
>
> In the former case if you press enter after time has run out, it won't
> print the time, in the latter you could potentially make a correct
> answer after time has  run out.
>
> Example: At 29.0 you answer
> raw_input awaits and you wait 5 minutes, then answer.
> It will still run the print statement. The loop started and it doesn't
> matter how long you wait, because it won't evaluate that until the loop
> starts again.
>
> But it may alright depending on what you are trying to accomplish.
>
> Just my 2 cents,
> S Hotchkiss
>
> Tutor Lurker
>

Okay! Here's a sample 30-second Adding Game using time.time()
and a while True: loop. The timing granularity isn't all that great.
Sometimes it times out 2 or 3 seconds past 30 seconds, but in
this case, it probably isn't a big deal. This has been tested with
Python 2.4.3 running on Linux kernel 2.6.15 from the vim editor!

#!/usr/bin/python
import random
import time

startNum = random.choice(range(1, 9))
score = 0

print "#"*65
print " "*14,"Welcome to the 30-second Adding Game!"
print "#"*65
print " "* 5,"Instructions:"
print " "*10,"You'll choose a number."
print " "*10,"You'll be given a starting number."
print " "*10,"Add the number you chose to the starting number,"
print " "*10,"then keep adding your number to the sum until"
print " "*10,"the timer runs out."
print " "*10,"You'll have 30 seconds."
print " "* 5,
num2add = raw_input(" Choose a number to add: ")
print raw_input(" Press <Enter> when you're ready to begin.")
print "#"*65
num2add = int(num2add) # interpolation
newNum = startNum + num2add
print " Start with the number ", startNum
start = time.time()
while True:
    if time.time() - start < 30.0:
        answer = int(raw_input(" Enter your answer: "))
        if answer == newNum:
             print " That is correct!  Keep going."
             score = score + 5
             newNum = newNum + num2add
             print " Your score is ", score
        else:
             print " That is incorrect.  Please try again."
             print " Hurry! You only have %2.1f seconds left!"\
                     % (30 - (time.time() - start))
    else:
        break

print " Buzzz!!! Time's up!"
print time.time() - start
#print "\n"
print " Your total score was: ", score


Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

From shotchkiss at signalmtnlodge.com  Fri Dec  7 20:36:20 2007
From: shotchkiss at signalmtnlodge.com (Scottie Hotchkiss)
Date: Fri, 07 Dec 2007 12:36:20 -0700
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <47598EFC.1060803@alum.rpi.edu>
References: <961777.86332.qm@web45116.mail.sp1.yahoo.com>	<475969AA.3080509@alum.rpi.edu>	<ea979d70712070831i73af316dl6a5f3ed731654ec@mail.gmail.com>
	<47598EFC.1060803@alum.rpi.edu>
Message-ID: <4759A0B4.4090507@signalmtnlodge.com>

Disclaimer: I can't test this while I'm at work, but using

"while 1:"

instead of

"while time.time() - start < 30.0"

would be better.

In the former case if you press enter after time has run out, it won't 
print the time, in the latter you could potentially make a correct 
answer after time has  run out.

Example: At 29.0 you answer
raw_input awaits and you wait 5 minutes, then answer.
It will still run the print statement. The loop started and it doesn't 
matter how long you wait, because it won't evaluate that until the loop 
starts again.

But it may alright depending on what you are trying to accomplish.

Just my 2 cents,
S Hotchkiss

Tutor Lurker

From ricaraoz at gmail.com  Fri Dec  7 13:18:43 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 07 Dec 2007 09:18:43 -0300
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <961777.86332.qm@web45116.mail.sp1.yahoo.com>
References: <961777.86332.qm@web45116.mail.sp1.yahoo.com>
Message-ID: <47593A23.6030208@bigfoot.com>

earlylight publishing wrote:
> Hello all,
>  
> I now have my bit of code in while loop form and it works!  It's great
> but not exactly what I wanted to do.  I've been googling my heart out
> and I find lots of info on while loops and lots of info on timers that
> will execute an action AFTER a given interval but nothing on a timer
> that will execute an action DURING a given interval.  What I'd really
> like to do at this point in my game is have the player execute the loop
> for 30 seconds then have it print the final score and break.  Does
> anyone out there have any code that'll do that?
>  
> Here's what I've got.  I'm sure it ain't pretty and I'm happy to hear
> suggestions on cleaning it up as well.  I know it needs some def's in
> there and possibly a class too.
>  
> import random

import time

> startNum = random.choice(range(1, 9))
> print 'Start with the number ', startNum,'.  Then continuously add 7 to
> that number until the timer runs out.  You have 30 seconds.'
> score = 0

  start_time = time.clock()

> answer = int(raw_input('Enter your answer: '))
> while (score < 50):
>     startNum = startNum + 7
>     if startNum == answer:
>         print 'That is correct!'
>         score = score + 5
>         print 'Your score is ', score

      if (time.clock() - start_time) >= 30
          print 'Time's out. Game over. Your final score is ', score
          break

>        
>         answer = int(raw_input('Enter your answer: '))
>     else:
>         print 'That is incorrect.  Game over. Your final score is ', score
>         break
> else:
>     print 'You win! Your final score is ', score
>  
>  


From globophobe at gmail.com  Fri Dec  7 23:34:15 2007
From: globophobe at gmail.com (Luis N)
Date: Sat, 8 Dec 2007 07:34:15 +0900
Subject: [Tutor] Still Can't Find Timed While Loops
Message-ID: <c6e072940712071434o2c5b7116l60f02ec7bb5f4cea@mail.gmail.com>

I can't recall what your initial project was. I think it was a text
adventure. I imagine that you have bigger ideas regarding timers then
your current code suggests. Maybe you should investigate a time aware
long-running process. Twisted Python is such a beast.

While I can't recommend it's use as it's probably over your head and
certainly over mine, there is some code out there for a text adventure
using Twisted Python. I think the codebase is called Twisted Reality
now.

Luis

From rdm at rcblue.com  Sat Dec  8 09:29:02 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 08 Dec 2007 00:29:02 -0800
Subject: [Tutor] Still Can't Find Timed While Loops
In-Reply-To: <961777.86332.qm@web45116.mail.sp1.yahoo.com>
References: <mailman.8882.1196992748.13604.tutor@python.org>
	<961777.86332.qm@web45116.mail.sp1.yahoo.com>
Message-ID: <20071208082908.148891E401B@bag.python.org>

At 09:11 PM 12/6/2007, earlylight publishing wrote:
>Hello all,
>
>I now have my bit of code in while loop form and it works!  It's 
>great but not exactly what I wanted to do.  I've been googling my 
>heart out and I find lots of info on while loops and lots of info on 
>timers that will execute an action AFTER a given interval but 
>nothing on a timer that will execute an action DURING a given 
>interval.  What I'd really like to do at this point in my game is 
>have the player execute the loop for 30 seconds then have it print 
>the final score and break.  Does anyone out there have any code 
>that'll do that?

Did you miss this reply to an earlier post of yours?: 
<http://mail.python.org/pipermail/tutor/2007-December/058952.html> 
Doesn't that code do what you want?

Dick Moores



From tiagosaboga at terra.com.br  Sat Dec  8 10:25:16 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Sat, 8 Dec 2007 07:25:16 -0200
Subject: [Tutor] logic for a tree like structure
Message-ID: <20071208092516.GB19208@localdomain>

Hi,

I need an additional thread in my app, and I am trying to understand
how it works. Alas, all I found about threads is too simple (does not
fit in my real life problem) or too complicated. The best thing I've
read until now is the great tutorial by Norman Matloff, but it isn't
enough. If you could point me to some more docs, it would be great.
The python docs have been of no use for me in this case.

Anyway, I am trying to play a little with it, and I can't understand
what's happening in this simple example. I want to establish a
connection between my two threads by a os.pipe, but it seems like I
can only read the pipe when everything was done. I was hoping to see
the output of writer.py come out in real time, but it is coming out
all together when writer.py returns. Why?

Thanks,

Tiago Saboga.

=====writer.py=======

#!/usr/bin/python2.5

import time

for i in range(10):
    print 'Line number %s.' % i
    time.sleep(1)

======threadit.py=======
#!/usr/bin/python2.5

from __future__ import with_statement
import thread
import subprocess
import os

def run(out):
    subprocess.Popen(['./writer.py'], stdout=os.fdopen(out, 'w'))

def main():
    out_r, out_w = os.pipe()
    thread.start_new_thread(run, (out_w,))
    with os.fdopen(out_r) as f:
        while True:
            line=f.readline()
            if line:
                print '[main]', line

if __name__=='__main__':
    main()

From tiagosaboga at terra.com.br  Sat Dec  8 11:35:43 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Sat, 8 Dec 2007 08:35:43 -0200
Subject: [Tutor] thread and os.pipe (was: logic for a tree like structure)
In-Reply-To: <20071208092516.GB19208@localdomain>
References: <20071208092516.GB19208@localdomain>
Message-ID: <20071208103543.GC19208@localdomain>

I started a message, changed my mind, wrote about some other thing and
forgot to change the subject. Sorry for the noise.

Tiago.


On Sat, Dec 08, 2007 at 07:25:16AM -0200, Tiago Saboga wrote:
> Hi,
> 
> I need an additional thread in my app, and I am trying to understand
> how it works. Alas, all I found about threads is too simple (does not
> fit in my real life problem) or too complicated. The best thing I've
> read until now is the great tutorial by Norman Matloff, but it isn't
> enough. If you could point me to some more docs, it would be great.
> The python docs have been of no use for me in this case.
> 
> Anyway, I am trying to play a little with it, and I can't understand
> what's happening in this simple example. I want to establish a
> connection between my two threads by a os.pipe, but it seems like I
> can only read the pipe when everything was done. I was hoping to see
> the output of writer.py come out in real time, but it is coming out
> all together when writer.py returns. Why?
> 
> Thanks,
> 
> Tiago Saboga.
> 
> =====writer.py=======
> 
> #!/usr/bin/python2.5
> 
> import time
> 
> for i in range(10):
>     print 'Line number %s.' % i
>     time.sleep(1)
> 
> ======threadit.py=======
> #!/usr/bin/python2.5
> 
> from __future__ import with_statement
> import thread
> import subprocess
> import os
> 
> def run(out):
>     subprocess.Popen(['./writer.py'], stdout=os.fdopen(out, 'w'))
> 
> def main():
>     out_r, out_w = os.pipe()
>     thread.start_new_thread(run, (out_w,))
>     with os.fdopen(out_r) as f:
>         while True:
>             line=f.readline()
>             if line:
>                 print '[main]', line
> 
> if __name__=='__main__':
>     main()
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From rdm at rcblue.com  Sat Dec  8 12:35:14 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 08 Dec 2007 03:35:14 -0800
Subject: [Tutor] Best way of learning
In-Reply-To: <47572988.6000403@dsl.pipex.com>
References: <47572988.6000403@dsl.pipex.com>
Message-ID: <20071208113519.AA13A1E400B@bag.python.org>

At 02:43 PM 12/5/2007, andy wrote:
>Over a year ago I dabbled in learning Python, working my way through a
>few tutorials, the Deitel's  "How to program in Python" and Hetland's
>"Practical Python", until I came across the OOP sections. My mind just
>froze up, and I found myself wondering if I had really understood
>anything at all. In addition to which I didn't have any "itch" that I
>needed to scratch so was trying to learn something without any purpose.
>So I stopped.

Take a look at a book just out, Object-Oriented Programming in 
Python, <http://www.bestbookdeal.com/book/detail/0136150314>.  I'm 
hoping it will unfreeze my mind about OOP.

Dick Moores



From alan.gauld at btinternet.com  Sat Dec  8 12:54:07 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 8 Dec 2007 11:54:07 -0000
Subject: [Tutor] thread and os.pipe (was: logic for a tree like
	structure)
References: <20071208092516.GB19208@localdomain>
	<20071208103543.GC19208@localdomain>
Message-ID: <fje0l8$l1s$1@ger.gmane.org>

"Tiago Saboga" <tiagosaboga at terra.com.br> wrote

> what's happening in this simple example. I want to establish a
> connection between my two threads by a os.pipe,

While its possible to use a pipe to communicate within a process
its not very helpful and very rarely done. Usially queues are used
for communication between threads

> I was hoping to see the output of writer.py come out in real time

But you aren't really using a thrwad in your code you are
spawning a new subprocess using Popen and reading the
output of that from a pipe. are you sure you really need to
do that in a thread? You can simply dip into the pipe and
read it on demand. The usual case for a thread is when
you want to perform two tasks concurrently within the same
process, not to run another parallel process.,

> ... but it is coming out all together when writer.py returns. Why?

Dunno, it depends on what writer.py is doing. If its writing
to stdout then the puipe should be able to read the rewsults
as you go.

>> from __future__ import with_statement
>> import thread
>> import subprocess
>> import os
>>
>> def run(out):
>>     subprocess.Popen(['./writer.py'], stdout=os.fdopen(out, 'w'))
>>
>> def main():
>>     out_r, out_w = os.pipe()
>>     thread.start_new_thread(run, (out_w,))

Why not just set up outw to the output of Popen?
Using the subprocess pattern:

pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout

or in your case:

f = subprocess.Popen(['./writer.py'], shell=True, 
stdout=subprocess.PIPE).stdout


>>     with os.fdopen(out_r) as f:

So you don't need this

>>         while True:
>>             line=f.readline()
>>             if line:
>>                 print '[main]', line

And this should just work.

And if you really want to do something else wehile the output of 
writer
is being collected put all of the above into your run function.

Its not clear to me that you really need a thread here? A simpler
approach may work better.

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



From earlylightpublishing at yahoo.com  Sat Dec  8 15:25:28 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Sat, 8 Dec 2007 06:25:28 -0800 (PST)
Subject: [Tutor] Timed While Loops Thank You
In-Reply-To: <mailman.8988.1197057269.13604.tutor@python.org>
Message-ID: <124083.89292.qm@web45105.mail.sp1.yahoo.com>

Thank you all so much for your patience and help!  I haven't had a chance to try any of the code yet (gotta go be a mommy first)  :^)  I look forward to sitting down and playing around with it this evening though!  I also finally found a book that seems to fit my learning style well.  Hopefully it'll answer some of my more basic questions so I can save the tough stuff for the list.  Thanks again to everyone.  Have a great weekend!


Please visit our website www.earlylightpublishing.com
       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071208/d341793d/attachment.htm 

From ricaraoz at gmail.com  Sat Dec  8 22:45:48 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 08 Dec 2007 18:45:48 -0300
Subject: [Tutor] Sleeping it out
Message-ID: <475B108C.20208@bigfoot.com>

Hi, I have this code :

import time
L = [i for i in xrange(20)]
for n, i in enumerate(L) :
    if n%3 == 0 and n > 0 :
        print 'waiting 3 seconds'
        time.sleep(3)
    print i

I'm using Py 2.51 and PyAlaMode. It works ok but instead of printing in
groups of three, it will go through the program but the printing will
appear all at once at the end of the loop. Is there any way to flush the
output?

From brunson at brunson.com  Sat Dec  8 22:56:01 2007
From: brunson at brunson.com (Eric Brunson)
Date: Sat, 08 Dec 2007 14:56:01 -0700
Subject: [Tutor] Sleeping it out
In-Reply-To: <475B108C.20208@bigfoot.com>
References: <475B108C.20208@bigfoot.com>
Message-ID: <475B12F1.1010905@brunson.com>


Yes, import sys, then sys.stdout.flush() when you need it.


Ricardo Ar?oz wrote:
> Hi, I have this code :
>
> import time
> L = [i for i in xrange(20)]
> for n, i in enumerate(L) :
>     if n%3 == 0 and n > 0 :
>         print 'waiting 3 seconds'
>         time.sleep(3)
>     print i
>
> I'm using Py 2.51 and PyAlaMode. It works ok but instead of printing in
> groups of three, it will go through the program but the printing will
> appear all at once at the end of the loop. Is there any way to flush the
> output?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From tiagosaboga at terra.com.br  Sat Dec  8 23:03:19 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Sat, 8 Dec 2007 20:03:19 -0200
Subject: [Tutor] thread and os.pipe
In-Reply-To: <fje0l8$l1s$1@ger.gmane.org>
References: <20071208092516.GB19208@localdomain>
	<20071208103543.GC19208@localdomain> <fje0l8$l1s$1@ger.gmane.org>
Message-ID: <20071208220319.GA20392@localdomain>

On Sat, Dec 08, 2007 at 11:54:07AM -0000, Alan Gauld wrote:
> "Tiago Saboga" <tiagosaboga at terra.com.br> wrote
> 
> > what's happening in this simple example. I want to establish a
> > connection between my two threads by a os.pipe,
> 
> While its possible to use a pipe to communicate within a process
> its not very helpful and very rarely done. Usially queues are used
> for communication between threads

I find - and while googling I discovered I am not alone - very
difficult to grasp all details of thread programming. I am trying to
keep it simple, it's why I have chosen this way. 

> > I was hoping to see the output of writer.py come out in real time
> 
> But you aren't really using a thrwad in your code you are
> spawning a new subprocess using Popen and reading the
> output of that from a pipe. are you sure you really need to
> do that in a thread? 

This was just a sandbox; I am trying to make something very simple
work before applying it to my program.

> You can simply dip into the pipe and
> read it on demand. The usual case for a thread is when
> you want to perform two tasks concurrently within the same
> process, not to run another parallel process.,
> 
> > ... but it is coming out all together when writer.py returns. Why?
> 
> Dunno, it depends on what writer.py is doing. If its writing
> to stdout then the puipe should be able to read the rewsults
> as you go.

The writer.py file was included in my mail. ;)
It just prints out a test line every few seconds. As I said, it's just
a test.

> 
> >> from __future__ import with_statement
> >> import thread
> >> import subprocess
> >> import os
> >>
> >> def run(out):
> >>     subprocess.Popen(['./writer.py'], stdout=os.fdopen(out, 'w'))
> >>
> >> def main():
> >>     out_r, out_w = os.pipe()
> >>     thread.start_new_thread(run, (out_w,))
> 
> Why not just set up outw to the output of Popen?

Because in the more complicated case, the run function would have
several steps, including some external processes with Popen. The run()
function will take care of determining which processes will run,
according to the returncode of the first process), and will have to do
some cleaning in the end. But as this happens, I want my my main()
function to analyse and print the output from the Popen while the
external processes are running. This is what I wanted in this simple
test. I am sorry if I am not clear enough, I am still learning both
python and english!

As for the real program I am making, it's a gui for ffmpeg and several
other little programs to convert video files. The gui is written in a
single class, subclassing the qt-designer/pyuic generated one. I am trying
to make my two auxiliary classes totally independent, as I would love
to make a curses version later. So I have a Converter class which does
the actual job of calling the back-end, but I want the gui to be
updated to show the output from the commands. What I want to do
is make the doit() method of the Converter class return a pipe,
through which it will then send the output of the programs. 

Thanks for your answer, as for the excellent tutorial.

Tiago.

From jeff at drinktomi.com  Sun Dec  9 01:13:19 2007
From: jeff at drinktomi.com (Jeff Younker)
Date: Sat, 8 Dec 2007 16:13:19 -0800
Subject: [Tutor] logic for a tree like structure
In-Reply-To: <20071208092516.GB19208@localdomain>
References: <20071208092516.GB19208@localdomain>
Message-ID: <E29B416D-9057-44B9-B339-DDE6EE239F99@drinktomi.com>

Pipes and IO channels are buffered.   The buffers are much larger than
the amount of information you are writing to them, so they're never  
getting
flushed while the program is running.   The child program completes, the
IO channel closes, and it flushes out the output.

My advice is to forget about all the file descriptor and pipes stuff.   
Getting
incremental IO from them via the subprocess module (or any standard IO
module) is painful.   You're probably better off getting the nonstandard
pexpect module and using that instead.

Here's your program using pexpect.

#/usr/bin/python2.5

import pexpect

def main():
    cmd = pexpect.spawn('./writer.py')
    try:
        while True:
            # wait for the end of the line or ten seconds
            cmd.expect('\r\n', timeout=10)
            # get output preceding the EOF matched above
            line = cmd.before
            print '[main]', line
    except pexpect.TIMEOUT:
          print "No output received for ten seconds"
    except pexpect.EOF:
          pass
    finally:
         cmd.close()

if __name__ == '__main__':
   main()



- Jeff Younker - jeff at drinktomi.com -


From alan.gauld at btinternet.com  Sun Dec  9 01:25:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 9 Dec 2007 00:25:59 -0000
Subject: [Tutor] thread and os.pipe
References: <20071208092516.GB19208@localdomain><20071208103543.GC19208@localdomain>
	<fje0l8$l1s$1@ger.gmane.org> <20071208220319.GA20392@localdomain>
Message-ID: <fjfcn1$bh5$1@ger.gmane.org>

"Tiago Saboga" <tiagosaboga at terra.com.br> wrote

>> Why not just set up outw to the output of Popen?
>
> Because in the more complicated case, the run function would have
> several steps, including some external processes with Popen. The 
> run()
> function will take care of determining which processes will run,
> according to the returncode of the first process), and will have to 
> do
> some cleaning in the end. But as this happens, I want my my main()
> function to analyse and print the output from the Popen while the
> external processes are running.

OK, I suspected this might be the case.
In that situation I'd still consider running the initial Popen without
threads and capturing the output but then once you know which
secondary proceses need running and what cleanup needs doing
you could perform those parts in a thread. In other words only
use threads where you truly need parallel processing in the
same process.

> test. I am sorry if I am not clear enough, I am still learning both
> python and english!

Both are looking fine to me :-)

> single class, subclassing the qt-designer/pyuic generated one. I am 
> trying
> to make my two auxiliary classes totally independent, as I would 
> love
> to make a curses version later. So I have a Converter class which 
> does
> the actual job of calling the back-end, but I want the gui to be
> updated to show the output from the commands. What I want to do
> is make the doit() method of the Converter class return a pipe,
> through which it will then send the output of the programs.

I'm still not convinced that a pipe is the best solution here.
You could simply register the UI View with the converter (in usual MVC
design pattern) and get the converter to either send updates to the
UI (or notify the UI to request updates) as needed. That way you
only need a regular Python method in the Converter to deliver the
data and another in the UI code to respond to the notification.
No pipes or queues required.

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  Sun Dec  9 01:37:09 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 9 Dec 2007 00:37:09 -0000
Subject: [Tutor] Sleeping it out
References: <475B108C.20208@bigfoot.com>
Message-ID: <fjfdbv$cu8$1@ger.gmane.org>

"Ricardo Ar?oz" <ricaraoz at gmail.com> wrote

> import time
> L = [i for i in xrange(20)]
> for n, i in enumerate(L) :
>    if n%3 == 0 and n > 0 :
>        print 'waiting 3 seconds'
>        time.sleep(3)
>    print i
>
> I'm using Py 2.51 and PyAlaMode. It works ok but instead of printing 
> in
> groups of three, it will go through the program but the printing 
> will
> appear all at once at the end of the loop. Is there any way to flush 
> the
> output?

Interestingly, it works perfectly at the command prompt but in
Pythonwin I get a similar but slightly different result to PyAlaMode. 
I get
the digits printed in groups but then I wait 3 seconds before the 
waiting
message gets printed!

I assume this is due to how the various IDEs intercept stdout and 
reproduce
it on the GUI, but interesting that the results are different and both
against expectation.

Alan G 



From alan.gauld at btinternet.com  Sun Dec  9 01:38:25 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 9 Dec 2007 00:38:25 -0000
Subject: [Tutor] Sleeping it out
References: <475B108C.20208@bigfoot.com> <475B12F1.1010905@brunson.com>
Message-ID: <fjfdeb$d3g$1@ger.gmane.org>


"Eric Brunson" <brunson at brunson.com> wrote

> Yes, import sys, then sys.stdout.flush() when you need it.

This was my initial idea but it doesn't work in the IDE because
it is not really using sys.stdout. In fact the normal print works
fine from the command prompt (at least in XP)

Alan G.



Ricardo Ar?oz wrote:
> Hi, I have this code :
>
> import time
> L = [i for i in xrange(20)]
> for n, i in enumerate(L) :
>     if n%3 == 0 and n > 0 :
>         print 'waiting 3 seconds'
>         time.sleep(3)
>     print i
>
> I'm using Py 2.51 and PyAlaMode. It works ok but instead of printing 
> in
> groups of three, it will go through the program but the printing 
> will
> appear all at once at the end of the loop. Is there any way to flush 
> the
> output?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

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



From brunson at brunson.com  Sun Dec  9 02:19:12 2007
From: brunson at brunson.com (Eric Brunson)
Date: Sat, 08 Dec 2007 18:19:12 -0700
Subject: [Tutor] Sleeping it out
In-Reply-To: <fjfdeb$d3g$1@ger.gmane.org>
References: <475B108C.20208@bigfoot.com> <475B12F1.1010905@brunson.com>
	<fjfdeb$d3g$1@ger.gmane.org>
Message-ID: <475B4290.1040405@brunson.com>

Alan Gauld wrote:
> "Eric Brunson" <brunson at brunson.com> wrote
>
>   
>> Yes, import sys, then sys.stdout.flush() when you need it.
>>     
>
> This was my initial idea but it doesn't work in the IDE because
> it is not really using sys.stdout. In fact the normal print works
> fine from the command prompt (at least in XP)
>
> Alan G.
>   

Ah, I didn't realize that pyalamode was an IDE.  Just one more reason to 
stick with emacs as my development IDE.  :-)


From theyain.riyu at gmail.com  Sun Dec  9 04:08:31 2007
From: theyain.riyu at gmail.com (Theyain)
Date: Sat, 08 Dec 2007 22:08:31 -0500
Subject: [Tutor] Beat me over the head with it
Message-ID: <475B5C2F.6060300@gmail.com>

I'm not sure if this is really the place to do this, but I will ask anyways.

Hello everyone, names Theyain.  I want to learn Python.  But I am one of 
those people who needs some one to "Beat me over the head" to actually 
learn something.  I can't get myself to actually sit down and read a 
tutorial on Python because no one is making me.  So can someone help me 
with this?  I really want to learn python, but I can't do it with out help.


So help?

From rob.andrews at gmail.com  Sun Dec  9 05:04:04 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Sat, 8 Dec 2007 22:04:04 -0600
Subject: [Tutor] Beat me over the head with it
In-Reply-To: <475B5C2F.6060300@gmail.com>
References: <475B5C2F.6060300@gmail.com>
Message-ID: <8d757d2e0712082004g51bf6eecta0a08bb32fc22364@mail.gmail.com>

Need help with a motivational disorder? ;)

When you say you want to learn Python, what's the nature of the "want
to" part? Looking to write a game, land a job, parse a log file?

Perhaps if you focus on what it is you want to do, that will lead the way.

On Dec 8, 2007 9:08 PM, Theyain <theyain.riyu at gmail.com> wrote:
> I'm not sure if this is really the place to do this, but I will ask anyways.
>
> Hello everyone, names Theyain.  I want to learn Python.  But I am one of
> those people who needs some one to "Beat me over the head" to actually
> learn something.  I can't get myself to actually sit down and read a
> tutorial on Python because no one is making me.  So can someone help me
> with this?  I really want to learn python, but I can't do it with out help.
>
>
> So help?

From fredp101 at mac.com  Sun Dec  9 05:10:17 2007
From: fredp101 at mac.com (Fred P)
Date: Sat, 8 Dec 2007 20:10:17 -0800
Subject: [Tutor] Newbie to Python
Message-ID: <D5DAAB43-24E9-4A6D-B4A0-B07CC81670D3@mac.com>

Hey everyone,

New to python, but not so scripting.  Have some experience with C++,  
but more experience with LUA, CShell, and other types of scripting  
similar to those.

I want to learn Python, and I have decided I would like my first  
project to be a collection program.

I would like to provide the script the path and filename of a file.

Then provide the script with a destination location.

Then the script would create a series of required directories
then copy the contents of the provided folder into the destination  
location + series of required directories

It doesn't seem to terribly difficult, and I think i could get this  
same functionality done in something other than python, but I would  
love to try and start off with something like this.

Alot of what I need python for is automated maintenance and  
manipulation of files.  Would be nice to start off trying to create  
something useful, and I look forward to seeing how active this list is!

Thanks for your time
Fred



From goldwamh at slu.edu  Sun Dec  9 05:11:02 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Sat, 8 Dec 2007 22:11:02 -0600
Subject: [Tutor] Timed While Loops and Threads
Message-ID: <18267.27350.881592.56226@euclid.slu.edu>


Hi everyone,

I'm having some fun combining two recent topics: the "Timed While
Loops" game and that of communication between threads.  Here is an
example that allows a person to gather points in a while loop, but
only for a fixed period of time.  It relies on a few shared variables
to coordinate the activity of the main thread and the secondary
thread.


import threading

def playGame():
    global score, inPlay     # shared with main thread
    while inPlay:
        raw_input('Press return to score a point! ')
        if inPlay:
            score += 1
            print 'Score =', score

score = 0
inPlay = True
numSeconds = 5       # I didn't have patience for the 30 second version
T = threading.Thread(target=playGame)
T.start()
T.join(numSeconds)
inPlay = False       # signal to secondary thread that game is over
print
print 'After', numSeconds, 'seconds, you scored', score, 'points.'





       +-----------------------------------------------
       | Michael Goldwasser
       | Associate Professor
       | Dept. Mathematics and Computer Science
       | Saint Louis University
       | 220 North Grand Blvd.
       | St. Louis, MO 63103-2007


From ricaraoz at gmail.com  Sun Dec  9 07:04:35 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 09 Dec 2007 03:04:35 -0300
Subject: [Tutor] Sleeping it out
In-Reply-To: <fjfdeb$d3g$1@ger.gmane.org>
References: <475B108C.20208@bigfoot.com> <475B12F1.1010905@brunson.com>
	<fjfdeb$d3g$1@ger.gmane.org>
Message-ID: <475B8573.8090902@bigfoot.com>

Alan Gauld wrote:
> "Eric Brunson" <brunson at brunson.com> wrote
> 
>> Yes, import sys, then sys.stdout.flush() when you need it.
> 
> This was my initial idea but it doesn't work in the IDE because
> it is not really using sys.stdout. In fact the normal print works
> fine from the command prompt (at least in XP)
> 
> Alan G.


Thanks guys, Idle seems to work ok, so I guess I'll do my testing in Idle.

Ricardo


> 
> 
> 
> Ricardo Ar?oz wrote:
>> Hi, I have this code :
>>
>> import time
>> L = [i for i in xrange(20)]
>> for n, i in enumerate(L) :
>>     if n%3 == 0 and n > 0 :
>>         print 'waiting 3 seconds'
>>         time.sleep(3)
>>     print i
>>
>> I'm using Py 2.51 and PyAlaMode. It works ok but instead of printing 
>> in
>> groups of three, it will go through the program but the printing 
>> will
>> appear all at once at the end of the loop. Is there any way to flush 
>> the
>> output?

From alan.gauld at btinternet.com  Sun Dec  9 09:46:44 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 9 Dec 2007 08:46:44 -0000
Subject: [Tutor] Newbie to Python
References: <D5DAAB43-24E9-4A6D-B4A0-B07CC81670D3@mac.com>
Message-ID: <fjga1u$21j$1@ger.gmane.org>

Hi Fred,

welcome to the list

> I would like to provide the script the path and filename of a file.

OK, Look at sys.argv for command line argument passing
Look at raw_input() for interactive prompting

> Then the script would create a series of required directories
> then copy the contents of the provided folder into the destination
> location + series of required directories

Look at the os module for lots of stuff around handling files.
In particular look at the os.path module and the shutil module.

> It doesn't seem to terribly difficult, and I think i could get this
> same functionality done in something other than python, but I would
> love to try and start off with something like this.

It's a perfectly valid starting point. Have a go, and ask here
if/when you hit problems.

You might find the  "Using the OS" topic in my tutorial useful
as a starter.

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



From tiagosaboga at terra.com.br  Sun Dec  9 14:22:12 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Sun, 9 Dec 2007 11:22:12 -0200
Subject: [Tutor] logic for a tree like structure
In-Reply-To: <E29B416D-9057-44B9-B339-DDE6EE239F99@drinktomi.com>
References: <20071208092516.GB19208@localdomain>
	<E29B416D-9057-44B9-B339-DDE6EE239F99@drinktomi.com>
Message-ID: <20071209132212.GB20392@localdomain>

On Sat, Dec 08, 2007 at 04:13:19PM -0800, Jeff Younker wrote:
> Pipes and IO channels are buffered.   The buffers are much larger than
> the amount of information you are writing to them, so they're never getting
> flushed while the program is running.   The child program completes, the
> IO channel closes, and it flushes out the output.

Yes! I've just noticed that if I replaced the python writer.py with an
equivalent bash script it worked as expected (my original example).
And then, I could make it work with writer.py if I flush sys.stdout
after each print statement. It is a little frustrating to see
that I was not able to see something that already bit me other times,
but... c'est la vie...

> My advice is to forget about all the file descriptor and pipes stuff.  
> Getting
> incremental IO from them via the subprocess module (or any standard IO
> module) is painful.   You're probably better off getting the nonstandard
> pexpect module and using that instead.

Thanks, it sounds like a useful module (and I don't mind it being
nonstandard, as long as it is in debian - and it is ;) ) but I still
can't see how to do something like that in my case. As I mentioned in
another mail, I have two independent classes, one for the gui and the
other for the converter. The converter has to spawn several processes
depending on the return code of each of them and then do some clean
up. In this mean time (it can take hours), the gui must be alive and
updated with the stdout of the processes.

Tiago.

> Here's your program using pexpect.
>
> #/usr/bin/python2.5
>
> import pexpect
>
> def main():
>    cmd = pexpect.spawn('./writer.py')
>    try:
>        while True:
>            # wait for the end of the line or ten seconds
>            cmd.expect('\r\n', timeout=10)
>            # get output preceding the EOF matched above
>            line = cmd.before
>            print '[main]', line
>    except pexpect.TIMEOUT:
>          print "No output received for ten seconds"
>    except pexpect.EOF:
>          pass
>    finally:
>         cmd.close()
>
> if __name__ == '__main__':
>   main()

From bhaaluu at gmail.com  Sun Dec  9 16:30:04 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Sun, 9 Dec 2007 10:30:04 -0500
Subject: [Tutor] Timed While Loops and Threads
In-Reply-To: <18267.27350.881592.56226@euclid.slu.edu>
References: <18267.27350.881592.56226@euclid.slu.edu>
Message-ID: <ea979d70712090730qda06bb3g17c67753c5711c8b@mail.gmail.com>

On Dec 8, 2007 11:11 PM, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
>
> Hi everyone,
>
> I'm having some fun combining two recent topics: the "Timed While
> Loops" game and that of communication between threads.  Here is an
> example that allows a person to gather points in a while loop, but
> only for a fixed period of time.  It relies on a few shared variables
> to coordinate the activity of the main thread and the secondary
> thread.
>
>
> import threading
>
> def playGame():
>     global score, inPlay     # shared with main thread
>     while inPlay:
>         raw_input('Press return to score a point! ')
>         if inPlay:
>             score += 1
>             print 'Score =', score
>
> score = 0
> inPlay = True
> numSeconds = 5       # I didn't have patience for the 30 second version
> T = threading.Thread(target=playGame)
> T.start()
> T.join(numSeconds)
> inPlay = False       # signal to secondary thread that game is over
> print
> print 'After', numSeconds, 'seconds, you scored', score, 'points.'
>

WOW! That is awesome! 8^D

Here's my best score:
After 5 seconds, you scored 106 points.
Heheheh.

It shouldn't take much to convert that into any kind of timed gaming event.
It is easy to read and understand.
It is elegant!
Thank you!

Although I'm not the OP, I'm interested in all things related to gaming in
Python. This code is trully excellent! 8^D

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

>
>
>
>
>        +-----------------------------------------------
>        | Michael Goldwasser
>        | Associate Professor
>        | Dept. Mathematics and Computer Science
>        | Saint Louis University
>        | 220 North Grand Blvd.
>        | St. Louis, MO 63103-2007
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From quantrum75 at yahoo.com  Sun Dec  9 19:34:01 2007
From: quantrum75 at yahoo.com (quantrum75)
Date: Sun, 9 Dec 2007 10:34:01 -0800 (PST)
Subject: [Tutor] Noob question
Message-ID: <302436.99174.qm@web31413.mail.mud.yahoo.com>

Hi there,
I am a newbie trying to actively learn python.
My question is,
Suppose I have a list
a=["apple","orange","banana"]

How do I convert this list into a string which is

b="appleorangebanana"
Sorry for my ignorance, but I have been trying a "for" loop and trying the inbuilt str.join() method without success.
Thanks a lot.
Regards
Quant


       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071209/679f4a8e/attachment.htm 

From brunson at brunson.com  Sun Dec  9 19:52:09 2007
From: brunson at brunson.com (Eric Brunson)
Date: Sun, 09 Dec 2007 11:52:09 -0700
Subject: [Tutor] Noob question
In-Reply-To: <302436.99174.qm@web31413.mail.mud.yahoo.com>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>
Message-ID: <475C3959.3030209@brunson.com>

quantrum75 wrote:
> Hi there,
> I am a newbie trying to actively learn python.
> My question is,
> Suppose I have a list
> a=["apple","orange","banana"]
>
> How do I convert this list into a string which is
>
> b="appleorangebanana"
> Sorry for my ignorance, 

No worries, every new language has its idioms that only come from 
experience and exposure.

Try this:

In [1]: a=["apple","orange","banana"]

In [2]: print "".join( a )
appleorangebanana

And just for clarity:

In [3]: print "|".join( a )
apple|orange|banana

Hope that helps, good luck learning python.

Sincerely,
e.

> but I have been trying a "for" loop and trying the inbuilt str.join() 
> method without success.
> Thanks a lot.
> Regards
> Quant
>
> ------------------------------------------------------------------------
> Looking for last minute shopping deals? Find them fast with Yahoo! 
> Search. 
> <http://us.rd.yahoo.com/evt=51734/*http://tools.search.yahoo.com/newsearch/category.php?category=shopping> 
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From eric at ericwalstad.com  Sun Dec  9 22:40:27 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Sun, 09 Dec 2007 13:40:27 -0800
Subject: [Tutor] Noob question
In-Reply-To: <475C3959.3030209@brunson.com>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>
	<475C3959.3030209@brunson.com>
Message-ID: <475C60CB.9060401@ericwalstad.com>

Eric Brunson wrote:
> quantrum75 wrote:
>> Hi there,
>> I am a newbie trying to actively learn python.
>> My question is,
>> Suppose I have a list
>> a=["apple","orange","banana"]
>>
>> How do I convert this list into a string which is
>>
>> b="appleorangebanana"
>> Sorry for my ignorance, 
> 
> No worries, every new language has its idioms that only come from 
> experience and exposure.
> 
> Try this:
> 
> In [1]: a=["apple","orange","banana"]
> 
> In [2]: print "".join( a )
> appleorangebanana
> 
> And just for clarity:
> 
> In [3]: print "|".join( a )
> apple|orange|banana

And another good reference for you to know about is the built-in help
system that comes with Python.  For example, to learn a bit about why
Eric's code works the way it does:
>>> help("".join)

Help on built-in function join:

join(...)
    S.join(sequence) -> string

    Return a string which is the concatenation of the strings in the
    sequence.  The separator between elements is S.


In Eric's example, the variable 'a' was a type of Python sequence,
specifically, a list.


You could also achieve the same result of concatenating a list of
strings by looping over the list items like so:

b = ''
for fruit in a:
    b += fruit

print b

Eric.

From alan.gauld at btinternet.com  Mon Dec 10 02:18:56 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 10 Dec 2007 01:18:56 -0000
Subject: [Tutor] Noob question
References: <302436.99174.qm@web31413.mail.mud.yahoo.com><475C3959.3030209@brunson.com>
	<475C60CB.9060401@ericwalstad.com>
Message-ID: <fji46a$oo3$1@ger.gmane.org>

"Eric Walstad" <eric at ericwalstad.com> wrote

> You could also achieve the same result of concatenating a list of
> strings by looping over the list items like so:
> 
> b = ''
> for fruit in a:
>    b += fruit
> 
> print b

And to add to the options you could use the formatting operator 
provided you know there are only 3 items, 

b = "%s%s%s" % tuple(a)

Or for an indefinite number of strings:

b = "%s" * len(a)
b = b % tuple(a)

So many options. However, to the OP, if you get stuck in 
future its best if you post the erroneous code that you have tried, 
then we can better see where you have gone wrong and thus 
provide clearer guidance on how to fix it. Its better to learn to 
do it your own way correctly than just to see other folks 
attempts .

HTH,

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


From ricaraoz at gmail.com  Mon Dec 10 03:10:10 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 09 Dec 2007 23:10:10 -0300
Subject: [Tutor] A couple of modules
Message-ID: <475CA002.7040506@bigfoot.com>

Hi, somebody did ask about dates. Found this package, might be usefull
http://labix.org/python-dateutil
"""
The dateutil module provides powerful extensions to the standard
datetime module, available in Python 2.3+.

Features

    * Computing of relative deltas (next month, next year, next monday,
last week of month, etc);
    * Computing of relative deltas between two given date and/or
datetime objects;
    * Computing of dates based on very flexible recurrence rules, using
a superset of the

      iCalendar specification. Parsing of RFC strings is supported as well.
    * Generic parsing of dates in almost any string format;
    * Timezone (tzinfo) implementations for tzfile(5) format files
(/etc/localtime, /usr/share/zoneinfo, etc), TZ environment string (in
all known formats), iCalendar format files, given ranges (with help from
relative deltas), local machine timezone, fixed offset timezone, UTC
timezone, and Windows registry-based time zones.
    * Internal up-to-date world timezone information based on Olson's
database.
    * Computing of Easter Sunday dates for any given year, using
Western, Orthodox or Julian algorithms;
    * More than 400 test cases.
"""

Somebody was also asking about taking accents out of a string. Check
this out : http://packages.debian.org/sid/python/python-unac
"""
Unac is a programmer's library that removes accents from a string.

This package contains Python bindings for the original C library.
"""
and also :
http://groups.google.com/group/linux.debian.bugs.dist/browse_thread/thread/adb5cc05b1b7b247
"""
python-unac -- code is of poor quality and can be done as easily in
native Python
"""


HTH

Ricardo


From keridee at jayco.net  Mon Dec 10 13:48:08 2007
From: keridee at jayco.net (Tiger12506)
Date: Mon, 10 Dec 2007 07:48:08 -0500
Subject: [Tutor] Beat me over the head with it
References: <475B5C2F.6060300@gmail.com>
Message-ID: <009401c83b2a$edf9dea0$43fce004@jslaptop>

Write a python script that prints out what 2+2 is NOW!!!
And after you've done that, write one that does my chemistry homework, 
IMMEDIATELY!
Bonk!

;-)
JS 


From amitsaxena69 at gmail.com  Mon Dec 10 14:19:19 2007
From: amitsaxena69 at gmail.com (Amit Saxena)
Date: Mon, 10 Dec 2007 18:49:19 +0530
Subject: [Tutor] Noob question
In-Reply-To: <fji46a$oo3$1@ger.gmane.org>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>
	<475C3959.3030209@brunson.com> <475C60CB.9060401@ericwalstad.com>
	<fji46a$oo3$1@ger.gmane.org>
Message-ID: <82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>

The simplest way i could think of:

a=["apple","orange","banana"]
b = ""
for i in range(len(a)):
     b += a[i]
print b


Amit

On Dec 10, 2007 6:48 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> "Eric Walstad" <eric at ericwalstad.com> wrote
>
> > You could also achieve the same result of concatenating a list of
> > strings by looping over the list items like so:
> >
> > b = ''
> > for fruit in a:
> >    b += fruit
> >
> > print b
>
> And to add to the options you could use the formatting operator
> provided you know there are only 3 items,
>
> b = "%s%s%s" % tuple(a)
>
> Or for an indefinite number of strings:
>
> b = "%s" * len(a)
> b = b % tuple(a)
>
> So many options. However, to the OP, if you get stuck in
> future its best if you post the erroneous code that you have tried,
> then we can better see where you have gone wrong and thus
> provide clearer guidance on how to fix it. Its better to learn to
> do it your own way correctly than just to see other folks
> attempts .
>
> 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/20071210/26967480/attachment.htm 

From bba at inbox.com  Mon Dec 10 14:48:05 2007
From: bba at inbox.com (Ben Bartrum)
Date: Mon, 10 Dec 2007 05:48:05 -0800
Subject: [Tutor] Beat me over the head with it
In-Reply-To: <8d757d2e0712082004g51bf6eecta0a08bb32fc22364@mail.gmail.com>
References: <475b5c2f.6060300@gmail.com>
Message-ID: <9075E7E90F0.000001C5bba@inbox.com>

import motivation

(sorry)

> -----Original Message-----
> From: rob.andrews at gmail.com
> Sent: Sat, 8 Dec 2007 22:04:04 -0600
> To: theyain.riyu at gmail.com
> Subject: Re: [Tutor] Beat me over the head with it
> 
> Need help with a motivational disorder? ;)
> 
> When you say you want to learn Python, what's the nature of the "want
> to" part? Looking to write a game, land a job, parse a log file?
> 
> Perhaps if you focus on what it is you want to do, that will lead the
> way.
> 
> On Dec 8, 2007 9:08 PM, Theyain <theyain.riyu at gmail.com> wrote:
>> I'm not sure if this is really the place to do this, but I will ask
>> anyways.
>> 
>> Hello everyone, names Theyain.  I want to learn Python.  But I am one of
>> those people who needs some one to "Beat me over the head" to actually
>> learn something.  I can't get myself to actually sit down and read a
>> tutorial on Python because no one is making me.  So can someone help me
>> with this?  I really want to learn python, but I can't do it with out
>> help.
>> 
>> 
>> So help?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

____________________________________________________________
FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!
Check it out at http://www.inbox.com/earth

From bba at inbox.com  Mon Dec 10 14:42:10 2007
From: bba at inbox.com (Ben Bartrum)
Date: Mon, 10 Dec 2007 05:42:10 -0800
Subject: [Tutor] thread not running
Message-ID: <9068AD06846.000001B2bba@inbox.com>

Hello

I have the following, which I use within a CherryPy app.  The subprocess bit is just to see if it runs or not.   It works on my home PC (Python 2.5.1 on Ubuntu), but not on the live host which has Python 2.4.4 on Debian Etch.  


    def daemon():
      while 1:
         myperiodicfunction()
         p = subprocess.Popen('cal > /tmp/stilhere.txt', shell=True)
         time.sleep(30) 

    thread.start_new_thread(daemon,())

Is there a way to get it to work without upgrading Python (which I am not keen to do, as I prefer the packaged version & security updates)

Thanks

____________________________________________________________
GET FREE 5GB EMAIL - Check out spam free email with many cool features!
Visit http://www.inbox.com/email to find out more!

From evert.rol at gmail.com  Mon Dec 10 15:15:20 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Mon, 10 Dec 2007 14:15:20 +0000
Subject: [Tutor] thread not running
In-Reply-To: <9068AD06846.000001B2bba@inbox.com>
References: <9068AD06846.000001B2bba@inbox.com>
Message-ID: <813A18BF-C1A0-4ADD-B4CE-F202753761F4@gmail.com>

> I have the following, which I use within a CherryPy app.  The  
> subprocess bit is just to see if it runs or not.   It works on my  
> home PC (Python 2.5.1 on Ubuntu), but not on the live host which  
> has Python 2.4.4 on Debian Etch.
>
>
>     def daemon():
>       while 1:
>          myperiodicfunction()
>          p = subprocess.Popen('cal > /tmp/stilhere.txt', shell=True)
>          time.sleep(30)
>
>     thread.start_new_thread(daemon,())
>
> Is there a way to get it to work without upgrading Python (which I  
> am not keen to do, as I prefer the packaged version & security  
> updates)

   Hi Ben,

What's going wrong when running it with 2.4? AfaIcs, all modules are  
in 2.4, so it my not have to do anything with the Python version, but  
with the underlying system. Any traceback? Perhaps replace the  
subprocess part with just a print statement to see what's happening?


From bba at inbox.com  Mon Dec 10 15:56:38 2007
From: bba at inbox.com (Ben Bartrum)
Date: Mon, 10 Dec 2007 06:56:38 -0800
Subject: [Tutor] thread not running
In-Reply-To: <813A18BF-C1A0-4ADD-B4CE-F202753761F4@gmail.com>
References: <9068ad06846.000001b2bba@inbox.com>
Message-ID: <910F22066F4.0000027Ebba@inbox.com>


> What's going wrong when running it with 2.4? AfaIcs, all modules are
> in 2.4, so it my not have to do anything with the Python version, but
> with the underlying system. Any traceback? Perhaps replace the
> subprocess part with just a print statement to see what's happening?

There are no tracebacks, and I have done some more investigation:
1. the thread code works fine standalone on both systems
2. the thread code works within CherryPy on my home PC but does not work within CherryPy on the live host
3. Both run the same version of CherryPy - I could not imagine it is a CherryPy issue, but unless you have any suggestion I'll try the CherryPy list

The live code runs under supervisor.  Could that make a difference?

Thanks

From evert.rol at gmail.com  Mon Dec 10 16:16:14 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Mon, 10 Dec 2007 15:16:14 +0000
Subject: [Tutor] thread not running
In-Reply-To: <910F22066F4.0000027Ebba@inbox.com>
References: <9068ad06846.000001b2bba@inbox.com>
	<910F22066F4.0000027Ebba@inbox.com>
Message-ID: <2C46683C-464C-46CF-A18D-219410D8E8B1@gmail.com>

>> What's going wrong when running it with 2.4? AfaIcs, all modules are
>> in 2.4, so it my not have to do anything with the Python version, but
>> with the underlying system. Any traceback? Perhaps replace the
>> subprocess part with just a print statement to see what's happening?
>
> There are no tracebacks, and I have done some more investigation:
> 1. the thread code works fine standalone on both systems
> 2. the thread code works within CherryPy on my home PC but does not  
> work within CherryPy on the live host
> 3. Both run the same version of CherryPy - I could not imagine it  
> is a CherryPy issue, but unless you have any suggestion I'll try  
> the CherryPy list
>

I think the CherryPy mailing list will indeed now be your best option  
now.
Simple things I can think of (without any CherryPy experience) are  
eg: is the IO actually not flushed in some way (one would think  
running it in shell through subprocess would do that, though), so  
that you won't see any output while there is; or is there somehow a  
thread started from another (sub)thread, not the main thread. I don't  
know what the latter will do, but it may cause some unexpected results.
It's typical that it works for one CherryPy system, but not for another.
If you want to find out if it could be related to the Python version,  
you can download the Python 2.4.4 source code and do a 'make  
altinstall', which will leave the Python 2.5 version alone; you'll  
need to install the CherryPy & dependency modules as well then (which  
go in lib/python2.4/site-packages/).


> The live code runs under supervisor.  Could that make a difference?

I'm not familiar with the concept of 'supervisor' in this context,  
but a quick glance at wikipedia suggest that that could indeed be a  
problem: "A [...] supervisor is a computer program, usually part of  
an operating system, that controls the execution of other routines  
and regulates work scheduling, input/output operations, error  
actions, and similar functions and regulates the flow of work in a  
data processing system."
So it could control your threads (and output from them, or even  
prevent them from running.
Then again, as far as I've understood Python, threads within Python  
still run within the same system thread/PID, so it's still one  
program to the underlying OS (which a quick check seems to confirm).

Good luck,

   Evert


From brunson at brunson.com  Mon Dec 10 16:27:29 2007
From: brunson at brunson.com (Eric Brunson)
Date: Mon, 10 Dec 2007 08:27:29 -0700
Subject: [Tutor] Noob question
In-Reply-To: <82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>	<475C3959.3030209@brunson.com>
	<475C60CB.9060401@ericwalstad.com>	<fji46a$oo3$1@ger.gmane.org>
	<82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>
Message-ID: <475D5AE1.7020705@brunson.com>


Hi Amit,

This is fairly inefficient.  Because strings in python are immutable 
this approach causes a new string to be created every iteration.  While 
it may not be an issue with just 3 strings, it is much better to create 
your list and use "".join() to create the concatenation after the list 
is complete.  When you get used to it, it's a bit more concise and 
readable, also.

Sincerely,
e.

Amit Saxena wrote:
> The simplest way i could think of:
>
> a=["apple","orange","banana"]
> b = ""
> for i in range(len(a)):
>      b += a[i]
> print b
>
>
> Amit
>
> On Dec 10, 2007 6:48 AM, Alan Gauld <alan.gauld at btinternet.com 
> <mailto:alan.gauld at btinternet.com>> wrote:
>
>     "Eric Walstad" <eric at ericwalstad.com
>     <mailto:eric at ericwalstad.com>> wrote
>
>     > You could also achieve the same result of concatenating a list of
>     > strings by looping over the list items like so:
>     >
>     > b = ''
>     > for fruit in a:
>     >    b += fruit
>     >
>     > print b
>
>     And to add to the options you could use the formatting operator
>     provided you know there are only 3 items,
>
>     b = "%s%s%s" % tuple(a)
>
>     Or for an indefinite number of strings:
>
>     b = "%s" * len(a)
>     b = b % tuple(a)
>
>     So many options. However, to the OP, if you get stuck in
>     future its best if you post the erroneous code that you have tried,
>     then we can better see where you have gone wrong and thus
>     provide clearer guidance on how to fix it. Its better to learn to
>     do it your own way correctly than just to see other folks
>     attempts .
>
>     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 <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From sewqyne at yahoo.com  Mon Dec 10 18:00:31 2007
From: sewqyne at yahoo.com (Sewqyne Olpo)
Date: Mon, 10 Dec 2007 09:00:31 -0800 (PST)
Subject: [Tutor] Windows Os Programming
Message-ID: <233349.51575.qm@web45904.mail.sp1.yahoo.com>

Hello. As a new python programmer I wish to interact with the Windows Xp Os like loggin off session or restarting the system etc. But  I dont know exactly where to start  and what to learn. Could you give some hints about  windows programming using python? 
Thanks in advance.




      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/3777e938/attachment-0001.htm 

From bryan.fodness at gmail.com  Mon Dec 10 18:56:47 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 10 Dec 2007 12:56:47 -0500
Subject: [Tutor] updating a print statement
Message-ID: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>

I have a print statement in a for loop so I can watch the progress

for line in file(file):
    the_line = line.split()
    if the_line:
        print ("Index = %.2f") %index

Is there a way that only one line will be output and the variable is updated
rather than one line for every index.

Thanks,
Bryan

-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/49233ec2/attachment.htm 

From tjampman at gmail.com  Mon Dec 10 19:30:09 2007
From: tjampman at gmail.com (Ole Henning Jensen)
Date: Mon, 10 Dec 2007 19:30:09 +0100
Subject: [Tutor] updating a print statement
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
Message-ID: <006201c83b5a$b3d16880$7a02a8c0@allmycore>


  I have a print statement in a for loop so I can watch the progress

  for line in file(file):
      the_line = line.split()
      if the_line:
          print ("Index = %.2f") %index

  Is there a way that only one line will be output and the variable is updated rather than one line for every index.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/abae1e9b/attachment.htm 

From tjampman at gmail.com  Mon Dec 10 19:37:59 2007
From: tjampman at gmail.com (Ole Henning Jensen)
Date: Mon, 10 Dec 2007 19:37:59 +0100
Subject: [Tutor] updating a print statement
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
Message-ID: <007801c83b5b$cb6b51d0$7a02a8c0@allmycore>


Sry about the previous mail.

----- Original Message ----- 

I have a print statement in a for loop so I can watch the progress

for line in file(file):
    the_line = line.split()
    if the_line:
        print ("Index = %.2f") %index

Is there a way that only one line will be output and the variable is updated
rather than one line for every index.
-------------------------

Now I'm still only in the learning process, but couldn't you do something 
like this:

for line in file(file):
    the_line = line.split()
    if the_line:
        Index = "%.2f" %index     # This line might have to be
                                                # adjusted to do what it is 
you want
print "Index= " + Index


BR
Ole

PS heres to hoping the code is indented properbly. 



From rabidpoobear at gmail.com  Mon Dec 10 19:53:07 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 10 Dec 2007 12:53:07 -0600
Subject: [Tutor] updating a print statement
In-Reply-To: <007801c83b5b$cb6b51d0$7a02a8c0@allmycore>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
	<007801c83b5b$cb6b51d0$7a02a8c0@allmycore>
Message-ID: <475D8B13.6070607@gmail.com>

Ole Henning Jensen wrote:
> Sry about the previous mail.
>
> ----- Original Message ----- 
>
> I have a print statement in a for loop so I can watch the progress
>
> for line in file(file):
>     the_line = line.split()
>     if the_line:
>         print ("Index = %.2f") %index
>
> Is there a way that only one line will be output and the variable is updated
> rather than one line for every index.
You have to get into the console modules to do this.
Python doesn't have built-in support for modifying the terminal.
PyCurses can be used if you're on Linux (and presumably OS X?)
from Mark Hammond's Win32all module, you can use Win32.Console.
Both of these are fairly complicated from a beginner's standpoint, so 
I'd advise that you just don't worry about it.

From noufal at airtelbroadband.in  Mon Dec 10 20:16:04 2007
From: noufal at airtelbroadband.in (Noufal Ibrahim)
Date: Tue, 11 Dec 2007 00:46:04 +0530
Subject: [Tutor] Formatting timedelta objects
Message-ID: <475D9074.8070305@airtelbroadband.in>

Hello everyone,
   This is probably something simple but I can't seem to find a way to 
format a timedelta object for printing? I need to be able to print it in 
a HH:MM:SS format but without the microseconds part (which is what you 
get if you str() it).

   Any pointers?

Thanks.


-- 
~noufal
http://nibrahim.net.in/

From kent37 at tds.net  Mon Dec 10 20:43:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 10 Dec 2007 14:43:53 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
Message-ID: <475D96F9.9080300@tds.net>

Bryan Fodness wrote:
> I have a print statement in a for loop so I can watch the progress
>  
> for line in file(file):
>     the_line = line.split()
>     if the_line:
>         print ("Index = %.2f") %index
>  
> Is there a way that only one line will be output and the variable is 
> updated rather than one line for every index.

I'm not sure I understand what you are asking. index is never updated in 
the loop above.

If you want to overwrite the same line on the console, try
   print "\rIndex = %.2f" % index,

note ----^
      ---------------------------^

You might need some extra spaces at the end of the print to 'erase' a 
longer previous line.

Kent

From alan.gauld at btinternet.com  Mon Dec 10 19:51:09 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 10 Dec 2007 18:51:09 -0000
Subject: [Tutor] Windows Os Programming
References: <233349.51575.qm@web45904.mail.sp1.yahoo.com>
Message-ID: <fjk1r8$e1c$1@ger.gmane.org>


"Sewqyne Olpo" <sewqyne at yahoo.com> wrote

> Could you give some hints about  windows programming using python? 

The biggest hint is to buy Mark Hammonds venerable but still useful 
book: Python rogramming on Win32 

Then read the os module documents and shutil and os.path.
(Try the OS topic in my tutorial for a starter)

All of these work more or less as is on Windows.

Finally investigate the MSDN web site for WSH which gives 
you relatively easy access to windows files, printers, registry and 
processes via a set of COM objects that can be instantiated from 
Python.

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 Dec 10 20:09:02 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 10 Dec 2007 19:09:02 -0000
Subject: [Tutor] updating a print statement
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
Message-ID: <fjk2so$i7l$1@ger.gmane.org>


"Bryan Fodness" <bryan.fodness at gmail.com> wrote

> for line in file(file):
>    the_line = line.split()
>    if the_line:
>        print ("Index = %.2f") %index
>
> Is there a way that only one line will be output and the variable is 
> updated
> rather than one line for every index.

If you use Linux then the curses module will let you address
a specific screen location. If on Windows its a little harder but
you can try using Ctrl-H to delete a character (or several)
before printing.

Use a comma to prevent Python outputting a new line.
Something like::

print '\n\nThe indices are:   ',
for index in range(5):
   print chr(8) * 4,              # ^H *4 => delete four characters
   print ("%2s" % index),    # string formatting forces width to two


There is also a Python WConIO(?) library you can download which gives
cursor addressing under Windows.

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 Dec 10 22:33:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 10 Dec 2007 16:33:50 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>	
	<475D96F9.9080300@tds.net>
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>
Message-ID: <475DB0BE.2090304@tds.net>

Bryan Fodness wrote:
> I do want to overwrite the same line.
>  
> I do not see a difference between using the \r and not using it.

How are you running the program? Try it from a command line if that is 
not what you are doing. Can you show your new code?

Kent

PS Please Reply All to stay on the list.

> 
> On Dec 10, 2007 2:43 PM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
> 
>     Bryan Fodness wrote:
>      > I have a print statement in a for loop so I can watch the progress
>      >
>      > for line in file(file):
>      >     the_line = line.split()
>      >     if the_line:
>      >         print ("Index = %.2f") %index
>      >
>      > Is there a way that only one line will be output and the variable is
>      > updated rather than one line for every index.
> 
>     I'm not sure I understand what you are asking. index is never
>     updated in
>     the loop above.
> 
>     If you want to overwrite the same line on the console, try
>       print "\rIndex = %.2f" % index,
> 
>     note ----^
>          ---------------------------^
> 
>     You might need some extra spaces at the end of the print to 'erase' a
>     longer previous line.
> 
>     Kent
> 
> 
> 
> 
> -- 
> "The game of science can accurately be described as a never-ending 
> insult to human intelligence." - Jo?o Magueijo


From bryan.fodness at gmail.com  Mon Dec 10 22:45:00 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 10 Dec 2007 16:45:00 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <475DB0BE.2090304@tds.net>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
	<475D96F9.9080300@tds.net>
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>
	<475DB0BE.2090304@tds.net>
Message-ID: <fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>

Here is the code.

for line in file('test.txt'):
    the_line = line.split()
    if the_line:
        if the_line[0] == 'Index':
            index = float(the_line[-1])
            print ("\rIndex = %.3f") %index
raw_input("\nExit")

Here is the output.

Index = 0.000
Index = 0.400
Index = 0.800
Index = 1.000

Exit


On Dec 10, 2007 4:33 PM, Kent Johnson <kent37 at tds.net> wrote:

> Bryan Fodness wrote:
> > I do want to overwrite the same line.
> >
> > I do not see a difference between using the \r and not using it.
>
> How are you running the program? Try it from a command line if that is
> not what you are doing. Can you show your new code?
>
> Kent
>
> PS Please Reply All to stay on the list.
>
> >
> > On Dec 10, 2007 2:43 PM, Kent Johnson <kent37 at tds.net
>  > <mailto:kent37 at tds.net>> wrote:
> >
> >     Bryan Fodness wrote:
> >      > I have a print statement in a for loop so I can watch the
> progress
> >      >
> >      > for line in file(file):
> >      >     the_line = line.split()
> >      >     if the_line:
> >      >         print ("Index = %.2f") %index
> >      >
> >      > Is there a way that only one line will be output and the variable
> is
> >      > updated rather than one line for every index.
> >
> >     I'm not sure I understand what you are asking. index is never
> >     updated in
> >     the loop above.
> >
> >     If you want to overwrite the same line on the console, try
> >       print "\rIndex = %.2f" % index,
> >
> >     note ----^
> >          ---------------------------^
> >
> >     You might need some extra spaces at the end of the print to 'erase'
> a
> >     longer previous line.
> >
> >     Kent
> >
> >
> >
> >
> > --
> > "The game of science can accurately be described as a never-ending
> > insult to human intelligence." - Jo?o Magueijo
>
>


-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/6117efd5/attachment-0001.htm 

From kent37 at tds.net  Mon Dec 10 22:48:11 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 10 Dec 2007 16:48:11 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>	
	<475D96F9.9080300@tds.net>	
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>	
	<475DB0BE.2090304@tds.net>
	<fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>
Message-ID: <475DB41B.8080604@tds.net>

Bryan Fodness wrote:
> Here is the code.
>  
> for line in file('test.txt'):
>     the_line = line.split()
>     if the_line:
>         if the_line[0] == 'Index':
>             index = float(the_line[-1])
>             print ("\rIndex = %.3f") %index

Add a comma at the end of the above line to suppress the newline that 
print normally outputs.

Kent

> raw_input("\nExit")
>  
> Here is the output.
> 
> Index = 0.000
> Index = 0.400
> Index = 0.800
> Index = 1.000
>  
> Exit
> 
> 
> On Dec 10, 2007 4:33 PM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
> 
>     Bryan Fodness wrote:
>      > I do want to overwrite the same line.
>      >
>      > I do not see a difference between using the \r and not using it.
> 
>     How are you running the program? Try it from a command line if that is
>     not what you are doing. Can you show your new code?
> 
>     Kent
> 
>     PS Please Reply All to stay on the list.
> 
>      >
>      > On Dec 10, 2007 2:43 PM, Kent Johnson <kent37 at tds.net
>     <mailto:kent37 at tds.net>
>      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>> wrote:
>      >
>      >     Bryan Fodness wrote:
>      >      > I have a print statement in a for loop so I can watch the
>     progress
>      >      >
>      >      > for line in file(file):
>      >      >     the_line = line.split()
>      >      >     if the_line:
>      >      >         print ("Index = %.2f") %index
>      >      >
>      >      > Is there a way that only one line will be output and the
>     variable is
>      >      > updated rather than one line for every index.
>      >
>      >     I'm not sure I understand what you are asking. index is never
>      >     updated in
>      >     the loop above.
>      >
>      >     If you want to overwrite the same line on the console, try
>      >       print "\rIndex = %.2f" % index,
>      >
>      >     note ----^
>      >          ---------------------------^
>      >
>      >     You might need some extra spaces at the end of the print to
>     'erase' a
>      >     longer previous line.
>      >
>      >     Kent
>      >
>      >
>      >
>      >
>      > --
>      > "The game of science can accurately be described as a never-ending
>      > insult to human intelligence." - Jo?o Magueijo
> 
> 
> 
> 
> -- 
> "The game of science can accurately be described as a never-ending 
> insult to human intelligence." - Jo?o Magueijo


From bryan.fodness at gmail.com  Mon Dec 10 22:55:28 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 10 Dec 2007 16:55:28 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <475DB41B.8080604@tds.net>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
	<475D96F9.9080300@tds.net>
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>
	<475DB0BE.2090304@tds.net>
	<fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>
	<475DB41B.8080604@tds.net>
Message-ID: <fbf64d2b0712101355u1252b1r2c9758739de418c0@mail.gmail.com>

for line in file('test.txt'):
    the_line = line.split()
    if the_line:
        if the_line[0] == 'Index':
            index = float(the_line[-1])
            print ("\rIndex = %.3f  ") %index,
raw_input("\nExit")
Here is my output,

Index = 0.000   Index = 0.400   Index = 0.800   Index = 1.000


On Dec 10, 2007 4:48 PM, Kent Johnson <kent37 at tds.net> wrote:

> Bryan Fodness wrote:
> > Here is the code.
> >
> > for line in file('test.txt'):
> >     the_line = line.split()
> >     if the_line:
> >         if the_line[0] == 'Index':
> >             index = float(the_line[-1])
> >             print ("\rIndex = %.3f") %index
>
> Add a comma at the end of the above line to suppress the newline that
> print normally outputs.
>
> Kent
>
> > raw_input("\nExit")
> >
> > Here is the output.
> >
> > Index = 0.000
> > Index = 0.400
> > Index = 0.800
> > Index = 1.000
> >
> > Exit
> >
> >
> > On Dec 10, 2007 4:33 PM, Kent Johnson <kent37 at tds.net
> > <mailto:kent37 at tds.net>> wrote:
> >
> >     Bryan Fodness wrote:
> >      > I do want to overwrite the same line.
> >      >
> >      > I do not see a difference between using the \r and not using it.
> >
> >     How are you running the program? Try it from a command line if that
> is
> >     not what you are doing. Can you show your new code?
> >
> >     Kent
> >
> >     PS Please Reply All to stay on the list.
> >
> >      >
> >      > On Dec 10, 2007 2:43 PM, Kent Johnson <kent37 at tds.net
> >     <mailto:kent37 at tds.net>
>  >      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>> wrote:
> >      >
> >      >     Bryan Fodness wrote:
> >      >      > I have a print statement in a for loop so I can watch the
> >     progress
> >      >      >
> >      >      > for line in file(file):
> >      >      >     the_line = line.split()
> >      >      >     if the_line:
> >      >      >         print ("Index = %.2f") %index
> >      >      >
> >      >      > Is there a way that only one line will be output and the
> >     variable is
> >      >      > updated rather than one line for every index.
> >      >
> >      >     I'm not sure I understand what you are asking. index is never
> >      >     updated in
> >      >     the loop above.
> >      >
> >      >     If you want to overwrite the same line on the console, try
> >      >       print "\rIndex = %.2f" % index,
> >      >
> >      >     note ----^
> >      >          ---------------------------^
> >      >
> >      >     You might need some extra spaces at the end of the print to
> >     'erase' a
> >      >     longer previous line.
> >      >
> >      >     Kent
> >      >
> >      >
> >      >
> >      >
> >      > --
> >      > "The game of science can accurately be described as a
> never-ending
> >      > insult to human intelligence." - Jo?o Magueijo
> >
> >
> >
> >
> > --
> > "The game of science can accurately be described as a never-ending
> > insult to human intelligence." - Jo?o Magueijo
>
>


-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/00f86ef7/attachment.htm 

From kent37 at tds.net  Mon Dec 10 23:02:16 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 10 Dec 2007 17:02:16 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <fbf64d2b0712101355u1252b1r2c9758739de418c0@mail.gmail.com>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>	
	<475D96F9.9080300@tds.net>	
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>	
	<475DB0BE.2090304@tds.net>	
	<fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>	
	<475DB41B.8080604@tds.net>
	<fbf64d2b0712101355u1252b1r2c9758739de418c0@mail.gmail.com>
Message-ID: <475DB768.40506@tds.net>

How are you running the program?

Bryan Fodness wrote:
>  
> for line in file('test.txt'):
>     the_line = line.split()
>     if the_line:
>         if the_line[0] == 'Index':
>             index = float(the_line[-1])
>             print ("\rIndex = %.3f  ") %index,
> raw_input("\nExit")
> Here is my output,
> 
> Index = 0.000   Index = 0.400   Index = 0.800   Index = 1.000  
> 
> 
> On Dec 10, 2007 4:48 PM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
> 
>     Bryan Fodness wrote:
>      > Here is the code.
>      >
>      > for line in file('test.txt'):
>      >     the_line = line.split()
>      >     if the_line:
>      >         if the_line[0] == 'Index':
>      >             index = float(the_line[-1])
>      >             print ("\rIndex = %.3f") %index
> 
>     Add a comma at the end of the above line to suppress the newline that
>     print normally outputs.
> 
>     Kent
> 
>      > raw_input("\nExit")
>      >
>      > Here is the output.
>      >
>      > Index = 0.000
>      > Index = 0.400
>      > Index = 0.800
>      > Index = 1.000
>      >
>      > Exit
>      >
>      >
>      > On Dec 10, 2007 4:33 PM, Kent Johnson <kent37 at tds.net
>     <mailto:kent37 at tds.net>
>      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>> wrote:
>      >
>      >     Bryan Fodness wrote:
>      >      > I do want to overwrite the same line.
>      >      >
>      >      > I do not see a difference between using the \r and not
>     using it.
>      >
>      >     How are you running the program? Try it from a command line
>     if that is
>      >     not what you are doing. Can you show your new code?
>      >
>      >     Kent
>      >
>      >     PS Please Reply All to stay on the list.
>      >
>      >      >
>      >      > On Dec 10, 2007 2:43 PM, Kent Johnson <kent37 at tds.net
>     <mailto:kent37 at tds.net>
>      >     <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>
>      >      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>
>     <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>>> wrote:
>      >      >
>      >      >     Bryan Fodness wrote:
>      >      >      > I have a print statement in a for loop so I can
>     watch the
>      >     progress
>      >      >      >
>      >      >      > for line in file(file):
>      >      >      >     the_line = line.split()
>      >      >      >     if the_line:
>      >      >      >         print ("Index = %.2f") %index
>      >      >      >
>      >      >      > Is there a way that only one line will be output
>     and the
>      >     variable is
>      >      >      > updated rather than one line for every index.
>      >      >
>      >      >     I'm not sure I understand what you are asking. index
>     is never
>      >      >     updated in
>      >      >     the loop above.
>      >      >
>      >      >     If you want to overwrite the same line on the console, try
>      >      >       print "\rIndex = %.2f" % index,
>      >      >
>      >      >     note ----^
>      >      >          ---------------------------^
>      >      >
>      >      >     You might need some extra spaces at the end of the
>     print to
>      >     'erase' a
>      >      >     longer previous line.
>      >      >
>      >      >     Kent
>      >      >
>      >      >
>      >      >
>      >      >
>      >      > --
>      >      > "The game of science can accurately be described as a
>     never-ending
>      >      > insult to human intelligence." - Jo?o Magueijo
>      >
>      >
>      >
>      >
>      > --
>      > "The game of science can accurately be described as a never-ending
>      > insult to human intelligence." - Jo?o Magueijo
> 
> 
> 
> 
> -- 
> "The game of science can accurately be described as a never-ending 
> insult to human intelligence." - Jo?o Magueijo


From bryan.fodness at gmail.com  Mon Dec 10 23:07:49 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 10 Dec 2007 17:07:49 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <475DB768.40506@tds.net>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
	<475D96F9.9080300@tds.net>
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>
	<475DB0BE.2090304@tds.net>
	<fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>
	<475DB41B.8080604@tds.net>
	<fbf64d2b0712101355u1252b1r2c9758739de418c0@mail.gmail.com>
	<475DB768.40506@tds.net>
Message-ID: <fbf64d2b0712101407m26a6f3bbn90189959808e4d98@mail.gmail.com>

I ran it both in IDLE and Command Prompt

On Dec 10, 2007 5:02 PM, Kent Johnson <kent37 at tds.net> wrote:

> How are you running the program?
>
> Bryan Fodness wrote:
> >
> > for line in file('test.txt'):
> >     the_line = line.split()
> >     if the_line:
> >         if the_line[0] == 'Index':
> >             index = float(the_line[-1])
> >             print ("\rIndex = %.3f  ") %index,
> > raw_input("\nExit")
> > Here is my output,
> >
> > Index = 0.000   Index = 0.400   Index = 0.800   Index = 1.000
> >
> >
> > On Dec 10, 2007 4:48 PM, Kent Johnson <kent37 at tds.net
> > <mailto:kent37 at tds.net>> wrote:
> >
> >     Bryan Fodness wrote:
> >      > Here is the code.
> >      >
> >      > for line in file('test.txt'):
> >      >     the_line = line.split()
> >      >     if the_line:
> >      >         if the_line[0] == 'Index':
> >      >             index = float(the_line[-1])
> >      >             print ("\rIndex = %.3f") %index
> >
> >     Add a comma at the end of the above line to suppress the newline
> that
> >     print normally outputs.
> >
> >     Kent
> >
> >      > raw_input("\nExit")
> >      >
> >      > Here is the output.
> >      >
> >      > Index = 0.000
> >      > Index = 0.400
> >      > Index = 0.800
> >      > Index = 1.000
> >      >
> >      > Exit
> >      >
> >      >
> >      > On Dec 10, 2007 4:33 PM, Kent Johnson <kent37 at tds.net
> >     <mailto:kent37 at tds.net>
>  >      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>> wrote:
> >      >
> >      >     Bryan Fodness wrote:
> >      >      > I do want to overwrite the same line.
> >      >      >
> >      >      > I do not see a difference between using the \r and not
> >     using it.
> >      >
> >      >     How are you running the program? Try it from a command line
> >     if that is
> >      >     not what you are doing. Can you show your new code?
> >      >
> >      >     Kent
> >      >
> >      >     PS Please Reply All to stay on the list.
> >      >
> >      >      >
> >      >      > On Dec 10, 2007 2:43 PM, Kent Johnson <kent37 at tds.net
> >     <mailto:kent37 at tds.net>
> >      >     <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>
> >      >      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>
> >     <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>>> wrote:
> >      >      >
> >      >      >     Bryan Fodness wrote:
> >      >      >      > I have a print statement in a for loop so I can
> >     watch the
> >      >     progress
> >      >      >      >
> >      >      >      > for line in file(file):
> >      >      >      >     the_line = line.split()
> >      >      >      >     if the_line:
> >      >      >      >         print ("Index = %.2f") %index
> >      >      >      >
> >      >      >      > Is there a way that only one line will be output
> >     and the
> >      >     variable is
> >      >      >      > updated rather than one line for every index.
> >      >      >
> >      >      >     I'm not sure I understand what you are asking. index
> >     is never
> >      >      >     updated in
> >      >      >     the loop above.
> >      >      >
> >      >      >     If you want to overwrite the same line on the console,
> try
> >      >      >       print "\rIndex = %.2f" % index,
> >      >      >
> >      >      >     note ----^
> >      >      >          ---------------------------^
> >      >      >
> >      >      >     You might need some extra spaces at the end of the
> >     print to
> >      >     'erase' a
> >      >      >     longer previous line.
> >      >      >
> >      >      >     Kent
> >      >      >
> >      >      >
> >      >      >
> >      >      >
> >      >      > --
> >      >      > "The game of science can accurately be described as a
> >     never-ending
> >      >      > insult to human intelligence." - Jo?o Magueijo
> >      >
> >      >
> >      >
> >      >
> >      > --
> >      > "The game of science can accurately be described as a
> never-ending
> >      > insult to human intelligence." - Jo?o Magueijo
> >
> >
> >
> >
> > --
> > "The game of science can accurately be described as a never-ending
> > insult to human intelligence." - Jo?o Magueijo
>
>


-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/38654df3/attachment-0001.htm 

From bryan.fodness at gmail.com  Mon Dec 10 23:14:27 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 10 Dec 2007 17:14:27 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <fbf64d2b0712101407m26a6f3bbn90189959808e4d98@mail.gmail.com>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>
	<475D96F9.9080300@tds.net>
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>
	<475DB0BE.2090304@tds.net>
	<fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>
	<475DB41B.8080604@tds.net>
	<fbf64d2b0712101355u1252b1r2c9758739de418c0@mail.gmail.com>
	<475DB768.40506@tds.net>
	<fbf64d2b0712101407m26a6f3bbn90189959808e4d98@mail.gmail.com>
Message-ID: <fbf64d2b0712101414n5586c181pe95fb5a44964139e@mail.gmail.com>

It works now.

Closed everything down and reopened.

Thanks.

On Dec 10, 2007 5:07 PM, Bryan Fodness <bryan.fodness at gmail.com> wrote:

> I ran it both in IDLE and Command Prompt
>
>
> On Dec 10, 2007 5:02 PM, Kent Johnson <kent37 at tds.net> wrote:
>
> > How are you running the program?
> >
> > Bryan Fodness wrote:
> > >
> > > for line in file('test.txt'):
> > >     the_line = line.split()
> > >     if the_line:
> > >         if the_line[0] == 'Index':
> > >             index = float(the_line[-1])
> > >             print ("\rIndex = %.3f  ") %index,
> > > raw_input("\nExit")
> > > Here is my output,
> > >
> > > Index = 0.000   Index = 0.400   Index = 0.800   Index = 1.000
> > >
> > >
> > > On Dec 10, 2007 4:48 PM, Kent Johnson <kent37 at tds.net
> > > <mailto:kent37 at tds.net>> wrote:
> > >
> > >     Bryan Fodness wrote:
> > >      > Here is the code.
> > >      >
> > >      > for line in file(' test.txt'):
> > >      >     the_line = line.split()
> > >      >     if the_line:
> > >      >         if the_line[0] == 'Index':
> > >      >             index = float(the_line[-1])
> > >      >             print ("\rIndex = %.3f") %index
> > >
> > >     Add a comma at the end of the above line to suppress the newline
> > that
> > >     print normally outputs.
> > >
> > >     Kent
> > >
> > >      > raw_input("\nExit")
> > >      >
> > >      > Here is the output.
> > >      >
> > >      > Index = 0.000
> > >      > Index = 0.400
> > >      > Index = 0.800
> > >      > Index = 1.000
> > >      >
> > >      > Exit
> > >      >
> > >      >
> > >      > On Dec 10, 2007 4:33 PM, Kent Johnson <kent37 at tds.net
> > >     <mailto:kent37 at tds.net >
> >  >      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>> wrote:
> > >      >
> > >      >     Bryan Fodness wrote:
> > >      >      > I do want to overwrite the same line.
> > >      >      >
> > >      >      > I do not see a difference between using the \r and not
> > >     using it.
> > >      >
> > >      >     How are you running the program? Try it from a command line
> > >     if that is
> > >      >     not what you are doing. Can you show your new code?
> > >      >
> > >      >     Kent
> > >      >
> > >      >     PS Please Reply All to stay on the list.
> > >      >
> > >      >      >
> > >      >      > On Dec 10, 2007 2:43 PM, Kent Johnson < kent37 at tds.net
> > >     <mailto:kent37 at tds.net>
> > >      >     <mailto:kent37 at tds.net <mailto: kent37 at tds.net>>
> > >      >      > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>
> > >     <mailto: kent37 at tds.net <mailto:kent37 at tds.net>>>> wrote:
> > >      >      >
> > >      >      >     Bryan Fodness wrote:
> > >      >      >      > I have a print statement in a for loop so I can
> > >     watch the
> > >      >     progress
> > >      >      >      >
> > >      >      >      > for line in file(file):
> > >      >      >      >     the_line = line.split()
> > >      >      >      >     if the_line:
> > >      >      >      >         print ("Index = %.2f") %index
> > >      >      >      >
> > >      >      >      > Is there a way that only one line will be output
> > >     and the
> > >      >     variable is
> > >      >      >      > updated rather than one line for every index.
> > >      >      >
> > >      >      >     I'm not sure I understand what you are asking. index
> >
> > >     is never
> > >      >      >     updated in
> > >      >      >     the loop above.
> > >      >      >
> > >      >      >     If you want to overwrite the same line on the
> > console, try
> > >      >      >       print "\rIndex = %.2f" % index,
> > >      >      >
> > >      >      >     note ----^
> > >      >      >          ---------------------------^
> > >      >      >
> > >      >      >     You might need some extra spaces at the end of the
> > >     print to
> > >      >     'erase' a
> > >      >      >     longer previous line.
> > >      >      >
> > >      >      >     Kent
> > >      >      >
> > >      >      >
> > >      >      >
> > >      >      >
> > >      >      > --
> > >      >      > "The game of science can accurately be described as a
> > >     never-ending
> > >      >      > insult to human intelligence." - Jo?o Magueijo
> > >      >
> > >      >
> > >      >
> > >      >
> > >      > --
> > >      > "The game of science can accurately be described as a
> > never-ending
> > >      > insult to human intelligence." - Jo?o Magueijo
> > >
> > >
> > >
> > >
> > > --
> > > "The game of science can accurately be described as a never-ending
> > > insult to human intelligence." - Jo?o Magueijo
> >
> >
>
>
> --
>
> "The game of science can accurately be described as a never-ending insult
> to human intelligence." - Jo?o Magueijo
>



-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/b07614c5/attachment.htm 

From kent37 at tds.net  Mon Dec 10 23:45:26 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 10 Dec 2007 17:45:26 -0500
Subject: [Tutor] updating a print statement
In-Reply-To: <fbf64d2b0712101407m26a6f3bbn90189959808e4d98@mail.gmail.com>
References: <fbf64d2b0712100956o29945bc9n12392fce02bf2ac0@mail.gmail.com>	
	<475D96F9.9080300@tds.net>	
	<fbf64d2b0712101321m4e43f505k814391d6c80effe3@mail.gmail.com>	
	<475DB0BE.2090304@tds.net>	
	<fbf64d2b0712101345w1e0821f7pe8d0eae803086e67@mail.gmail.com>	
	<475DB41B.8080604@tds.net>	
	<fbf64d2b0712101355u1252b1r2c9758739de418c0@mail.gmail.com>	
	<475DB768.40506@tds.net>
	<fbf64d2b0712101407m26a6f3bbn90189959808e4d98@mail.gmail.com>
Message-ID: <475DC186.4030107@tds.net>

This works for me:

import sys
import time
for i in range(5):
     print '\rIndex =', i,
     sys.stdout.flush()
     time.sleep(1)

Kent

Bryan Fodness wrote:
> I ran it both in IDLE and Command Prompt
> 
> On Dec 10, 2007 5:02 PM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
> 
>     How are you running the program?
> 
>     Bryan Fodness wrote:
>      >
>      > for line in file('test.txt'):
>      >     the_line = line.split()
>      >     if the_line:
>      >         if the_line[0] == 'Index':
>      >             index = float(the_line[-1])
>      >             print ("\rIndex = %.3f  ") %index,
>      > raw_input("\nExit")
>      > Here is my output,
>      >
>      > Index = 0.000   Index = 0.400   Index = 0.800   Index = 1.000


From john at fouhy.net  Tue Dec 11 00:10:16 2007
From: john at fouhy.net (John Fouhy)
Date: Tue, 11 Dec 2007 12:10:16 +1300
Subject: [Tutor] Windows Os Programming
In-Reply-To: <fjk1r8$e1c$1@ger.gmane.org>
References: <233349.51575.qm@web45904.mail.sp1.yahoo.com>
	<fjk1r8$e1c$1@ger.gmane.org>
Message-ID: <5e58f2e40712101510t241c3868jd8302d7d5992582a@mail.gmail.com>

On 11/12/2007, Alan Gauld <alan.gauld at btinternet.com> wrote:
> Finally investigate the MSDN web site for WSH which gives
> you relatively easy access to windows files, printers, registry and
> processes via a set of COM objects that can be instantiated from
> Python.

Also the Microsoft Script Centre has a repository of python scripts:
http://www.microsoft.com/technet/scriptcenter/scripts/python/default.mspx?mfr=true

-- 
John.

From john at fouhy.net  Tue Dec 11 00:14:18 2007
From: john at fouhy.net (John Fouhy)
Date: Tue, 11 Dec 2007 12:14:18 +1300
Subject: [Tutor] Formatting timedelta objects
In-Reply-To: <475D9074.8070305@airtelbroadband.in>
References: <475D9074.8070305@airtelbroadband.in>
Message-ID: <5e58f2e40712101514gafc06c7rd076537c488b9ade@mail.gmail.com>

On 11/12/2007, Noufal Ibrahim <noufal at airtelbroadband.in> wrote:
> Hello everyone,
>    This is probably something simple but I can't seem to find a way to
> format a timedelta object for printing? I need to be able to print it in
> a HH:MM:SS format but without the microseconds part (which is what you
> get if you str() it).
>
>    Any pointers?

datetime.timedelta have 'days', 'seconds' and 'microseconds'
attributes.  You could write your own formatter using the seconds
attribute.

e.g.:

def formatTD(td):
  hours = td.seconds // 3600
  minutes = (td.seconds % 3600) // 60
  seconds = td.seconds % 60
  return '%s:%s:%s' % (hours, minutes, seconds)

HTH!

-- 
John.

From wescpy at gmail.com  Tue Dec 11 00:16:45 2007
From: wescpy at gmail.com (wesley chun)
Date: Mon, 10 Dec 2007 15:16:45 -0800
Subject: [Tutor] Formatting timedelta objects
In-Reply-To: <475D9074.8070305@airtelbroadband.in>
References: <475D9074.8070305@airtelbroadband.in>
Message-ID: <78b3a9580712101516y3a68d957h21f942b638ac5846@mail.gmail.com>

>    This is probably something simple but I can't seem to find a way to
> format a timedelta object for printing? I need to be able to print it in
> a HH:MM:SS format but without the microseconds part (which is what you
> get if you str() it).


hi noufal,

there's no real easy way to do this since only date, datetime, and
time objects in datetime have strftime() methods.  timedelta objects
only give you days, seconds, and microseconds, so you have to roll
your own:

>>> z # some random timedelta object
datetime.timedelta(1, 84830, 429624)
>>> str(z)
'1 day, 23:33:50.429624'
>>> sec = z.days*24*60*60+z.seconds
>>> min, sec = divmod(sec, 60)
>>> hrs, min = divmod(min, 60)
>>> hrs, min, sec
(47, 33, 50)
>>> '%02d:%02d:%02d' % (hrs, min, sec)
'47:33:50'

if you want to round with microseconds, you'll have to add that to the
mix above.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

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

From wescpy at gmail.com  Tue Dec 11 00:24:07 2007
From: wescpy at gmail.com (wesley chun)
Date: Mon, 10 Dec 2007 15:24:07 -0800
Subject: [Tutor] Beat me over the head with it
In-Reply-To: <475B5C2F.6060300@gmail.com>
References: <475B5C2F.6060300@gmail.com>
Message-ID: <78b3a9580712101524l1659f478o3cb3e2dce8b45a19@mail.gmail.com>

> Hello everyone, names Theyain.  I want to learn Python.  But I am one of
> those people who needs some one to "Beat me over the head" to actually
> learn something.


pick up a copy of "Core Python Programming" and do every single
exercise in it.  i need an answer key. ;-)  there are more than 300
problems in the book, so you'll practically be a Python guru by the
time you're done.

cheers, and welcome to Python!
-- 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 alan.gauld at btinternet.com  Tue Dec 11 00:27:15 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 10 Dec 2007 23:27:15 +0000 (GMT)
Subject: [Tutor] Windows Os Programming
Message-ID: <173399.69340.qm@web86711.mail.ird.yahoo.com>


From: John Fouhy <john at fouhy.net>

>>  Finally investigate the MSDN web site for WSH which gives
>
>Also the Microsoft Script Centre has a repository of python scripts:
> http://www.microsoft.com/technet/scriptcenter/scripts/python/default.mspx?mfr=true



Wow! That's new since I last looked. And there's a lot of stuff there.
Thanks for that pointer John, It looks like Microsoft are taking Python 
seriously!

Alan g.


From earlylightpublishing at yahoo.com  Tue Dec 11 05:14:59 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Mon, 10 Dec 2007 20:14:59 -0800 (PST)
Subject: [Tutor] How is "tuple" pronounced?
Message-ID: <887525.29912.qm@web45113.mail.sp1.yahoo.com>

Is it tuh-ple (rhymes with supple)
   
  or is it two-ple (rhymes with nothing that I can think of)?


Please visit our website www.earlylightpublishing.com
       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/2763c718/attachment.htm 

From steve.reighard at gmail.com  Tue Dec 11 05:23:43 2007
From: steve.reighard at gmail.com (steve reighard)
Date: Mon, 10 Dec 2007 23:23:43 -0500
Subject: [Tutor] How is "tuple" pronounced?
In-Reply-To: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
References: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
Message-ID: <85661be80712102023s86d895fv62105d0193b5e695@mail.gmail.com>

On Dec 10, 2007 11:14 PM, earlylight publishing <
earlylightpublishing at yahoo.com> wrote:

> Is it tuh-ple (rhymes with supple)
>
> or is it two-ple (rhymes with nothing that I can think of)?
>
> How unscrupulous of you!

>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071210/ab791767/attachment.htm 

From mlangford.cs03 at gtalumni.org  Tue Dec 11 05:24:55 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 10 Dec 2007 23:24:55 -0500
Subject: [Tutor] How is "tuple" pronounced?
In-Reply-To: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
References: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
Message-ID: <82b4f5810712102024r45d9d366l3798dd3b1238dc47@mail.gmail.com>

Tuple, rhymes with "you pull"

      --Michael

On 12/10/07, earlylight publishing <earlylightpublishing at yahoo.com> wrote:
> Is it tuh-ple (rhymes with supple)
>
> or is it two-ple (rhymes with nothing that I can think of)?
>
> Please visit our website www.earlylightpublishing.com
>
>  ________________________________
> Never miss a thing. Make Yahoo your homepage.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From amitsaxena69 at gmail.com  Tue Dec 11 05:32:37 2007
From: amitsaxena69 at gmail.com (Amit Saxena)
Date: Tue, 11 Dec 2007 10:02:37 +0530
Subject: [Tutor] Noob question
In-Reply-To: <475D5AE1.7020705@brunson.com>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>
	<475C3959.3030209@brunson.com> <475C60CB.9060401@ericwalstad.com>
	<fji46a$oo3$1@ger.gmane.org>
	<82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>
	<475D5AE1.7020705@brunson.com>
Message-ID: <82c58b390712102032l616acd4o9775ca0f9028ad4c@mail.gmail.com>

Hi Eric,

Thanks for the information..............since i m new to Python so didnt
knew about this fact...........thanks again for it, will keep it in mind
while writing such a program.

Amit

On Dec 10, 2007 8:57 PM, Eric Brunson <brunson at brunson.com> wrote:

>
> Hi Amit,
>
> This is fairly inefficient.  Because strings in python are immutable
> this approach causes a new string to be created every iteration.  While
> it may not be an issue with just 3 strings, it is much better to create
> your list and use "".join() to create the concatenation after the list
> is complete.  When you get used to it, it's a bit more concise and
> readable, also.
>
> Sincerely,
> e.
>
> Amit Saxena wrote:
> > The simplest way i could think of:
> >
> > a=["apple","orange","banana"]
> > b = ""
> > for i in range(len(a)):
> >      b += a[i]
> > print b
> >
> >
> > Amit
> >
> > On Dec 10, 2007 6:48 AM, Alan Gauld <alan.gauld at btinternet.com
> > <mailto:alan.gauld at btinternet.com>> wrote:
> >
> >     "Eric Walstad" <eric at ericwalstad.com
> >     <mailto:eric at ericwalstad.com>> wrote
> >
> >     > You could also achieve the same result of concatenating a list of
> >     > strings by looping over the list items like so:
> >     >
> >     > b = ''
> >     > for fruit in a:
> >     >    b += fruit
> >     >
> >     > print b
> >
> >     And to add to the options you could use the formatting operator
> >     provided you know there are only 3 items,
> >
> >     b = "%s%s%s" % tuple(a)
> >
> >     Or for an indefinite number of strings:
> >
> >     b = "%s" * len(a)
> >     b = b % tuple(a)
> >
> >     So many options. However, to the OP, if you get stuck in
> >     future its best if you post the erroneous code that you have tried,
> >     then we can better see where you have gone wrong and thus
> >     provide clearer guidance on how to fix it. Its better to learn to
> >     do it your own way correctly than just to see other folks
> >     attempts .
> >
> >     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 <mailto:Tutor at python.org>
> >     http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>


-- 
Thanks and Regards,
Amit Saxena
Senior QA Engineer
Ketera
Direct: +91 4199 5028
Mobile: +91 99001 18641
asaxena at ketera.com

? Visit us at http://www.ketera.com
? Watch the demo at http://www.ketera.com/resources/demos.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071211/530f8c90/attachment.htm 

From jeff at mossycup.com  Tue Dec 11 06:10:33 2007
From: jeff at mossycup.com (Jeff Stevens)
Date: Mon, 10 Dec 2007 21:10:33 -0800
Subject: [Tutor] How is "tuple" pronounced?
In-Reply-To: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
References: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
Message-ID: <1197349833.3571.119.camel@varroa.int.mossycup.com>

On Mon, 2007-12-10 at 20:14 -0800, earlylight publishing wrote:
> Is it tuh-ple (rhymes with supple)
>  
> or is it two-ple (rhymes with nothing that I can think of)?

It it probably Latin so:

A.  Pronounce it the same way you would in the words quintuple,
sextuple, septuple, etc.

B.  Latin is no longer a spoken language; Pronounce it how you like.

-Jeff


From brunson at brunson.com  Tue Dec 11 07:15:01 2007
From: brunson at brunson.com (Eric Brunson)
Date: Mon, 10 Dec 2007 23:15:01 -0700
Subject: [Tutor] How is "tuple" pronounced?
In-Reply-To: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
References: <887525.29912.qm@web45113.mail.sp1.yahoo.com>
Message-ID: <475E2AE5.20503@brunson.com>

earlylight publishing wrote:
> Is it tuh-ple (rhymes with supple)
>  
> or is it two-ple (rhymes with nothing that I can think of)?

As a mathematician, I've always heard it pronounced "toople", even 
though when you put a prefix on it (quintuple, sextuple, octuple) it 
becomes "tuhple".  We're mathematicians, not linguists.  :-)

Guido says, "toople".  *shrug*


>
>
> Please visit our website www.earlylightpublishing.com
>
> ------------------------------------------------------------------------
> Never miss a thing. Make Yahoo your homepage. 
> <http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From tetsuo2k6 at web.de  Tue Dec 11 13:11:34 2007
From: tetsuo2k6 at web.de (Paul Schewietzek)
Date: Tue, 11 Dec 2007 13:11:34 +0100
Subject: [Tutor] Beat me over the head with it
In-Reply-To: <475B5C2F.6060300@gmail.com>
References: <475B5C2F.6060300@gmail.com>
Message-ID: <475E7E76.3000100@web.de>

Theyain schrieb:
> I'm not sure if this is really the place to do this, but I will ask anyways.
> 
> Hello everyone, names Theyain.  I want to learn Python.  But I am one of 
> those people who needs some one to "Beat me over the head" to actually 
> learn something.  I can't get myself to actually sit down and read a 
> tutorial on Python because no one is making me.  So can someone help me 
> with this?  I really want to learn python, but I can't do it with out help.
> 
> 
> So help?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

Reminds me of the all-queen problem... :)

If you know chess, you could try the following:

Step 1: Arrange 8 queens on a chessboard in a way that no queen is 
threatened by any other.

Step 2: Write a script that prints out all possible solutions to this 
problem. Can be printed in text-mode so you don't have to worry about 
real graphics when starting, like this:

	 ---------------
	| | | | | | | | |
	 ---------------
	| | | | | | | | |
	 ---------------
	| | | |X| | | | |
	 ---------------
	| | | | | | | | |
	 ---------------
	| |X| | | | | | |
	 ---------------
	| | | | | | | | |
	 ---------------
	| | | | | |X| | |
	 ---------------
	| | | | | | | | |
	 ---------------

	where X is a queen - of course there shall be eight (8) X'es :)

Step 3: Make the board scalable (6 queens on a 6x6 board, 12 queens on a 
12x12 board, n queens on a n x n board) - Hint: 4 is the minimum, 
smaller setups have no solution.

This exercise isn't really meant to learn a specific language, but 
rather to learn how to solve a problem algorythmically - However it WILL 
give you a feeling for Python, tracing back the bugs you will encounter :)

If you feel it is to hard, write back and I'll give you hints how to 
structure the script (logically - I definitively have no time for syntax 
questions. And by the way, I am relatively new to Python myself :))

Good Luck!

From kent37 at tds.net  Tue Dec 11 13:19:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Dec 2007 07:19:28 -0500
Subject: [Tutor] Noob question
In-Reply-To: <475D5AE1.7020705@brunson.com>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>	<475C3959.3030209@brunson.com>	<475C60CB.9060401@ericwalstad.com>	<fji46a$oo3$1@ger.gmane.org>	<82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>
	<475D5AE1.7020705@brunson.com>
Message-ID: <475E8050.1020201@tds.net>

Eric Brunson wrote:
> Hi Amit,
> 
> This is fairly inefficient.  Because strings in python are immutable 
> this approach causes a new string to be created every iteration.

This is not true of CPython (the standard python.org release) since 
version 2.4:
http://www.python.org/doc/2.4.4/whatsnew/node12.html#SECTION0001210000000000000000

Other versions of Python (Jython, IronPython, PyPy) do not have this 
optimization AFAIK.

Kent

> 
> Amit Saxena wrote:
>> The simplest way i could think of:
>>
>> a=["apple","orange","banana"]
>> b = ""
>> for i in range(len(a)):
>>      b += a[i]
>> print b

From rdm at rcblue.com  Tue Dec 11 22:43:19 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 11 Dec 2007 13:43:19 -0800
Subject: [Tutor] Noob question
In-Reply-To: <475E8050.1020201@tds.net>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>
	<475C3959.3030209@brunson.com> <475C60CB.9060401@ericwalstad.com>
	<fji46a$oo3$1@ger.gmane.org>
	<82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>
	<475D5AE1.7020705@brunson.com> <475E8050.1020201@tds.net>
Message-ID: <20071211214347.F36B21E401C@bag.python.org>

At 04:19 AM 12/11/2007, Kent Johnson wrote:
>Eric Brunson wrote:
> > Hi Amit,
> >
> > This is fairly inefficient.  Because strings in python are immutable
> > this approach causes a new string to be created every iteration.
>
>This is not true of CPython (the standard python.org release) since
>version 2.4:
>http://www.python.org/doc/2.4.4/whatsnew/node12.html#SECTION0001210000000000000000
>
>Other versions of Python (Jython, IronPython, PyPy) do not have this
>optimization AFAIK.

Concatenating strings is still VERY slow in CPython 2.5.1 compared to 
using join(), however. See <http://py77.python.pastebin.com/f66c3b3da>.

Dick Moores 


From earlylightpublishing at yahoo.com  Tue Dec 11 22:55:18 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Tue, 11 Dec 2007 13:55:18 -0800 (PST)
Subject: [Tutor] How is "tuple" pronounced?
In-Reply-To: <c9415b010712110500w37c584f6qa5e301cde45647e@mail.gmail.com>
Message-ID: <264326.10329.qm@web45105.mail.sp1.yahoo.com>

So it looks like most folks here and on the web are saying too-ple (rhymes with scruple or pupil... sorta).  That's the one I'll go with... now that I can say it it's time to get back to learning how to use em!



Please visit our website www.earlylightpublishing.com
       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071211/24e65714/attachment.htm 

From wescpy at gmail.com  Tue Dec 11 23:05:56 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 11 Dec 2007 14:05:56 -0800
Subject: [Tutor] Noob question
In-Reply-To: <20071211214347.F36B21E401C@bag.python.org>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>
	<475C3959.3030209@brunson.com> <475C60CB.9060401@ericwalstad.com>
	<fji46a$oo3$1@ger.gmane.org>
	<82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>
	<475D5AE1.7020705@brunson.com> <475E8050.1020201@tds.net>
	<20071211214347.F36B21E401C@bag.python.org>
Message-ID: <78b3a9580712111405xfbc4922kc81bb0e790989371@mail.gmail.com>

> > > This is fairly inefficient.  Because strings in python are immutable
> > > this approach causes a new string to be created every iteration.
> >
> >This is not true of CPython (the standard python.org release) since
> >version 2.4:
> >http://www.python.org/doc/2.4.4/whatsnew/node12.html#SECTION0001210000000000000000


i'm also fairly certain that this minor improvement only works for
strings and not other sequences.  it is also not recommended to
concatenate lists either, for similar reasons.  it's better to use the
list.extend() method to add the contents of one list to another,
rather than creating a 3rd list which is the sum of the 1st pair.

to its defense however, i have seen some use cases where list
concatenation is the simplest choice in the code. it usually occurs
when you need a list but with a couple more items added to it (so you
can act upon the larger list), and neither append() nor extend() have
return values. now whether or not you wish to modify the original list
needs to be figured in as well.

-- 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 bhaaluu at gmail.com  Wed Dec 12 03:45:49 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Tue, 11 Dec 2007 21:45:49 -0500
Subject: [Tutor] How is "tuple" pronounced?
In-Reply-To: <264326.10329.qm@web45105.mail.sp1.yahoo.com>
References: <c9415b010712110500w37c584f6qa5e301cde45647e@mail.gmail.com>
	<264326.10329.qm@web45105.mail.sp1.yahoo.com>
Message-ID: <ea979d70712111845k4a643945icd7f0bd7577ec3a1@mail.gmail.com>

Greetz!
On Dec 11, 2007 4:55 PM, earlylight publishing
<earlylightpublishing at yahoo.com> wrote:
> So it looks like most folks here and on the web are saying too-ple (rhymes
> with scruple or pupil... sorta).  That's the one I'll go with... now that I
> can say it it's time to get back to learning how to use em!

There is tuple packing and tuple unpacking! Wierd, eh?

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python.index.html

From bryan.fodness at gmail.com  Wed Dec 12 04:10:09 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Tue, 11 Dec 2007 22:10:09 -0500
Subject: [Tutor] Parsing DICOMRT file
Message-ID: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>

I am trying to parse a DICOMRT file, which is a radiation therapy DICOM
file.

First, I get different outputs from the two methods below.

for line in file('file.dcm', 'rb'):
    print line

inp = open('file.dcm', 'rb')
print inp.readlines()

Second, I have never tried to parse a binary file.  I could use a few hints
to get started.

Bryan

-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071211/48fa828d/attachment.htm 

From bgailer at alum.rpi.edu  Wed Dec 12 05:06:57 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 11 Dec 2007 23:06:57 -0500
Subject: [Tutor] Parsing DICOMRT file
In-Reply-To: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
References: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
Message-ID: <475F5E61.3060103@alum.rpi.edu>

Bryan Fodness wrote:
> I am trying to parse a DICOMRT file, which is a radiation therapy 
> DICOM file. 
>  
> First, I get different outputs from the two methods below.
>  
> for line in file('file.dcm', 'rb'):
>     print line
>    
> inp = open('file.dcm', 'rb')
> print inp.readlines()
I agree. I'd expect that. Why does it surprise you? What did you expect?
>  
> Second, I have never tried to parse a binary file.  I could use a few 
> hints to get started.
Hint 1 - tell us what the fie format is and what you want from "parsing" it.

Most of us here are not acquainted with DICOM files.

From alan.gauld at btinternet.com  Wed Dec 12 08:15:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 12 Dec 2007 07:15:35 -0000
Subject: [Tutor] Parsing DICOMRT file
References: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
Message-ID: <fjo1qo$g0b$1@ger.gmane.org>

"Bryan Fodness" <bryan.fodness at gmail.com> wrote

> First, I get different outputs from the two methods below.
>
> for line in file('file.dcm', 'rb'):
>     print line

This prints each line in turn.

> inp = open('file.dcm', 'rb')
> print inp.readlines()

This prints a list of lines

> Second, I have never tried to parse a binary file.  I could use a 
> few hints
> to get started.

Take a look at my File handling topic which gives a simple example.
(about 2/3 of the way down)

Basically the key is to know what the data looks like and define a
struct pattern to match. Note that the data may well not be
accessible using readline, you may need to use read with an length
argument. See help(read)...

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



From gmoonn at gmail.com  Wed Dec 12 09:05:24 2007
From: gmoonn at gmail.com (Gman)
Date: Wed, 12 Dec 2007 03:05:24 -0500
Subject: [Tutor] Python Versions
Message-ID: <op.t27p3azgjgjj51@dialup-4.225.228.112.dial1.detroit1.level3.net>

Hmm how do I put this without looking completely igrint! I am new to  
python and peck away at it every chance i get.Well I also follow the list  
here and remember A big todo about versions
and compatibility. Well I have 2.51 and have been encountering many errors  
when I try to use some examples from the book "A byte of python". At first  
I thought well a few minor things I will just move on and try the next.  
Well some work and others dont, and mind you I am only trying to get the  
basics down.Anyhow in the forward of the book it is refering to 2.3, could  
the very basics have changed from 2.3 to 2.5. Once again not all of them  
just some of them.
I will send examples if you think it is my editing in question.I know I  
could just get a different book, there is a plethora to choose from but I  
thought I had A good beginner book?
Oh and I know you buried this one but...I thought it was tuple` like  
too-play.

(sounds french chic's will dig it) Sorry had to throw that in there, a  
liitle humor is always good.....

-- 
Look sure in soup with socks dirty when to put with cracker in boots that  
I on wear to crunch.

From wescpy at gmail.com  Wed Dec 12 09:19:29 2007
From: wescpy at gmail.com (wesley chun)
Date: Wed, 12 Dec 2007 00:19:29 -0800
Subject: [Tutor] Python Versions
In-Reply-To: <op.t27p3azgjgjj51@dialup-4.225.228.112.dial1.detroit1.level3.net>
References: <op.t27p3azgjgjj51@dialup-4.225.228.112.dial1.detroit1.level3.net>
Message-ID: <78b3a9580712120019wd68527akecf30b525751c1a3@mail.gmail.com>

> Well I have 2.51 and have been encountering many errors
> when I try to use some examples from the book "A byte of python". At first
> I thought well a few minor things I will just move on and try the next.
> Well some work and others dont, and mind you I am only trying to get the
> basics down.Anyhow in the forward of the book it is refering to 2.3, could
> the very basics have changed from 2.3 to 2.5. Once again not all of them
> just some of them.

send your code examples and the errors you've received.  ppl should be
able to figure out what your problems are from there.


> I know I
> could just get a different book, there is a plethora to choose from but I
> thought I had A good beginner book?

it depends on your programming experience.  if you could elaborate on
that, then folks here can recommend the books we think are right for
you.

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

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

From earlylightpublishing at yahoo.com  Wed Dec 12 13:31:13 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Wed, 12 Dec 2007 04:31:13 -0800 (PST)
Subject: [Tutor] Python Versions
Message-ID: <96230.68789.qm@web45114.mail.sp1.yahoo.com>

I have the latest python version too when I first started "A Byte of Python" my code wouldn't work either.  My problem was that I was programming in the shell (the screen with the three '>>>' on it).  I found when I wrote the examples in a new window (cntrl+N) they all worked as advertized.  He never mentions that you need to use an 'editing window' (I think it's called).  I just stumbled across the fact.
       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071212/6bb1dd3f/attachment.htm 

From kent37 at tds.net  Wed Dec 12 13:37:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Dec 2007 07:37:47 -0500
Subject: [Tutor] Python Versions
In-Reply-To: <op.t27p3azgjgjj51@dialup-4.225.228.112.dial1.detroit1.level3.net>
References: <op.t27p3azgjgjj51@dialup-4.225.228.112.dial1.detroit1.level3.net>
Message-ID: <475FD61B.3080400@tds.net>

Gman wrote:
> Hmm how do I put this without looking completely igrint! 

No worries, this is a list for beginners!

> I have 2.51 and have been encountering many errors  
> when I try to use some examples from the book "A byte of python". At first  
> I thought well a few minor things I will just move on and try the next.  
> Well some work and others dont, and mind you I am only trying to get the  
> basics down.Anyhow in the forward of the book it is refering to 2.3, could  
> the very basics have changed from 2.3 to 2.5. Once again not all of them  
> just some of them.

Most of the changes from Python 2.3 to 2.5 are backward-compatible. You 
should not be having many problems with the examples. Post specifics 
here so we can help. Please show the exact code you are trying, and the 
complete error message including traceback.

Read the details of what has changed here:
http://www.python.org/doc/2.4.4/whatsnew/whatsnew24.html
http://docs.python.org/whatsnew/whatsnew25.html

Kent

From rdm at rcblue.com  Wed Dec 12 14:53:35 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 12 Dec 2007 05:53:35 -0800
Subject: [Tutor] Noob question
In-Reply-To: <20071211214347.F36B21E401C@bag.python.org>
References: <302436.99174.qm@web31413.mail.mud.yahoo.com>
	<475C3959.3030209@brunson.com> <475C60CB.9060401@ericwalstad.com>
	<fji46a$oo3$1@ger.gmane.org>
	<82c58b390712100519y38da505di3a0e66aec33c69b6@mail.gmail.com>
	<475D5AE1.7020705@brunson.com> <475E8050.1020201@tds.net>
	<20071211214347.F36B21E401C@bag.python.org>
Message-ID: <20071212135339.592481E4006@bag.python.org>

At 01:43 PM 12/11/2007, Dick Moores wrote:
>Concatenating strings is still VERY slow in CPython 2.5.1 compared to
>using join(), however. See <http://py77.python.pastebin.com/f66c3b3da>.

Code slightly modified and moved to <http://py77.python.pastebin.com/f4c6d3a69>

Dick




From alan.gauld at btinternet.com  Wed Dec 12 23:04:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 12 Dec 2007 22:04:59 -0000
Subject: [Tutor] Python Versions
References: <96230.68789.qm@web45114.mail.sp1.yahoo.com>
Message-ID: <fjpluc$9po$1@ger.gmane.org>

"earlylight publishing" <earlylightpublishing at yahoo.com> wrote

>I have the latest python version too when I first started "A Byte of 
>Python"
> my code wouldn't work either.  My problem was that I was programming
> in the shell (the screen with the three '>>>' on it).  I found when 
> I wrote
> the examples in a new window (cntrl+N) they all worked as 
> advertized.

Unless you are doing some strange GUI type things it should work at
the >>> prompt too. (Sometimes you need an extra line - that could
fox beginners I suspect, if his examples contain multiple statements)

> He never mentions that you need to use an 'editing window'
> (I think it's called).  I just stumbled across the fact.

You shouldn't need to use an editing window, but the >>> prompt
does execute each line 9or block) in turn thus:

x=0
for n in range(5):
    x = n+x
print x

looks like this in IDLE:

>>> x=0
>>> for n in range(5):
    x = n+x
                                            <--Extra line here!
>>> print x
10
>>>

Is that the kind of thing you are seeing?


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



From keridee at jayco.net  Wed Dec 12 23:48:36 2007
From: keridee at jayco.net (Tiger12506)
Date: Wed, 12 Dec 2007 22:48:36 -0000
Subject: [Tutor] Python Versions
References: <96230.68789.qm@web45114.mail.sp1.yahoo.com>
	<fjpluc$9po$1@ger.gmane.org>
Message-ID: <001101c95cab$c4fd56f0$91fce004@jslaptop>

The OP has not specified what his problems specifically are, but "earlylight 
publishing" described his problem before, and he was not understanding why 
the >>> prompt was expecting immediate keyboard input when he typed in 
raw_input(). So a noob cannot figure out why it is advantageous to have a 
raw_input function that immediately asks for input. He thinks, "why can't I 
put the input in directly?" That is why putting a program into an edit 
window is very advantageous.

I believe it is very likely that raw_input() is the culprit of confusion 
here. 


From john at fouhy.net  Wed Dec 12 23:57:03 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 13 Dec 2007 11:57:03 +1300
Subject: [Tutor] Parsing DICOMRT file
In-Reply-To: <fbf64d2b0712121427y495b80f3sbaf21eec4e003a82@mail.gmail.com>
References: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
	<5e58f2e40712112001q578b2674u7156b806d2c70ba5@mail.gmail.com>
	<fbf64d2b0712121427y495b80f3sbaf21eec4e003a82@mail.gmail.com>
Message-ID: <5e58f2e40712121457x20e5d3d4rf43724bda49878b2@mail.gmail.com>

On 13/12/2007, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> I am new to doing anything like this.  I have looked at
> http://www.leadtools.com/SDK/Medical/DICOM/ltdc1.htm and am
> not sure how to proceed.

I haven't much experience here, but this is how I'd proceed, I think:

1. Start by reading the file.  It's binary data (I guess) so there's
no point in reading lines.:
  rawData = open('file.dcm', 'rb').read()

2. Write a function to parse the preamble:

  def parsePreamble(data):
    preamble = data[:128]
    dicm = data[128:132]

    # you might need to read up on encodings and things to make sure
this test is valid
    if dicm == 'DICM':
      return preamble, 132
    else:
      raise NotAPreambleException

3. Write functions to parse data elements.  The functions are going to
try to parse a data element starting at a particular position, and if
successful, return the position of the end of the element.

  def parseDataelement(data, start):
    # do stuff -- the web page you linked didn't have enough information here
    return element, pos

4. Parse the whole thing;

  def parseDICOM(data):
    elements = []
    try:
      preamble, next = parsePreamble(data)
    except NotAPreambleException:
      preamble, next = None, 0

    while True:
      element, next = parseDataElement(data, next)
      elements.append(element)
      # you will need some way of breaking out of this loop, either by
checking the structure of
      # element for an end condition, or by parseDataElement raising
an exception.

    return elements # and maybe preamble too if you want it

HTH!

From bryan.fodness at gmail.com  Thu Dec 13 00:12:05 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Wed, 12 Dec 2007 18:12:05 -0500
Subject: [Tutor] Parsing DICOMRT file
In-Reply-To: <5e58f2e40712121457x20e5d3d4rf43724bda49878b2@mail.gmail.com>
References: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
	<5e58f2e40712112001q578b2674u7156b806d2c70ba5@mail.gmail.com>
	<fbf64d2b0712121427y495b80f3sbaf21eec4e003a82@mail.gmail.com>
	<5e58f2e40712121457x20e5d3d4rf43724bda49878b2@mail.gmail.com>
Message-ID: <fbf64d2b0712121512u13ced122v7509cd40a4b089e8@mail.gmail.com>

Thanks for the immediate response!

On Dec 12, 2007 5:57 PM, John Fouhy <john at fouhy.net> wrote:

> On 13/12/2007, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> > I am new to doing anything like this.  I have looked at
> > http://www.leadtools.com/SDK/Medical/DICOM/ltdc1.htm and am
> > not sure how to proceed.
>
> I haven't much experience here, but this is how I'd proceed, I think:
>
> 1. Start by reading the file.  It's binary data (I guess) so there's
> no point in reading lines.:
>  rawData = open('file.dcm', 'rb').read()
>
> 2. Write a function to parse the preamble:
>
>  def parsePreamble(data):
>    preamble = data[:128]
>    dicm = data[128:132]
>
>    # you might need to read up on encodings and things to make sure
> this test is valid
>    if dicm == 'DICM':
>      return preamble, 132
>    else:
>      raise NotAPreambleException
>
> 3. Write functions to parse data elements.  The functions are going to
> try to parse a data element starting at a particular position, and if
> successful, return the position of the end of the element.
>
>  def parseDataelement(data, start):
>    # do stuff -- the web page you linked didn't have enough information
> here
>    return element, pos
>
> 4. Parse the whole thing;
>
>  def parseDICOM(data):
>    elements = []
>    try:
>      preamble, next = parsePreamble(data)
>    except NotAPreambleException:
>      preamble, next = None, 0
>
>    while True:
>      element, next = parseDataElement(data, next)
>      elements.append(element)
>      # you will need some way of breaking out of this loop, either by
> checking the structure of
>      # element for an end condition, or by parseDataElement raising
> an exception.
>
>    return elements # and maybe preamble too if you want it
>
> HTH!
>



-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071212/f3d1c632/attachment.htm 

From brunson at brunson.com  Thu Dec 13 00:18:53 2007
From: brunson at brunson.com (Eric Brunson)
Date: Wed, 12 Dec 2007 16:18:53 -0700
Subject: [Tutor] Parsing DICOMRT file
In-Reply-To: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
References: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
Message-ID: <47606C5D.8080605@brunson.com>

Bryan Fodness wrote:
> I am trying to parse a DICOMRT file, which is a radiation therapy 
> DICOM file.

I'm a little late to the party, but you may want to take a look at this:

http://mypage.iu.edu/~mmiller3/python/#dycom



>  
> First, I get different outputs from the two methods below.
>  
> for line in file('file.dcm', 'rb'):
>     print line
>    
> inp = open('file.dcm', 'rb')
> print inp.readlines()
>  
> Second, I have never tried to parse a binary file.  I could use a few 
> hints to get started.
>  
> Bryan
>
> -- 
> "The game of science can accurately be described as a never-ending 
> insult to human intelligence." - Jo?o Magueijo
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From bryan.fodness at gmail.com  Thu Dec 13 00:22:54 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Wed, 12 Dec 2007 18:22:54 -0500
Subject: [Tutor] Parsing DICOMRT file
In-Reply-To: <47606C5D.8080605@brunson.com>
References: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
	<47606C5D.8080605@brunson.com>
Message-ID: <fbf64d2b0712121522i78da4519pab225aab6bf0d3e4@mail.gmail.com>

Just downloaded it and have not had a chance to check it out.

Thanks,
Bryan

On Dec 12, 2007 6:18 PM, Eric Brunson <brunson at brunson.com> wrote:

> Bryan Fodness wrote:
> > I am trying to parse a DICOMRT file, which is a radiation therapy
> > DICOM file.
>
> I'm a little late to the party, but you may want to take a look at this:
>
> http://mypage.iu.edu/~mmiller3/python/#dycom
>
>
>
> >
> > First, I get different outputs from the two methods below.
> >
> > for line in file('file.dcm', 'rb'):
> >     print line
> >
> > inp = open('file.dcm', 'rb')
> > print inp.readlines()
> >
> > Second, I have never tried to parse a binary file.  I could use a few
> > hints to get started.
> >
> > Bryan
> >
> > --
> > "The game of science can accurately be described as a never-ending
> > insult to human intelligence." - Jo?o Magueijo
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>


-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071212/728f7881/attachment-0001.htm 

From kent37 at tds.net  Thu Dec 13 00:55:11 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Dec 2007 18:55:11 -0500
Subject: [Tutor] Parsing DICOMRT file
In-Reply-To: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
References: <fbf64d2b0712111910y449ab7a1rd769a74761294f7e@mail.gmail.com>
Message-ID: <476074DF.8060304@tds.net>

Bryan Fodness wrote:
> I am trying to parse a DICOMRT file, which is a radiation therapy DICOM 
> file. 

This might be helpful - I haven't tried it, but it seems to be designed 
for this sort of thing:
http://construct.wikispaces.com/

Also googling 'python dicom' gets quite a few hits.

Kent

From lavendula6654 at yahoo.com  Thu Dec 13 01:07:40 2007
From: lavendula6654 at yahoo.com (Elaine)
Date: Wed, 12 Dec 2007 16:07:40 -0800 (PST)
Subject: [Tutor] Computer Classes at Foothill
Message-ID: <336757.77266.qm@web31707.mail.mud.yahoo.com>

Winter quarter classes start Monday, 7 January, at
Foothill College.
These two may be of interest to you:

1) Introduction to Python Programming
Prerequisite: Any programming language experience
CIS 68K - Monday evenings at Middlefield campus in
Palo Alto

2) Application Software Development with Ajax
Prerequisite: Knowledge  of HTML and JavaScript 
COIN 71 - Thursday evenings at Middlefield campus in
Palo Alto

If you are interested in taking a class, please
register as soon as possible by going to:
http://www.foothill.fhda.edu/reg/index.php
If not enough students sign up, a class may be
cancelled.

If you have any questions, please contact the
instructor, Elaine Haight, at
haightElaine at foothill.edu



      ____________________________________________________________________________________
Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  http://tools.search.yahoo.com/newsearch/category.php?category=shopping

From robrecc at gmail.com  Thu Dec 13 03:48:12 2007
From: robrecc at gmail.com (Robert Recchia)
Date: Wed, 12 Dec 2007 21:48:12 -0500
Subject: [Tutor] python and interface duplex checks
Message-ID: <15b2d9090712121848g7f04f871o844450ccd3cb17d@mail.gmail.com>

I was wondering can python can be used to check the duplex settings of a
network card on a Linux os.

-- 
Robert Recchia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071212/fcded704/attachment.htm 

From mlangford.cs03 at gtalumni.org  Thu Dec 13 05:01:27 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 12 Dec 2007 23:01:27 -0500
Subject: [Tutor] python and interface duplex checks
In-Reply-To: <15b2d9090712121848g7f04f871o844450ccd3cb17d@mail.gmail.com>
References: <15b2d9090712121848g7f04f871o844450ccd3cb17d@mail.gmail.com>
Message-ID: <82b4f5810712122001n4be703e3vc1cb5088fdb621e8@mail.gmail.com>

Most easily: If your card supports ethtool, you can just open the
ethtool startup config file to check there whether or not you set it
to duplex in the configuration (see if you have an ETHTOOL_OPTS env
variable).

If you're not sure if your card can handle duplex (or you're not sure
the config file accurately shows what your card is set to), then you
can (more complicatedly) run ethtool with
popen(http://docs.python.org/lib/os-newstreams.html#os-newstreams) and
look for the status by parsing the duplex line.

If you're not yet using ethtool, you should if you can. If you can't
reply back to the list and I'll delve into the older mii-tools to tell
you which one to hack on.

          --Michael

On Dec 12, 2007 9:48 PM, Robert Recchia <robrecc at gmail.com> wrote:
> I was wondering can python can be used to check the duplex settings of a
> network card on a Linux os.
>
> --
> Robert Recchia
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From michael.langford at gmail.com  Thu Dec 13 05:05:56 2007
From: michael.langford at gmail.com (Michael Langford)
Date: Wed, 12 Dec 2007 23:05:56 -0500
Subject: [Tutor]  python and interface duplex checks
In-Reply-To: <82b4f5810712122001n4be703e3vc1cb5088fdb621e8@mail.gmail.com>
References: <15b2d9090712121848g7f04f871o844450ccd3cb17d@mail.gmail.com>
	<82b4f5810712122001n4be703e3vc1cb5088fdb621e8@mail.gmail.com>
Message-ID: <82b4f5810712122005qbe35b25y7db015548bcd449f@mail.gmail.com>

Most easily: If your card supports ethtool, you can just open the
ethtool startup config file to check there whether or not you set it
to duplex in the configuration (see if you have an ETHTOOL_OPTS env
variable).

If you're not sure if your card can handle duplex (or you're not sure
the config file accurately shows what your card is set to), then you
can (more complicatedly) run ethtool with
popen(http://docs.python.org/lib/os-newstreams.html#os-newstreams) and
look for the status by parsing the duplex line.

If you're not yet using ethtool, you should if you can. If you can't
reply back to the list and I'll delve into the older mii-tools to tell
you which one to hack on.

          --Michael


On Dec 12, 2007 9:48 PM, Robert Recchia <robrecc at gmail.com> wrote:
> I was wondering can python can be used to check the duplex settings of a
> network card on a Linux os.
>
> --
> Robert Recchia
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



--
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From pine508 at hotmail.com  Thu Dec 13 05:35:44 2007
From: pine508 at hotmail.com (Che M)
Date: Wed, 12 Dec 2007 23:35:44 -0500
Subject: [Tutor] user-given variable names for objects
Message-ID: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>






I'm sure this is a classic beginner's topic, and I've read a bit about it online already, but I'd like to ask about it here as well.  I want to assign names to objects based on what a user inputs so that I can later keep track of them. 

In particular, I want to time multiple events by getting each of their start times and later comparing them to their respective stop times--I don't want to user timers.  In order to do this, I need to give each start time a name associated with the name of the event.  If there is an "event A" it's start time could be eventA_start, whereas event B could be called eventB_start, i.e.:

eventA_start = datetime.datetime.now() 

The problem is, I don't know the "A" part...the user could choose eventPotato or eventDinosaur.  I won't know in advance.  I want the name chosen/inputted by the user to be attached to the name for the time that event started.

I have read that the way to do this properly in Python is with use of dictionaries, but I haven't found a reference online that shows how to do it is in a complete way.  Any help is appreciated.

_________________________________________________________________
Share life as it happens with the new Windows Live.
http://www.windowslive.com/share.html?ocid=TXT_TAGHM_Wave2_sharelife_122007
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071212/a0dd2269/attachment.htm 

From michael.langford at gmail.com  Thu Dec 13 05:48:52 2007
From: michael.langford at gmail.com (Michael Langford)
Date: Wed, 12 Dec 2007 23:48:52 -0500
Subject: [Tutor] python and interface duplex checks
In-Reply-To: <15b2d9090712122013r7f40509dp5a8eb8d0746a0cbe@mail.gmail.com>
References: <15b2d9090712121848g7f04f871o844450ccd3cb17d@mail.gmail.com>
	<82b4f5810712122001n4be703e3vc1cb5088fdb621e8@mail.gmail.com>
	<15b2d9090712122013r7f40509dp5a8eb8d0746a0cbe@mail.gmail.com>
Message-ID: <82b4f5810712122048t15d387b7occ539e04d9559174@mail.gmail.com>

Python can easily run ifconfig -a itself and then move through its
output. You can either parse out each string and then redisplay them.

If you *really* want to rewrite ifconfig, you need to call ioctl
(http://docs.python.org/lib/module-fcntl.html) and you need passing in
ioctl codes such as ones that start with SIOCGIF, such as SIOCGIFCONF
and SIOCGIFFLAGS and use the python struct module to then go through
the flags subfield. I've never looked for duplex, but I'm imagining
that it's there somewhere. You'll possibly need to parse some /proc
files as well.

This all can be done with python. Or you can just parse the ifconfig output.

          --Michael

On 12/12/07, Robert Recchia <robrecc at gmail.com> wrote:
>
>
> On Dec 12, 2007 11:01 PM, Michael Langford <mlangford.cs03 at gtalumni.org>
> wrote:
> > Most easily: If your card supports ethtool, you can just open the
> > ethtool startup config file to check there whether or not you set it
> > to duplex in the configuration (see if you have an ETHTOOL_OPTS env
> > variable).
> >
> > If you're not sure if your card can handle duplex (or you're not sure
> > the config file accurately shows what your card is set to), then you
> > can (more complicatedly) run ethtool with
> > popen(
> http://docs.python.org/lib/os-newstreams.html#os-newstreams)
> and
> > look for the status by parsing the duplex line.
> >
> > If you're not yet using ethtool, you should if you can. If you can't
> > reply back to the list and I'll delve into the older mii-tools to tell
> > you which one to hack on.
>
>
> Well what i would really like to do use python to basically display the
> interfaces ( like ifconfig -a ) and check if there is any value greater than
> 0 in either the RX error or TX errors part like below.
>
>  RX packets:588464 errors:0 dropped:0 overruns:0 frame:0
>   TX packets:714940 errors:0 dropped:0 overruns:0 carrier:0
> >
> >
> >          --Michael
> >
> >
> >
> >
> > On Dec 12, 2007 9:48 PM, Robert Recchia <robrecc at gmail.com> wrote:
> > > I was wondering can python can be used to check the duplex settings of a
> > > network card on a Linux os.
> > >
> > > --
> > > Robert Recchia
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
> >
> >
> > --
> > Michael Langford
> > Phone: 404-386-0495
> > Consulting: http://www.RowdyLabs.com
> >
>
>
>
> --
> Robert Recchia


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From earlylightpublishing at yahoo.com  Thu Dec 13 07:38:18 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Wed, 12 Dec 2007 22:38:18 -0800 (PST)
Subject: [Tutor] Python Versions
Message-ID: <618158.29422.qm@web45113.mail.sp1.yahoo.com>

Actually the first thing I noticed is the author would say something like "you can run the program by pressing F5 or selecting "run program" from the "run" menu.  Neither of those things work from the shell.  Saving programs also didn't work well for me when I put them in the shell.  Do people really write whole applications just using the shell?  
   
   
  "earlylight publishing" <earlylightpublishing at yahoo.com> wrote

>I have the latest python version too when I first started "A Byte of 
>Python"
> my code wouldn't work either.  My problem was that I was programming
> in the shell (the screen with the three '>>>' on it).  I found when 
> I wrote
> the examples in a new window (cntrl+N) they all worked as 
> advertized.

Unless you are doing some strange GUI type things it should work at
the >>> prompt too. (Sometimes you need an extra line - that could
fox beginners I suspect, if his examples contain multiple statements)

> He never mentions that you need to use an 'editing window'
> (I think it's called).  I just stumbled across the fact.

You shouldn't need to use an editing window, but the >>> prompt
does execute each line 9or block) in turn thus:

x=0
for n in range(5):
    x = n+x
print x

looks like this in IDLE:

>>> x=0
>>> for n in range(5):
    x = n+x
                                            <--Extra line here!
>>> print x
10
>>>

Is that the kind of thing you are seeing?




       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071212/d8a2fb3a/attachment.htm 

From globophobe at gmail.com  Thu Dec 13 08:00:44 2007
From: globophobe at gmail.com (Luis N)
Date: Thu, 13 Dec 2007 16:00:44 +0900
Subject: [Tutor] Python Versions
In-Reply-To: <618158.29422.qm@web45113.mail.sp1.yahoo.com>
References: <618158.29422.qm@web45113.mail.sp1.yahoo.com>
Message-ID: <c6e072940712122300q7d5b2bbdy5fd7264b3f4d1bca@mail.gmail.com>

On Dec 13, 2007 3:38 PM, earlylight publishing
<earlylightpublishing at yahoo.com> wrote:
> Do people really write whole applications just using the shell?
>
The shell isn't intended for writing whole applications. However, it's
invaluable for testing. For writing whole applications I'd recommend
The One True Editor with the external python-mode.

I use Aquamacs on a Macintosh. If you are on windows than consider Gnu Emacs.

From earlylightpublishing at yahoo.com  Thu Dec 13 08:13:06 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Wed, 12 Dec 2007 23:13:06 -0800 (PST)
Subject: [Tutor] Python Versions
Message-ID: <571202.19726.qm@web45101.mail.sp1.yahoo.com>

I'm a "she" not a "he".  :-)  But actually I don't believe I was a member of this group when I was working with the book "A Byte Of Python"  I don't believe I ever described a problem with raw_input here.  That concept seems pretty clear to me but as you say the OP hasn't described a specific problem.  As I said before, it was the fact that the author was describing features that I was not seeing in the shell that prompted me to try to figure out the "new window" feature.    As soon as I solved the shell problem I had no further difficulties understanding the concepts in the book.  I just thought I'd share what worked for me.  :-)
   
  The OP has not specified what his problems specifically are, but
 "earlylight 
publishing" described his problem before, and he was not understanding
 why 
the >>> prompt was expecting immediate keyboard input when he typed in 
raw_input(). So a noob cannot figure out why it is advantageous to have
 a 
raw_input function that immediately asks for input. He thinks, "why
 can't I 
put the input in directly?" That is why putting a program into an edit 
window is very advantageous.

I believe it is very likely that raw_input() is the culprit of
 confusion 
here. 


       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071212/57f64e38/attachment.htm 

From mlangford.cs03 at gtalumni.org  Thu Dec 13 08:14:45 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Thu, 13 Dec 2007 02:14:45 -0500
Subject: [Tutor] Python Versions
In-Reply-To: <618158.29422.qm@web45113.mail.sp1.yahoo.com>
References: <618158.29422.qm@web45113.mail.sp1.yahoo.com>
Message-ID: <82b4f5810712122314s2844094byc9f046ed84ba9b1c@mail.gmail.com>

There are 3 big schools of "how do you program" as far as what tools
you have open where.

IDE Geeks: "the author" you are reading about is one if them. This
means you run eclipse, idle, visual studio, kdevelop, etc, and you
debug and run out of that as well if you can. This is what most
primarily Microsoft platform developers do. These people look at
Editor and Shell geeks as if they are stuck in the 70's, even if the
developers in question they're looking at weren't alive then, or were
at least still messing their britches when Regan was inaugurated as
the POTUS.

Editor Geeks: These are the guys who make Vim or Emacs do everything
an IDE can do. They run their programs, debug their program, edit
their programs, probably check-in their programs and throw templates
down in the middle of their programs, all without leaving their
favorite editor. Sometimes they'll have an extra shell or two open to
look at another file, but the true hardcore editor geek uses buffers,
and can tell you why they do so for a good hour.

Shell Geeks: These guys have 3-10 shell windows open at a time. While
this is a bit of a continuum with the Editor geeks, these guys tend to
learn unix text processing tools to a almost magic degree. They can't
remember enough key bindings to be an editor geek, and they cringe at
all the mousing and hidden stuff going on in an IDE. These people can
write webservers with netcat and xargs if allowed to do so (they
should not *ever* be allowed to do so).

***

Usually which camp you're in is a historical oddity of where you've
done most of your programming, or at least, where you got good at it.
They IDE people have one thing going for them, that being mousing is
usually a little faster than remembering key sequences, although the
people remembering key sequences perceive themselves taking less time.
A lot of IDE people never really sink their teeth into the huge set of
immensely powerful unix tools out there (which work on windows too via
Cygwin and MinGW), and IDE editors are usually less powerful than a
vim or emacs (which usually operate on a block and word level rather
than a character level IDE editors usually function on).

Me personally, I'm a Shell Geek who's picking up more vim every year
(And bought the excellent VimEmu suite to get Vim keybindings in
Visual Studio and Outlook and Word). I have designed and implemented
huge projects without an IDE.  Then again, I use IDE's when people on
the project do and need to easily be able to work with me.

As far as python goes, it doesn't matter as long as you don't use tabs
:o). All of the above techniques can do that, so its all hunky dory.
Try each though, they'll make you learn something you didn't know, at
least how to talk to the other types of Geek.

           --Michael


On 12/13/07, earlylight publishing <earlylightpublishing at yahoo.com> wrote:
> Actually the first thing I noticed is the author would say something like
> "you can run the program by pressing F5 or selecting "run program" from the
> "run" menu.  Neither of those things work from the shell.  Saving programs
> also didn't work well for me when I put them in the shell.  Do people really
> write whole applications just using the shell?
>
>
>
> "earlylight publishing" <earlylightpublishing at yahoo.com> wrote
>
> >I have the latest python version too when I first started "A Byte of
> >Python"
> > my code wouldn't work either.  My problem was that I was programming
> > in the shell (the screen with the three '>>>' on it).  I found when
> > I wrote
> > the examples in a new window (cntrl+N) they all worked as
> > advertized.
>
> Unless you are doing some strange GUI type things it should work at
> the >>> prompt too. (Sometimes you need an extra line - that could
> fox beginners I suspect, if his examples contain multiple statements)
>
> > He never mentions that you need to use an 'editing window'
> > (I think it's called).  I just stumbled across the fact.
>
> You shouldn't need to use an editing window, but the >>> prompt
> does execute each line 9or block) in turn thus:
>
> x=0
> for n in range(5):
>     x = n+x
> print x
>
> looks like this in IDLE:
>
> >>> x=0
> >>> for n in range(5):
>     x = n+x
>                                             <--Extra line
> here!
> >>> print x
> 10
> >>>
>
> Is that the kind of thing you are seeing?
>
>
>
>
>  ________________________________
> Never miss a thing. Make Yahoo your homepage.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From alan.gauld at btinternet.com  Thu Dec 13 08:38:31 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 13 Dec 2007 07:38:31 -0000
Subject: [Tutor] Python Versions
References: <618158.29422.qm@web45113.mail.sp1.yahoo.com>
Message-ID: <fjqnho$tf0$1@ger.gmane.org>

"earlylight publishing" <earlylightpublishing at yahoo.com> wrote

> Actually the first thing I noticed is the author would say something
> like "you can run the program by pressing F5

Ah! Yes that would cause problems.
He obviously does intend you to use an Edit window rather than a
shell in that case. A great pity because every Pythonista should
learn how to use the shell,its one of Pythons most powerful tools.

> Do people really write whole applications just using the shell?

Only very occasionally, if its a short application that will only
be used once. For example I recently wrote a program to do
some bulk changes to my photo collection(renaming, moving,
creating new folders etc) and just typed it into the shell.

But OTOH it would be very unusual for me to write any signficant
sized application without using the shell to help me assemble
the application - trying out code snippets, using help(), testing and
debugging modules etc. Its very much an intrinsic part of my
development methodology with Python and I miss it greatly when
I have to revert to other languages.

-- 
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 Dec 13 08:53:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 13 Dec 2007 07:53:36 -0000
Subject: [Tutor] user-given variable names for objects
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>
Message-ID: <fjqoe1$vhk$1@ger.gmane.org>


"Che M" <pine508 at hotmail.com> wrote 

> I'm sure this is a classic beginner's topic, 

Indeed it is, it comes up about once a month or more!

> I want to assign names to objects based on what a 
> user inputs so that I can later keep track of them. 

This is almost never what you want to do, for precisely 
the reason that you can't keep trackl of them when you 
stop using the >>> prompt. Insteaed you should probably 
use a dictionary to collect these user based objects 
based on their names.

There is a section  on this in the OOP topic in my tutorial

> ...In order to do this, I need to give each start time 
> a name associated with the name of the event.  
> If there is an "event A" it's start time could be 
> eventA_start, whereas event B could be called eventB_start

So create a dictionary called events and access them using

events['A']
events['B']

etc.

> The problem is, I don't know the "A" part... the user could 
> choose eventPotato or eventDinosaur.  I won't know in advance.  

Which is why you can't write code to use variables whose 
names you don't know when writing the code. That's why putting 
them in a dictionary is a better solution. You just get the name 
as a string and use it as a key in the dictionary. Just watch out 
for duplicate names.

> I have read that the way to do this properly in Python is with 
> use of dictionaries, but I haven't found a reference online that 
> shows how to do it is in a complete way.  Any help is appreciated.

Check the bank account example in my tutorial, under the 
section heading "collections of objects".

HTH,

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



From rabidpoobear at gmail.com  Thu Dec 13 08:58:10 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 13 Dec 2007 01:58:10 -0600
Subject: [Tutor] user-given variable names for objects
In-Reply-To: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>
Message-ID: <4760E612.1030109@gmail.com>

Che M wrote:
> I'm sure this is a classic beginner's topic, and I've read a bit about 
> it online already, but I'd like to ask about it here as well.  I want 
> to assign names to objects based on what a user inputs so that I can 
> later keep track of them.
Yes, this comes up quite a bit.
> In particular, I want to time multiple events by getting each of their 
> start times and later comparing them to their respective stop times--I 
> don't want to user timers.  In order to do this, I need to give each 
> start time a name associated with the name of the event.  If there is 
> an "event A" it's start time could be eventA_start, whereas event B 
> could be called eventB_start, i.e.:
>
> eventA_start = datetime.datetime.now()
>
> The problem is, I don't know the "A" part...the user could choose 
> eventPotato or eventDinosaur.  I won't know in advance.  I want the 
> name chosen/inputted by the user to be attached to the name for the 
> time that event started.
>
> I have read that the way to do this properly in Python is with use of 
> dictionaries, but I haven't found a reference online that shows how to 
> do it is in a complete way.  Any help is appreciated.
There are a multitude of different ways this can be accomplished with 
dictionaries.  It really depends on what structure you want your data to 
follow.
By way of example, suppose we want to store the start time and length of 
timers from the user.
We could have an input loop as such:
import time
eventData = {}
while True:
    name, duration = raw_input("Name your event (done to exit): "), 
int(raw_input("How long should it last? "))
    if name.strip().lower() == "done":
        break

now we want to add the user's data to our dictionary so we can keep 
track of events.

    eventData[name] = time.time() + duration

note that I used the time.time() function to get the current time and 
just added duration to it,
so every event now stores the ending time of the event (when we want to 
trigger it, say)

given this time, we can generate a list of all events that have happened 
in the past,
using list comprehensions or by other methods:
[a for a in eventData.keys() if eventData[a] < time.time()]

then we can simply print out all events that have already occurred at 
any point in time:
while True:
    finished = [a for a in eventData.keys() if eventData[a] < time.time()]
    print "The following events have occurred: "
    for name in finished:
        print name
    time.sleep(1)
    if len(finished) == len(eventData.keys()):
        break

Of course this is by no means an ideal solution, it merely serves as an 
example.

Does this make sense, and do you understand why it's better to use 
dictionaries than to use variables
to achieve this?
[note - no code was tested, not guaranteed to work :)]
-Luke

From rabidpoobear at gmail.com  Thu Dec 13 09:04:55 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 13 Dec 2007 02:04:55 -0600
Subject: [Tutor] Python Versions
In-Reply-To: <001101c95cab$c4fd56f0$91fce004@jslaptop>
References: <96230.68789.qm@web45114.mail.sp1.yahoo.com>	<fjpluc$9po$1@ger.gmane.org>
	<001101c95cab$c4fd56f0$91fce004@jslaptop>
Message-ID: <4760E7A7.2010401@gmail.com>

Tiger12506 wrote:
> The OP has not specified what his problems specifically are, but "earlylight 
> publishing" described his problem before, and he was not understanding why 
> the >>> prompt was expecting immediate keyboard input when he typed in 
> raw_input(). So a noob cannot figure out why it is advantageous to have a 
> raw_input function that immediately asks for input. He thinks, "why can't I 
> put the input in directly?" That is why putting a program into an edit 
> window is very advantageous.
>
> I believe it is very likely that raw_input() is the culprit of confusion 
> here. 

Hey Tiger,
your system clock is set incorrectly and your e-mail was flagged as 
being sent 12/12/2008, causing it to appear after an e-mail sent as a 
reply - confusing.
Please remedy this situation ;P
-Luke

From pine508 at hotmail.com  Thu Dec 13 09:57:57 2007
From: pine508 at hotmail.com (Che M)
Date: Thu, 13 Dec 2007 03:57:57 -0500
Subject: [Tutor] user-given variable names for objects
In-Reply-To: <fjqoe1$vhk$1@ger.gmane.org>
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>
	<fjqoe1$vhk$1@ger.gmane.org>
Message-ID: <BAY105-W3240EEA3B114C96496A601E0660@phx.gbl>




> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Thu, 13 Dec 2007 07:53:36 +0000
> Subject: Re: [Tutor] user-given variable names for objects
> 
> 
> "Che M" <pine508 at hotmail.com> wrote 
> 
> > I'm sure this is a classic beginner's topic, 
> 
> Indeed it is, it comes up about once a month or more!
> 
> > I want to assign names to objects based on what a 
> > user inputs so that I can later keep track of them. 
> 
> This is almost never what you want to do, for precisely 
> the reason that you can't keep trackl of them when you 
> stop using the >>> prompt. Insteaed you should probably 
> use a dictionary to collect these user based objects 
> based on their names.
> 
> There is a section  on this in the OOP topic in my tutorial
> 
> > ...In order to do this, I need to give each start time 
> > a name associated with the name of the event.  
> > If there is an "event A" it's start time could be 
> > eventA_start, whereas event B could be called eventB_start
> 
> So create a dictionary called events and access them using
> 
> events['A']
> events['B']
> 
> etc.
> 
> > The problem is, I don't know the "A" part... the user could 
> > choose eventPotato or eventDinosaur.  I won't know in advance.  
> 
> Which is why you can't write code to use variables whose 
> names you don't know when writing the code. That's why putting 
> them in a dictionary is a better solution. You just get the name 
> as a string and use it as a key in the dictionary. Just watch out 
> for duplicate names.
> 
> > I have read that the way to do this properly in Python is with 
> > use of dictionaries, but I haven't found a reference online that 
> > shows how to do it is in a complete way.  Any help is appreciated.
> 
> Check the bank account example in my tutorial, under the 
> section heading "collections of objects".
> 
> HTH,
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 



Thank you, indeed it did help.  For some reason when I was reading
about dictionaries online I got the unfortunate thought that the value
couldn't be a function--glad I was highly incorrect on that one.  I had
also been shy of understanding how to use dictionaries for some reason (fear of hyphens and curly braces?),
but your section and a little trying it out in IDLE makes it seem
do-able.  I'll give it more of a go later and see if I can get things
moving ahead. 


_________________________________________________________________
The best games are on Xbox 360.  Click here for a special offer on an Xbox 360 Console.
http://www.xbox.com/en-US/hardware/wheretobuy/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071213/20460237/attachment-0001.htm 

From pine508 at hotmail.com  Thu Dec 13 10:03:59 2007
From: pine508 at hotmail.com (Che M)
Date: Thu, 13 Dec 2007 04:03:59 -0500
Subject: [Tutor] user-given variable names for objects
In-Reply-To: <4760E612.1030109@gmail.com>
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>
	<4760E612.1030109@gmail.com>
Message-ID: <BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>




> Date: Thu, 13 Dec 2007 01:58:10 -0600
> From: rabidpoobear at gmail.com
> To: pine508 at hotmail.com
> CC: tutor at python.org
> Subject: Re: [Tutor] user-given variable names for objects
> 
> Che M wrote:
> > I'm sure this is a classic beginner's topic, and I've read a bit about 
> > it online already, but I'd like to ask about it here as well.  I want 
> > to assign names to objects based on what a user inputs so that I can 
> > later keep track of them.
> Yes, this comes up quite a bit.
> > In particular, I want to time multiple events by getting each of their 
> > start times and later comparing them to their respective stop times--I 
> > don't want to user timers.  In order to do this, I need to give each 
> > start time a name associated with the name of the event.  If there is 
> > an "event A" it's start time could be eventA_start, whereas event B 
> > could be called eventB_start, i.e.:
> >
> > eventA_start = datetime.datetime.now()
> >
> > The problem is, I don't know the "A" part...the user could choose 
> > eventPotato or eventDinosaur.  I won't know in advance.  I want the 
> > name chosen/inputted by the user to be attached to the name for the 
> > time that event started.
> >
> > I have read that the way to do this properly in Python is with use of 
> > dictionaries, but I haven't found a reference online that shows how to 
> > do it is in a complete way.  Any help is appreciated.
> There are a multitude of different ways this can be accomplished with 
> dictionaries.  It really depends on what structure you want your data to 
> follow.
> By way of example, suppose we want to store the start time and length of 
> timers from the user.
> We could have an input loop as such:
> import time
> eventData = {}
> while True:
>     name, duration = raw_input("Name your event (done to exit): "), 
> int(raw_input("How long should it last? "))
>     if name.strip().lower() == "done":
>         break
> 
> now we want to add the user's data to our dictionary so we can keep 
> track of events.
> 
>     eventData[name] = time.time() + duration
> 
> note that I used the time.time() function to get the current time and 
> just added duration to it,
> so every event now stores the ending time of the event (when we want to 
> trigger it, say)
> 
> given this time, we can generate a list of all events that have happened 
> in the past,
> using list comprehensions or by other methods:
> [a for a in eventData.keys() if eventData[a] < time.time()]
> 
> then we can simply print out all events that have already occurred at 
> any point in time:
> while True:
>     finished = [a for a in eventData.keys() if eventData[a] < time.time()]
>     print "The following events have occurred: "
>     for name in finished:
>         print name
>     time.sleep(1)
>     if len(finished) == len(eventData.keys()):
>         break
> 
> Of course this is by no means an ideal solution, it merely serves as an 
> example.
> 
> Does this make sense, and do you understand why it's better to use 
> dictionaries than to use variables
> to achieve this?
> [note - no code was tested, not guaranteed to work :)]
> -Luke

Thanks, yes, I am getting clearer by the minute in my understanding of dictionaries and why they are better than variables for these cases.  Although I was not familiar with what you can do with a list such as you did here:
> [a for a in eventData.keys() if eventData[a] < time.time()]
I think it basically makes sense.  I guess .keys() is a built-in method for dictionaries to return a list of all their values, then?  By the way, what was the purpose of the line with
time.sleep(1)
But otherwise, it seems a good start.  Thank you, and I'll try more of it tomorrow.


_________________________________________________________________
Don't get caught with egg on your face. Play Chicktionary!
http://club.live.com/chicktionary.aspx?icid=chick_wlhmtextlink1_dec
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071213/a73d5681/attachment.htm 

From tiagosaboga at terra.com.br  Thu Dec 13 12:03:40 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Thu, 13 Dec 2007 09:03:40 -0200
Subject: [Tutor] thread and os.pipe
In-Reply-To: <fjfcn1$bh5$1@ger.gmane.org>
References: <fje0l8$l1s$1@ger.gmane.org> <20071208220319.GA20392@localdomain>
	<fjfcn1$bh5$1@ger.gmane.org>
Message-ID: <20071213110340.GA4812@localdomain>

On Sun, Dec 09, 2007 at 12:25:59AM -0000, Alan Gauld wrote:
> > updated to show the output from the commands. What I want to do
> > is make the doit() method of the Converter class return a pipe,
> > through which it will then send the output of the programs.
> 
> I'm still not convinced that a pipe is the best solution here.
> You could simply register the UI View with the converter (in usual MVC
> design pattern) and get the converter to either send updates to the
> UI (or notify the UI to request updates) as needed. That way you
> only need a regular Python method in the Converter to deliver the
> data and another in the UI code to respond to the notification.
> No pipes or queues required.

Thanks Alan, but finally I got it working without pipes, but with a
queue. I was afraid of getting into a new world, but it turned out to
be easier than I thought. OTOH, I am really not comfortable with MVC;
I am using some MVC patterns as I don't have the choice, but I still
can't really understand the concepts. But it's another point...

Thanks again,

Tiago.

From tiagosaboga at terra.com.br  Thu Dec 13 12:19:18 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Thu, 13 Dec 2007 09:19:18 -0200
Subject: [Tutor] ipython / readline problem
Message-ID: <20071213111918.GC4812@localdomain>

Hi,

I am facing what seems like a bug, and the docs are not enough to tell
me where the bug lies. In ipython, I can't type a multiline unicode
string. The bug is reported here [1], and the output is like that
(except that the commented out lines are modifications I have done):

===================================
In [1]: a = '''?
   ...: '''
---------------------------------------------------------------------------
<type 'exceptions.UnicodeEncodeError'>    Traceback (most recent call last)

/var/lib/python-support/python2.5/IPython/iplib.py in raw_input(self, prompt, continue_prompt)
   2041                         self.readline.remove_history_item(histlen-1)
   2042                         # newhist = newhist.encode('ascii', 'replace')
-> 2043                         self.readline.replace_history_item(histlen-2,newhist)
   2044                         #self.input_hist_raw[-1] = newhist
   2045                     except AttributeError:

<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xe7' in position 7: ordinal not in range(128)

===================================

So I went to the ipython source code to see what was wrong and finally
I discovered that one can't pass unicode strings to readline. To be
clearer, the behaviour above is found only in ipython, but the errors
below can be reproduced also in the python console:

===================================

In [6]: readline.add_history('a??o')

In [7]: readline.get_current_history_length()
Out[7]: 1008

In [8]: readline.replace_history_item(1008, 'a??o')

In [9]: readline.replace_history_item(1008, u'a??o')
---------------------------------------------------------------------------
<type 'exceptions.UnicodeEncodeError'>    Traceback (most recent call
last)

/home/tiago/<ipython console> in <module>()

<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode
characters in position 1-2: ordinal not in range(128)

In [10]: readline.add_history(u'ca?a')
---------------------------------------------------------------------------
<type 'exceptions.UnicodeEncodeError'>    Traceback (most recent call
last)

/home/tiago/<ipython console> in <module>()

<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode
character u'\xe7' in position 2: ordinal not in range(128)

=======================================

What's happening? Why do the readline methods accept a multibyte
string ('a??o') but not a unicode (u'a??o')?

Thanks,

Tiago.

[1] - http://projects.scipy.org/ipython/ipython/ticket/201

From kent37 at tds.net  Thu Dec 13 13:41:08 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 13 Dec 2007 07:41:08 -0500
Subject: [Tutor] ipython / readline problem
In-Reply-To: <20071213111918.GC4812@localdomain>
References: <20071213111918.GC4812@localdomain>
Message-ID: <47612864.5050206@tds.net>

Tiago Saboga wrote:
> <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode
> character u'\xe7' in position 2: ordinal not in range(128)
> 
> =======================================
> 
> What's happening? Why do the readline methods accept a multibyte
> string ('a??o') but not a unicode (u'a??o')?

I don't know what is happening with readline but this error is usually 
the result of converting a Unicode string to a plain string without 
specifying encoding, either explicitly by calling str() or implicitly 
such as in a print statement:

In [3]: u='a\303\247\303\243o'.decode('utf-8')
In [4]: print u
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode 
characters in position 1-2: ordinal not in range(128)

In [5]: str(u)
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode 
characters in position 1-2: ordinal not in range(128)

Kent

From jfabiani at yolo.com  Thu Dec 13 18:54:52 2007
From: jfabiani at yolo.com (johnf)
Date: Thu, 13 Dec 2007 09:54:52 -0800
Subject: [Tutor] what is the difference
Message-ID: <200712130954.52778.jfabiani@yolo.com>

if self._inFlush:
	return
self._inFlush = True
....

AND

if not self._inFlush:
	...
	self._inFlush = True
else:
	return

I can not see the difference but the second one acts differently in my code.
-- 
John Fabiani

From goldwamh at slu.edu  Thu Dec 13 19:39:27 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Thu, 13 Dec 2007 12:39:27 -0600
Subject: [Tutor]  what is the difference
In-Reply-To: <200712130954.52778.jfabiani@yolo.com>
References: <200712130954.52778.jfabiani@yolo.com>
Message-ID: <18273.31839.631737.852729@euclid.slu.edu>


Hi John,

It depends upon whether the "..." code fragment is affected in any way
by the value of self._inFlush.  The first code sample you offer should
be identical to the following.

    if not self._inFlush:
    	self._inFlush = True    # reset this before the ...
    	...
    else:
    	return

With regard,
Michael

On Thursday December 13, 2007, johnf wrote: 

>    if self._inFlush:
>    	return
>    self._inFlush = True
>    ....
>    
>    AND
>    
>    if not self._inFlush:
>    	...
>    	self._inFlush = True
>    else:
>    	return
>    
>    I can not see the difference but the second one acts differently in my code.
>    -- 
>    John Fabiani
>    _______________________________________________
>    Tutor maillist  -  Tutor at python.org
>    http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Thu Dec 13 19:36:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 13 Dec 2007 18:36:49 -0000
Subject: [Tutor] user-given variable names for objects
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl><4760E612.1030109@gmail.com>
	<BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>
Message-ID: <fjru43$54g$1@ger.gmane.org>


"Che M" <pine508 at hotmail.com> wrote

>  Although I was not familiar with what you can do with a list such 
> as you did here:
> [a for a in eventData.keys() if eventData[a] < time.time()]

This is known as a list comprehension (and is described in the 
Functional
Programming topic of my tutorial - obligatory plug :-)

> I guess .keys() is a built-in method for dictionaries to return a
> list of all their values, then?

To be accurate it returns a list of the keys, the values are the 
things you get when you access the dictionary using a key:

value = dictionary[key]

So you can do things like

for key in dictionary.keys():
    print dictionary[key]

> By the way, what was the purpose of the line with
> time.sleep(1)

It pauses for 1 second. But i'm not sure why he wanted a pause! :-)

Alan G. 



From alan.gauld at btinternet.com  Thu Dec 13 19:52:22 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 13 Dec 2007 18:52:22 -0000
Subject: [Tutor] what is the difference
References: <200712130954.52778.jfabiani@yolo.com>
Message-ID: <fjrv17$8ho$1@ger.gmane.org>


"johnf" <jfabiani at yolo.com> wrote

> if self._inFlush:
>       return
> self._inFlush = True
> ....
>
> AND
>
> if not self._inFlush:
>      ...
>     self._inFlush = True
> else:
>     return
>
> I can not see the difference but the second one acts differently in 
> my code.

The first has no else clause so the second assignment always happens.

Alan G. 



From tiagosaboga at terra.com.br  Thu Dec 13 20:05:55 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Thu, 13 Dec 2007 17:05:55 -0200
Subject: [Tutor] ipython / readline problem
In-Reply-To: <47612864.5050206@tds.net>
References: <20071213111918.GC4812@localdomain> <47612864.5050206@tds.net>
Message-ID: <20071213190554.GF4812@localdomain>

On Thu, Dec 13, 2007 at 07:41:08AM -0500, Kent Johnson wrote:
> Tiago Saboga wrote:
>> <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode
>> character u'\xe7' in position 2: ordinal not in range(128)
>>
>> =======================================
>>
>> What's happening? Why do the readline methods accept a multibyte
>> string ('a??o') but not a unicode (u'a??o')?
>
> I don't know what is happening with readline but this error is usually the 
> result of converting a Unicode string to a plain string without specifying 
> encoding, either explicitly by calling str() or implicitly such as in a 
> print statement:

I already knew that, but it helped somehow ;) 

Apparently the problem is that ipython converts the input to unicode,
while the readline module wants a string object. With single line
input, ipython doesn't interfere with readline, but for multiline
input, it updates readline's history, but it tries to to that with the
unicode object. I've sent a patch to the ipython bug to reencode the
string to sys.stdin.encoding before submitting it to readline.

But in general, in the python libraries, I thought it would be safe to
assume that one can equally send a string or a unicode object, and
that otherwise there would be a warning in the docs. Is this
assumption plain wrong, is this info really missing in the docs, or
it's just me that have missed it?

Thanks,

Tiago Saboga.

From keridee at jayco.net  Thu Dec 13 21:52:44 2007
From: keridee at jayco.net (Tiger12506)
Date: Thu, 13 Dec 2007 20:52:44 -0000
Subject: [Tutor] what is the difference
References: <200712130954.52778.jfabiani@yolo.com> <fjrv17$8ho$1@ger.gmane.org>
Message-ID: <001201c95d64$c0d33630$a1fce004@jslaptop>

> "johnf" <jfabiani at yolo.com> wrote
>
>> if self._inFlush:
>>       return
>> self._inFlush = True
>> ....
>>
>> AND
>>
>> if not self._inFlush:
>>      ...
>>     self._inFlush = True
>> else:
>>     return
>>
>> I can not see the difference but the second one acts differently in
>> my code.
>
> The first has no else clause so the second assignment always happens.
>
> Alan G.

No it doesn't. The return statement does not allow the second assignment to 
occur in the first example. The second assignment only occurs if NOT 
(self._inFlush==True), as in the second example.


From keridee at jayco.net  Thu Dec 13 22:13:32 2007
From: keridee at jayco.net (Tiger12506)
Date: Thu, 13 Dec 2007 21:13:32 -0000
Subject: [Tutor] user-given variable names for objects
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl><4760E612.1030109@gmail.com><BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>
	<fjru43$54g$1@ger.gmane.org>
Message-ID: <008201c95d67$a8eed990$a1fce004@jslaptop>

I may sound like a know-it-all, but dictionaries *are* iterators.

[a for a in eventData if eventData[a] < time.time()]

This is more efficient. The keys method creates a list in memory first and 
then it iterates over it.
Unnecessary.

>
> "Che M" <pine508 at hotmail.com> wrote
>
>>  Although I was not familiar with what you can do with a list such
>> as you did here:
>> [a for a in eventData.keys() if eventData[a] < time.time()]
>
> This is known as a list comprehension (and is described in the
> Functional
> Programming topic of my tutorial - obligatory plug :-)
>
>> I guess .keys() is a built-in method for dictionaries to return a
>> list of all their values, then?
>
> To be accurate it returns a list of the keys, the values are the
> things you get when you access the dictionary using a key:
>
> value = dictionary[key]
>
> So you can do things like
>
> for key in dictionary.keys():
>    print dictionary[key]
>
>> By the way, what was the purpose of the line with
>> time.sleep(1)
>
> It pauses for 1 second. But i'm not sure why he wanted a pause! :-)
>
> Alan G.
>


From kent37 at tds.net  Thu Dec 13 22:24:34 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 13 Dec 2007 16:24:34 -0500
Subject: [Tutor] user-given variable names for objects
In-Reply-To: <008201c95d67$a8eed990$a1fce004@jslaptop>
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl><4760E612.1030109@gmail.com><BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>	<fjru43$54g$1@ger.gmane.org>
	<008201c95d67$a8eed990$a1fce004@jslaptop>
Message-ID: <4761A312.9000808@tds.net>

Tiger12506 wrote:
> I may sound like a know-it-all, but dictionaries *are* iterators.

Mmm, to nit-pick a little, dictionaries are iterables, not iterators. 
They don't have a next() method.

> [a for a in eventData if eventData[a] < time.time()]
> 
> This is more efficient. The keys method creates a list in memory first and 
> then it iterates over it.

I've never tested it but I suspect that when you need keys and values, 
it is more efficient to use itervalues():

[ k for k, v in eventData.itervalues() if v < time.time() ]

and of course if you care about efficiency you should hoist the call to 
time.time() out of the loop!

Kent

From keridee at jayco.net  Thu Dec 13 22:31:45 2007
From: keridee at jayco.net (Tiger12506)
Date: Thu, 13 Dec 2007 16:31:45 -0500
Subject: [Tutor] Python Versions
References: <96230.68789.qm@web45114.mail.sp1.yahoo.com>	<fjpluc$9po$1@ger.gmane.org>
	<001101c95cab$c4fd56f0$91fce004@jslaptop>
	<4760E7A7.2010401@gmail.com>
Message-ID: <00de01c83dcf$e6b5d520$a1fce004@jslaptop>


> Hey Tiger,
> your system clock is set incorrectly and your e-mail was flagged as being 
> sent 12/12/2008, causing it to appear after an e-mail sent as a reply - 
> confusing.
> Please remedy this situation ;P
> -Luke

Whoops!! I have to mess with my clock occasionally to test the integrity of 
date specific scripts that I write. Sorry. It has been fixed. Thank you. 


From alan.gauld at btinternet.com  Thu Dec 13 23:37:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 13 Dec 2007 22:37:05 -0000
Subject: [Tutor] what is the difference
References: <200712130954.52778.jfabiani@yolo.com> <fjrv17$8ho$1@ger.gmane.org>
	<001201c95d64$c0d33630$a1fce004@jslaptop>
Message-ID: <fjsc6i$n9s$1@ger.gmane.org>


"Tiger12506" <keridee at jayco.net> wrote

>>> I can not see the difference but the second one acts differently 
>>> in
>>> my code.
>>
>> The first has no else clause so the second assignment always 
>> happens.
>>
>> Alan G.
>
> No it doesn't. The return statement does not allow the second 
> assignment to
> occur in the first example. The second assignment only occurs if NOT
> (self._inFlush==True), as in the second example.

Quite right, see my other reply to Terry...

mea culpa,

Alan G. 



From alan.gauld at btinternet.com  Thu Dec 13 23:40:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 13 Dec 2007 22:40:18 -0000
Subject: [Tutor] ipython / readline problem
References: <20071213111918.GC4812@localdomain> <47612864.5050206@tds.net>
	<20071213190554.GF4812@localdomain>
Message-ID: <fjscck$nr4$1@ger.gmane.org>


"Tiago Saboga" <tiagosaboga at terra.com.br> wrote
> But in general, in the python libraries, I thought it would be safe 
> to
> assume that one can equally send a string or a unicode object, and
> that otherwise there would be a warning in the docs. Is this
> assumption plain wrong, is this info really missing in the docs, or
> it's just me that have missed it?

In general I think you can, the readline stuff is an IPython feature I 
think.
But I don't really know since I don't have IPython to compare with and
don't use unicode hardly ever.

But I think Python itself is pretty safe with unicode v ascii in most 
cases.
I'm sure Kent will be able to comment further, he seems to have made
himself an expert in this area! (and I'm sure glad somebody has! :-)

Alan G. 



From alan.gauld at btinternet.com  Fri Dec 14 00:28:46 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Thu, 13 Dec 2007 23:28:46 +0000 (GMT)
Subject: [Tutor] Fw:  what is the difference
Message-ID: <109474.85199.qm@web86701.mail.ird.yahoo.com>


Terry Carroll wrote:
On Thu, 13 Dec 2007, Alan Gauld wrote:
>> > if self._inFlush:
>> >       return
>> > self._inFlush = True
>> > ....
>> >
>> > I can not see the difference but the second one acts differently
 in
 
>> > my code.
>> 
>> The first has no else clause so the second assignment always
 happens.
>
> Alan, are you teasing the newbies?

No just not reading closely enough. 
You are quite right, I've no idea why they would behave differently!

John, care to elaborate on what is different?

> Or am I just misreading this somehow?

Nope, I was.

Alan G.








From kent37 at tds.net  Fri Dec 14 00:36:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 13 Dec 2007 18:36:39 -0500
Subject: [Tutor] ipython / readline problem
In-Reply-To: <fjscck$nr4$1@ger.gmane.org>
References: <20071213111918.GC4812@localdomain>
	<47612864.5050206@tds.net>	<20071213190554.GF4812@localdomain>
	<fjscck$nr4$1@ger.gmane.org>
Message-ID: <4761C207.4090804@tds.net>

Alan Gauld wrote:
> But I think Python itself is pretty safe with unicode v ascii in most 
> cases.

I was actually holding my tongue on that one. My guess is it varies from 
  one module to the next depending on how well maintained they are, but 
I don't really know.

> I'm sure Kent will be able to comment further, he seems to have made
> himself an expert in this area! (and I'm sure glad somebody has! :-)

I'm pretty knowledgeable about character sets and conversion issues, not 
so much about how specific modules use unicode.

Kent

From rabidpoobear at gmail.com  Fri Dec 14 00:48:11 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 13 Dec 2007 17:48:11 -0600
Subject: [Tutor] user-given variable names for objects
In-Reply-To: <fjru43$54g$1@ger.gmane.org>
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>
	<4760E612.1030109@gmail.com>
	<BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>
	<fjru43$54g$1@ger.gmane.org>
Message-ID: <dfeb4470712131548i777f10dam9102c577a0a8173a@mail.gmail.com>

>
> > By the way, what was the purpose of the line with
> > time.sleep(1)
>
> It pauses for 1 second. But i'm not sure why he wanted a pause! :-)
>
Just because it would dump a bunch of stuff to the screen really quickly
that you couldn't read as soon as some events expired.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071213/a18afd70/attachment.htm 

From rabidpoobear at gmail.com  Fri Dec 14 00:50:17 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 13 Dec 2007 17:50:17 -0600
Subject: [Tutor] user-given variable names for objects
In-Reply-To: <008201c95d67$a8eed990$a1fce004@jslaptop>
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl>
	<4760E612.1030109@gmail.com>
	<BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>
	<fjru43$54g$1@ger.gmane.org> <008201c95d67$a8eed990$a1fce004@jslaptop>
Message-ID: <dfeb4470712131550l11adf26h21dc67cb7eb86da6@mail.gmail.com>

On Dec 13, 2008 3:12 PM, Tiger12506 <keridee at jayco.net> wrote:

> I may sound like a know-it-all, but dictionaries *are* iterators.

I'm used to that from you :P

>
> [a for a in eventData if eventData[a] < time.time()]
>
> This is more efficient. The keys method creates a list in memory first and
> then it iterates over it.

Thanks. I was fairly certain that was the case, but since I wasn't going to
test the code, I used the alternative.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071213/95c1de19/attachment.htm 

From globophobe at gmail.com  Fri Dec 14 03:08:11 2007
From: globophobe at gmail.com (Luis N)
Date: Fri, 14 Dec 2007 11:08:11 +0900
Subject: [Tutor] Introspect function or class' required arguments
Message-ID: <c6e072940712131808g3ad23a1dw570da5ed842646e1@mail.gmail.com>

Is there a way to introspect a function or class' required arguments,
particularly keyword arguments?

I can easily use a dictionary since it is my own function that I wish
to introspect. I haven't tested the below code yet, but e.g.

obj = getattr(self, 'obj')()
preprocessors = {'Card':[{'obj_attr':'mastery',
                          'call':mastery,
                          'args_dict':['front', 'back']}
                         ]
                 }
obj_preprocessors = preprocessors.get(obj.__name__, None)
if obj_preprocessors:
    for preprocessor in obj_preprocessors:
        function_name = preprocessor['call'].__name__
        args_dict = {}
        for arg in preprocessor['args_dict']:
            if self.query_dict.has_key(arg):
                args_dict[preprocessor[arg]] = self.query_dict.get(arg)
            else:
                self.error = 'Required argument %s omitted for
function %s' % (arg, function_name)
                break
        if not hasattr(self, error):
            try:
                setattr(obj, preprocessor['obj_attr'],
preprocessor['call'](args_dict))
            except:
                self.error = 'Preprocessor %s failed.' % function_name
        else:
            break

From jmorcombe at westnet.com.au  Fri Dec 14 02:43:48 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Fri, 14 Dec 2007 10:43:48 +0900
Subject: [Tutor] using quotes in IDLE
Message-ID: <000e01c83df2$c7e4cde0$6a00a8c0@ASC000E7B84CF9F>

A really dumb question...

When typing things into IDLE, how are quotes meant to work?

If I type"

employee.name = "Susan"

then IDLE ignores the last " and I get an error.

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071214/08cd377b/attachment-0001.htm 

From kent37 at tds.net  Fri Dec 14 04:08:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 13 Dec 2007 22:08:01 -0500
Subject: [Tutor] Introspect function or class' required arguments
In-Reply-To: <c6e072940712131808g3ad23a1dw570da5ed842646e1@mail.gmail.com>
References: <c6e072940712131808g3ad23a1dw570da5ed842646e1@mail.gmail.com>
Message-ID: <4761F391.3020100@tds.net>

Luis N wrote:
> Is there a way to introspect a function or class' required arguments,
> particularly keyword arguments?

See inspect.getargspec() and formatargspec().
Look at the source if you want details of where the info is stored.

> I can easily use a dictionary since it is my own function that I wish
> to introspect. I haven't tested the below code yet, but e.g.

I don't understand what you are trying to do here.

Kent

From andre_mueninghoff at fastmail.fm  Fri Dec 14 04:12:58 2007
From: andre_mueninghoff at fastmail.fm (Andre Mueninghoff)
Date: Thu, 13 Dec 2007 22:12:58 -0500
Subject: [Tutor] Tutor Digest, Vol 46, Issue 39
In-Reply-To: <mailman.10241.1197600017.13604.tutor@python.org>
References: <mailman.10241.1197600017.13604.tutor@python.org>
Message-ID: <1197601978.1932.1226517645@webmail.messagingengine.com>

unsubscribe

On Fri, 14 Dec 2007 03:40:17 +0100, tutor-request at python.org said:
> Send Tutor mailing list submissions to
> 	tutor at python.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> 	tutor-request at python.org
> 
> You can reach the person managing the list at
> 	tutor-owner at python.org
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>    1. Re: user-given variable names for objects (Kent Johnson)
>    2. Re: Python Versions (Tiger12506)
>    3. Re: what is the difference (Alan Gauld)
>    4. Re: ipython / readline problem (Alan Gauld)
>    5. Fw:  what is the difference (ALAN GAULD)
>    6. Re: ipython / readline problem (Kent Johnson)
>    7. Re: user-given variable names for objects (Luke Paireepinart)
>    8. Re: user-given variable names for objects (Luke Paireepinart)
>    9. Introspect function or class' required arguments (Luis N)
>   10. using quotes in IDLE (Jim Morcombe)
> 
> 
> ----------------------------------------------------------------------
> 
> Message: 1
> Date: Thu, 13 Dec 2007 16:24:34 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] user-given variable names for objects
> To: Tiger12506 <keridee at jayco.net>
> Cc: tutor at python.org
> Message-ID: <4761A312.9000808 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Tiger12506 wrote:
> > I may sound like a know-it-all, but dictionaries *are* iterators.
> 
> Mmm, to nit-pick a little, dictionaries are iterables, not iterators. 
> They don't have a next() method.
> 
> > [a for a in eventData if eventData[a] < time.time()]
> > 
> > This is more efficient. The keys method creates a list in memory first and 
> > then it iterates over it.
> 
> I've never tested it but I suspect that when you need keys and values, 
> it is more efficient to use itervalues():
> 
> [ k for k, v in eventData.itervalues() if v < time.time() ]
> 
> and of course if you care about efficiency you should hoist the call to 
> time.time() out of the loop!
> 
> Kent
> 
> 
> ------------------------------
> 
> Message: 2
> Date: Thu, 13 Dec 2007 16:31:45 -0500
> From: "Tiger12506" <keridee at jayco.net>
> Subject: Re: [Tutor] Python Versions
> To: <tutor at python.org>
> Message-ID: <00de01c83dcf$e6b5d520$a1fce004 at jslaptop>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=response
> 
> 
> > Hey Tiger,
> > your system clock is set incorrectly and your e-mail was flagged as being 
> > sent 12/12/2008, causing it to appear after an e-mail sent as a reply - 
> > confusing.
> > Please remedy this situation ;P
> > -Luke
> 
> Whoops!! I have to mess with my clock occasionally to test the integrity
> of 
> date specific scripts that I write. Sorry. It has been fixed. Thank you. 
> 
> 
> 
> ------------------------------
> 
> Message: 3
> Date: Thu, 13 Dec 2007 22:37:05 -0000
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] what is the difference
> To: tutor at python.org
> Message-ID: <fjsc6i$n9s$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
> 
> 
> "Tiger12506" <keridee at jayco.net> wrote
> 
> >>> I can not see the difference but the second one acts differently 
> >>> in
> >>> my code.
> >>
> >> The first has no else clause so the second assignment always 
> >> happens.
> >>
> >> Alan G.
> >
> > No it doesn't. The return statement does not allow the second 
> > assignment to
> > occur in the first example. The second assignment only occurs if NOT
> > (self._inFlush==True), as in the second example.
> 
> Quite right, see my other reply to Terry...
> 
> mea culpa,
> 
> Alan G. 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 4
> Date: Thu, 13 Dec 2007 22:40:18 -0000
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] ipython / readline problem
> To: tutor at python.org
> Message-ID: <fjscck$nr4$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
> 
> 
> "Tiago Saboga" <tiagosaboga at terra.com.br> wrote
> > But in general, in the python libraries, I thought it would be safe 
> > to
> > assume that one can equally send a string or a unicode object, and
> > that otherwise there would be a warning in the docs. Is this
> > assumption plain wrong, is this info really missing in the docs, or
> > it's just me that have missed it?
> 
> In general I think you can, the readline stuff is an IPython feature I 
> think.
> But I don't really know since I don't have IPython to compare with and
> don't use unicode hardly ever.
> 
> But I think Python itself is pretty safe with unicode v ascii in most 
> cases.
> I'm sure Kent will be able to comment further, he seems to have made
> himself an expert in this area! (and I'm sure glad somebody has! :-)
> 
> Alan G. 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 5
> Date: Thu, 13 Dec 2007 23:28:46 +0000 (GMT)
> From: ALAN GAULD <alan.gauld at btinternet.com>
> Subject: [Tutor] Fw:  what is the difference
> To: tutor at python.org
> Message-ID: <109474.85199.qm at web86701.mail.ird.yahoo.com>
> Content-Type: text/plain; charset=utf-8
> 
> 
> Terry Carroll wrote:
> On Thu, 13 Dec 2007, Alan Gauld wrote:
> >> > if self._inFlush:
> >> >       return
> >> > self._inFlush = True
> >> > ....
> >> >
> >> > I can not see the difference but the second one acts differently
>  in
>  
> >> > my code.
> >> 
> >> The first has no else clause so the second assignment always
>  happens.
> >
> > Alan, are you teasing the newbies?
> 
> No just not reading closely enough. 
> You are quite right, I've no idea why they would behave differently!
> 
> John, care to elaborate on what is different?
> 
> > Or am I just misreading this somehow?
> 
> Nope, I was.
> 
> Alan G.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 6
> Date: Thu, 13 Dec 2007 18:36:39 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] ipython / readline problem
> To: Alan Gauld <alan.gauld at btinternet.com>
> Cc: tutor at python.org
> Message-ID: <4761C207.4090804 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Alan Gauld wrote:
> > But I think Python itself is pretty safe with unicode v ascii in most 
> > cases.
> 
> I was actually holding my tongue on that one. My guess is it varies from 
>   one module to the next depending on how well maintained they are, but 
> I don't really know.
> 
> > I'm sure Kent will be able to comment further, he seems to have made
> > himself an expert in this area! (and I'm sure glad somebody has! :-)
> 
> I'm pretty knowledgeable about character sets and conversion issues, not 
> so much about how specific modules use unicode.
> 
> Kent
> 
> 
> ------------------------------
> 
> Message: 7
> Date: Thu, 13 Dec 2007 17:48:11 -0600
> From: "Luke Paireepinart" <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] user-given variable names for objects
> To: "Alan Gauld" <alan.gauld at btinternet.com>
> Cc: tutor at python.org
> Message-ID:
> 	<dfeb4470712131548i777f10dam9102c577a0a8173a at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> >
> > > By the way, what was the purpose of the line with
> > > time.sleep(1)
> >
> > It pauses for 1 second. But i'm not sure why he wanted a pause! :-)
> >
> Just because it would dump a bunch of stuff to the screen really quickly
> that you couldn't read as soon as some events expired.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20071213/a18afd70/attachment-0001.htm 
> 
> ------------------------------
> 
> Message: 8
> Date: Thu, 13 Dec 2007 17:50:17 -0600
> From: "Luke Paireepinart" <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] user-given variable names for objects
> To: Tiger12506 <keridee at jayco.net>
> Cc: tutor at python.org
> Message-ID:
> 	<dfeb4470712131550l11adf26h21dc67cb7eb86da6 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> On Dec 13, 2008 3:12 PM, Tiger12506 <keridee at jayco.net> wrote:
> 
> > I may sound like a know-it-all, but dictionaries *are* iterators.
> 
> I'm used to that from you :P
> 
> >
> > [a for a in eventData if eventData[a] < time.time()]
> >
> > This is more efficient. The keys method creates a list in memory first and
> > then it iterates over it.
> 
> Thanks. I was fairly certain that was the case, but since I wasn't going
> to
> test the code, I used the alternative.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20071213/95c1de19/attachment-0001.htm 
> 
> ------------------------------
> 
> Message: 9
> Date: Fri, 14 Dec 2007 11:08:11 +0900
> From: "Luis N" <globophobe at gmail.com>
> Subject: [Tutor] Introspect function or class' required arguments
> To: tutor at python.org
> Message-ID:
> 	<c6e072940712131808g3ad23a1dw570da5ed842646e1 at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
> 
> Is there a way to introspect a function or class' required arguments,
> particularly keyword arguments?
> 
> I can easily use a dictionary since it is my own function that I wish
> to introspect. I haven't tested the below code yet, but e.g.
> 
> obj = getattr(self, 'obj')()
> preprocessors = {'Card':[{'obj_attr':'mastery',
>                           'call':mastery,
>                           'args_dict':['front', 'back']}
>                          ]
>                  }
> obj_preprocessors = preprocessors.get(obj.__name__, None)
> if obj_preprocessors:
>     for preprocessor in obj_preprocessors:
>         function_name = preprocessor['call'].__name__
>         args_dict = {}
>         for arg in preprocessor['args_dict']:
>             if self.query_dict.has_key(arg):
>                 args_dict[preprocessor[arg]] = self.query_dict.get(arg)
>             else:
>                 self.error = 'Required argument %s omitted for
> function %s' % (arg, function_name)
>                 break
>         if not hasattr(self, error):
>             try:
>                 setattr(obj, preprocessor['obj_attr'],
> preprocessor['call'](args_dict))
>             except:
>                 self.error = 'Preprocessor %s failed.' % function_name
>         else:
>             break
> 
> 
> ------------------------------
> 
> Message: 10
> Date: Fri, 14 Dec 2007 10:43:48 +0900
> From: "Jim Morcombe" <jmorcombe at westnet.com.au>
> Subject: [Tutor] using quotes in IDLE
> To: <tutor at python.org>
> Message-ID: <000e01c83df2$c7e4cde0$6a00a8c0 at ASC000E7B84CF9F>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> A really dumb question...
> 
> When typing things into IDLE, how are quotes meant to work?
> 
> If I type"
> 
> employee.name = "Susan"
> 
> then IDLE ignores the last " and I get an error.
> 
> Jim
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20071214/08cd377b/attachment.htm 
> 
> ------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> End of Tutor Digest, Vol 46, Issue 39
> *************************************

From jfabiani at yolo.com  Fri Dec 14 04:47:24 2007
From: jfabiani at yolo.com (johnf)
Date: Thu, 13 Dec 2007 19:47:24 -0800
Subject: [Tutor] Fw:  what is the difference
In-Reply-To: <109474.85199.qm@web86701.mail.ird.yahoo.com>
References: <109474.85199.qm@web86701.mail.ird.yahoo.com>
Message-ID: <200712131947.24934.jfabiani@yolo.com>

On Thursday 13 December 2007 03:28:46 pm ALAN GAULD wrote:
> Terry Carroll wrote:
>
> On Thu, 13 Dec 2007, Alan Gauld wrote:
> >> > if self._inFlush:
> >> >       return
> >> > self._inFlush = True
> >> > ....
> >> >
> >> > I can not see the difference but the second one acts differently
>
>  in
>
> >> > my code.
> >>
> >> The first has no else clause so the second assignment always
>
>  happens.
>
> > Alan, are you teasing the newbies?
>
> No just not reading closely enough.
> You are quite right, I've no idea why they would behave differently!
>
> John, care to elaborate on what is different?
>
> > Or am I just misreading this somehow?
>
> Nope, I was.
>
> Alan G.

I was attempting to debug a program.  I was expecting self._inFlush to execute 
the return at least sometimes but not always.  I then changed the code and 
things started working.  But to my eyes I could determine the difference 
between
if ...:
  return

and 

if not ...:

else:
  return

I still don't!  But for some reason it works!



-- 
John Fabiani

From srikanth007m at gmail.com  Fri Dec 14 05:32:24 2007
From: srikanth007m at gmail.com (chinni)
Date: Thu, 13 Dec 2007 20:32:24 -0800
Subject: [Tutor] Python Editor For Mac Os X
Message-ID: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>

Hi which editor for python on Mac os x platform is best with color syntax
compiler etc...

-- 
Cheers,
M.Srikanth Kumar,
Phone no: +91-9866774007
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071213/bc3203ce/attachment.htm 

From globophobe at gmail.com  Fri Dec 14 06:06:31 2007
From: globophobe at gmail.com (Luis N)
Date: Fri, 14 Dec 2007 14:06:31 +0900
Subject: [Tutor] Introspect function or class' required arguments
In-Reply-To: <4761F391.3020100@tds.net>
References: <c6e072940712131808g3ad23a1dw570da5ed842646e1@mail.gmail.com>
	<4761F391.3020100@tds.net>
Message-ID: <c6e072940712132106h8374647q33756f2ca5c2b9f0@mail.gmail.com>

On Dec 14, 2007 12:08 PM, Kent Johnson <kent37 at tds.net> wrote:
> Luis N wrote:
> > Is there a way to introspect a function or class' required arguments,
> > particularly keyword arguments?
>
> See inspect.getargspec() and formatargspec().
> Look at the source if you want details of where the info is stored.

Thanks that's exactly what I was looking for :-)

> > I can easily use a dictionary since it is my own function that I wish
> > to introspect. I haven't tested the below code yet, but e.g.
>
> I don't understand what you are trying to do here.

The code I posted before is to be part of a dispatcher for a django
application. Objects are routed to 'add', 'edit', or 'delete' methods.
Data for some of the fields/attributes of my django models objects
needs to be preprocessed.

However, as the add/edit/delete methods are used for multiple objects
I need to determine dynamically if a particular preprocessor needs to
be called.

> Kent
>

Thanks again,


Luis

From gmoonn at gmail.com  Fri Dec 14 07:40:32 2007
From: gmoonn at gmail.com (Gman)
Date: Fri, 14 Dec 2007 01:40:32 -0500
Subject: [Tutor] Python Versions
Message-ID: <op.t3bbhubijgjj51@dialup-4.229.168.250.dial1.detroit1.level3.net>

  Well, I dont feel Igrint, yet I must be. Turns out that Early Light was  
right regarding the command prompt. I had to go back and try a few of the  
exercises again to see if i actually had overlooked something so obvious,  
and it turns out I had! Enclosed is a example of my
ineptitude.I didnt mean to cause a fuss, and this is the first chance I  
have had to get to my mail to send A response. One thing for certain I am  
humbled but all the wiser, all part of learning I suppose. On the brighter  
side maybe you could save this snippet of code and use it as an  
example............. (Friends dont let Friends do  
this!)...............................
Yep, that's me the poster boy of dont let this happen to you
IDLE 1.2.1
>>> # Filename: func_param.py
>>> def printMax(a, b):
	if a > b:
		print a, 'is maximum'
	else:
		print b, 'is maximum'
printMax(3, 4)
SyntaxError: invalid syntax
>>>
Whats worse is that this is only one, I muddled through several and still  
didnt catch it.
Anyhow thanks to your team and readers for the help!
-- 
Look sure in soup with socks dirty when to put with cracker in boots that  
I on wear to crunch.

From shantanoo at gmail.com  Fri Dec 14 08:38:34 2007
From: shantanoo at gmail.com (=?UTF-8?Q?=E0=A4=B6=E0=A4=82=E0=A4=A4=E0=A4=A8=E0=A5=81_(Shantanoo)?=)
Date: Fri, 14 Dec 2007 13:08:34 +0530
Subject: [Tutor] Python Editor For Mac Os X
In-Reply-To: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>
References: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>
Message-ID: <230174700712132338o391f6100sd7b050756dc2e543@mail.gmail.com>

On Dec 14, 2007 10:02 AM, chinni <srikanth007m at gmail.com> wrote:
> Hi which editor for python on Mac os x platform is best with color syntax
> compiler etc...

You can try emacs, vim, textmate, eclipse(?)

regards,
shantanoo

From evert.rol at gmail.com  Fri Dec 14 08:59:30 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 14 Dec 2007 07:59:30 +0000
Subject: [Tutor] Python Editor For Mac Os X
In-Reply-To: <230174700712132338o391f6100sd7b050756dc2e543@mail.gmail.com>
References: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>
	<230174700712132338o391f6100sd7b050756dc2e543@mail.gmail.com>
Message-ID: <B4D24289-1C30-47CB-B805-E78EF350CD9F@gmail.com>

> On Dec 14, 2007 10:02 AM, chinni <srikanth007m at gmail.com> wrote:
>> Hi which editor for python on Mac os x platform is best with color  
>> syntax
>> compiler etc...
>
> You can try emacs, vim, textmate, eclipse(?)

I like Aquamacs Emacs myself, but since Emacs has a steep learning  
curve, that may be a bit too much (although the Aquamacs version  
makes that learning curve somewhat shallower). It depends what you're  
used to, if anything. And whether you're looking for something fully  
integrated (an IDE), or just a text editor, and execute the scripts  
in the Terminal.

   Evert


From alan.gauld at btinternet.com  Fri Dec 14 09:45:28 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 14 Dec 2007 08:45:28 -0000
Subject: [Tutor] using quotes in IDLE
References: <000e01c83df2$c7e4cde0$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <fjtfra$csk$1@ger.gmane.org>


"Jim Morcombe" <jmorcombe at westnet.com.au> wrote

> When typing things into IDLE, how are quotes meant to work?
>
> If I type"
>
>employee.name = "Susan"
>
> then IDLE ignores the last " and I get an error.

Quotes should work the same in Idle as anywhere else!
I suspect what you are doing is trying to create a double
quote by typing two single quotes. That won't work.

The types of quotes you can use are:

'text'    = single quote at each end
              (using single quote key, right end of middle row on UK 
keyboard)
"text"  = double quote at each end
              (using the double quote key, shift 2 on a UK keyboard)
'''text''' = triple single quote - three consecutrive single quote 
keystrokes
"""text""" = triple double quote - three consecutive double quote 
keystrokes

You cannoyt use two consecutive single quotes to create
a double quote, like

''text'' because Python sees that as an empty string followed
by a name followed by another empty string which is an error.

Did I guess right?

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  Fri Dec 14 09:57:42 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 14 Dec 2007 08:57:42 -0000
Subject: [Tutor] Python Versions
References: <op.t3bbhubijgjj51@dialup-4.229.168.250.dial1.detroit1.level3.net>
Message-ID: <fjtgi8$enl$1@ger.gmane.org>


"Gman" <gmoonn at gmail.com> wrote in message

>>>> # Filename: func_param.py
>>>> def printMax(a, b):
> >>>if a > b:
>          print a, 'is maximum'
>       else:
>           print b, 'is maximum'
> printMax(3, 4)
> SyntaxError: invalid syntax

OK, I think this is because you have tried to use the function
before you finished defining it. And this is not your fault its the 
books.

When you use the >>> prompt you must enter each new
command at a >>> prompt. If the >>> isn;t there it means
IDLE still thinks you are entering part of the previous command.
In this case thats the function definition.

So if you just hit return a couple of times at the end of the
function you will get back to >>> where you can then enter
the last line and it should work.

So it should look like (from Pythonwin rather than IDLE):

>>> def printMax(a, b):
...  if a > b:
...     print a, 'is maximum'
...  else:
...     print b, 'is maximum'
...
>>> printMax(3, 4)
4 is maximum
>>>

HTH,

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



From jeff at drinktomi.com  Fri Dec 14 11:29:17 2007
From: jeff at drinktomi.com (Jeff Younker)
Date: Fri, 14 Dec 2007 02:29:17 -0800
Subject: [Tutor] Python Editor For Mac Os X
In-Reply-To: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>
References: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>
Message-ID: <A255AC48-C86A-4DB4-A9E4-092FE1109F3F@drinktomi.com>

On Dec 13, 2007, at 8:32 PM, chinni wrote:
> Hi which editor for python on Mac os x platform is best with color  
> syntax compiler etc...

I'm pretty happy with Eclipse + Pydev.

- Jeff Younker - jeff at drinktomi.com -



From keridee at jayco.net  Fri Dec 14 13:43:42 2007
From: keridee at jayco.net (Tiger12506)
Date: Fri, 14 Dec 2007 07:43:42 -0500
Subject: [Tutor] Python Versions
References: <571202.19726.qm@web45101.mail.sp1.yahoo.com>
Message-ID: <006b01c83e4e$f90fe9c0$83fce004@jslaptop>

My apologies for mistaking your gender. Because English does not have 
adequate neutral gender indication, I tend to use the male as such, as they 
do in Spanish, and perhaps many other languages. At any rate, that's how 
it's written in the Bible.

I presumed that it was an issue with raw input because not many other things
are truly different within the prompt. An extra line is necessary within the
prompt after blocks of code such as classes and function declarations. (I 
guess this didn't bother me when I first started learning python because I 
got irritated when I hit enter and it didn't do anything, so I hit enter 
again, much more violently. ;-)

My apologies also to you for assuming what was the issue. I have a knack for 
knowing just what goes wrong, but there are many occasions where I am wrong. 
:-)

> I'm a "she" not a "he".  :-)  But actually I don't believe I was a member
> of this group when I was working with the book "A Byte Of Python"  I don't
> believe I ever described a problem with raw_input here.  That concept
> seems pretty clear to me but as you say the OP hasn't described a specific
> problem.  As I said before, it was the fact that the author was describing
> features that I was not seeing in the shell that prompted me to try to
> figure out the "new window" feature.    As soon as I solved the shell
> problem I had no further difficulties understanding the concepts in the
> book.  I just thought I'd share what worked for me.  :-)
>
>  The OP has not specified what his problems specifically are, but
> "earlylight
> publishing" described his problem before, and he was not understanding
> why
> the >>> prompt was expecting immediate keyboard input when he typed in
> raw_input(). So a noob cannot figure out why it is advantageous to have
> a
> raw_input function that immediately asks for input. He thinks, "why
> can't I
> put the input in directly?" That is why putting a program into an edit
> window is very advantageous.
>
> I believe it is very likely that raw_input() is the culprit of
> confusion
> here.
>
>
>
> ---------------------------------
> Never miss a thing.   Make Yahoo your homepage.


From kent37 at tds.net  Fri Dec 14 14:57:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Dec 2007 08:57:56 -0500
Subject: [Tutor] Python Editor For Mac Os X
In-Reply-To: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>
References: <b5300ea90712132032y22ddc2d8u75a2e0564faa271c@mail.gmail.com>
Message-ID: <47628BE4.6030301@tds.net>

chinni wrote:
> Hi which editor for python on Mac os x platform is best with color 
> syntax compiler etc...

You will get as many answers for 'best' as there are editors :-) it 
really depends on your preferences.

I like TextMate myself.

Kent

From tjampman at gmail.com  Fri Dec 14 16:45:48 2007
From: tjampman at gmail.com (Ole Henning Jensen)
Date: Fri, 14 Dec 2007 16:45:48 +0100
Subject: [Tutor] using quotes in IDLE
References: <000e01c83df2$c7e4cde0$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <004c01c83e68$672136d0$7a02a8c0@allmycore>


----- Original Message ----- 
From: "Jim Morcombe" <jmorcombe at westnet.com.au>
To: <tutor at python.org>
Sent: Friday, December 14, 2007 2:43 AM
Subject: [Tutor] using quotes in IDLE


A really dumb question...

When typing things into IDLE, how are quotes meant to work?

If I type"

employee.name = "Susan"

then IDLE ignores the last " and I get an error.
-------------------------------------------------------

When pasting you code into IDLE i get this:

>>> employee.name = "Susan"

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    employee.name = "Susan"
NameError: name 'employee' is not defined

which is the result of me not having a class called employee, do you have 
that?
If not, you can't use dots in variable names so in stead of 'employee.name' 
you could use employeeName or employee_name

fx
>>> employee_name = "susan"
>>> print employee_name
susan


Regards Ole Jensen 



From bryan.fodness at gmail.com  Fri Dec 14 17:14:13 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Fri, 14 Dec 2007 11:14:13 -0500
Subject: [Tutor] upper and lower case input for file name
Message-ID: <fbf64d2b0712140814o27351c35l23ed6259e2120ac7@mail.gmail.com>

Is there an easy way that an input can be upper or lower case?

The file name is TEST.TXT, and I get.

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

Enter File (if not local, enter path):    test.txt

Traceback (most recent call last):
  File "test.py", line 52, in <module>
    for line in open(file) :
IOError: [Errno 2] No such file or directory: 'test.txt'

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

This is a non-issue on Windows, but now I have migrated to Ubuntu.

Bryan


-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071214/aa5a4667/attachment.htm 

From kent37 at tds.net  Fri Dec 14 17:31:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 14 Dec 2007 11:31:28 -0500
Subject: [Tutor] upper and lower case input for file name
In-Reply-To: <fbf64d2b0712140814o27351c35l23ed6259e2120ac7@mail.gmail.com>
References: <fbf64d2b0712140814o27351c35l23ed6259e2120ac7@mail.gmail.com>
Message-ID: <4762AFE0.7060601@tds.net>

Bryan Fodness wrote:
> 
> Is there an easy way that an input can be upper or lower case?
> 
> The file name is TEST.TXT, and I get.
> 
> -------------------------------------------------------------------------
> 
> Enter File (if not local, enter path):    test.txt
> 
> Traceback (most recent call last):
>   File "test.py", line 52, in <module>
>     for line in open(file) :
> IOError: [Errno 2] No such file or directory: 'test.txt'
> 
> -------------------------------------------------------------------------
> 
> This is a non-issue on Windows, but now I have migrated to Ubuntu.

File names in the Windows file system are not case sensitive; in Linux 
they are. In Linux you can actually have two different files called 
test.txt and TEST.TXT:
[blogcosm at web8 py]$ cat > test.txt
this is a test
[blogcosm at web8 py]$ cat > TEST.TXT
THIS IS ANOTHER TEST
[blogcosm at web8 py]$ cat test.txt
this is a test
[blogcosm at web8 py]$ cat TEST.TXT
THIS IS ANOTHER TEST

Probably the best solution is to get used to it :-) but you could check 
for other files in the dir whose name matches ignoring case and open 
that file if there is a unique match.

Kent

From amonroe at columbus.rr.com  Fri Dec 14 21:08:43 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Fri, 14 Dec 2007 15:08:43 -0500
Subject: [Tutor] How to get python to differentiate between CR, LF,
	and CRLF in a string (not a file)?
Message-ID: <138-860626956.20071214150843@columbus.rr.com>

Is is possible to get python to differentiate between CR, LF, and CRLF
in a string (not a file)? This is a triple quoted string I've pasted
into the source (putting r to indicate raw string made no difference).
It contains a mixture of CR, LF and CRLF (I can see this by enabling
visible End of Line markers in Scite). I need to distingush between
them.

Whenever I iterate over the string, it's automagically converting all
variants to an ascii 10.

    for x in entry:
        print repr(x), ord(x)

...
'S' 83
'c' 99
'h' 104
'e' 101
'd' 100
'u' 117
'l' 108
'e' 101
'd' 100
'\n' 10  <--- this should be a 13 followed by a 10
...


Alan


From thorsten at thorstenkampe.de  Fri Dec 14 22:17:58 2007
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 14 Dec 2007 21:17:58 -0000
Subject: [Tutor] ipython / readline problem
References: <20071213111918.GC4812@localdomain> <47612864.5050206@tds.net>
	<20071213190554.GF4812@localdomain>
Message-ID: <fjuru8$86n$1@ger.gmane.org>

* Tiago Saboga (Thu, 13 Dec 2007 17:05:55 -0200)
> On Thu, Dec 13, 2007 at 07:41:08AM -0500, Kent Johnson wrote:
> > Tiago Saboga wrote:
> >> <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode
> >> character u'\xe7' in position 2: ordinal not in range(128)
> >>
> >> =======================================
> >>
> >> What's happening? Why do the readline methods accept a multibyte
> >> string ('a??o') but not a unicode (u'a??o')?
> >
> > I don't know what is happening with readline but this error is usually the
> > result of converting a Unicode string to a plain string without specifying
> > encoding, either explicitly by calling str() or implicitly such as in a
> > print statement:
> 
> I already knew that, but it helped somehow ;)
> 
> Apparently the problem is that ipython converts the input to unicode,
> while the readline module wants a string object. With single line
> input, ipython doesn't interfere with readline, but for multiline
> input, it updates readline's history, but it tries to to that with the
> unicode object. I've sent a patch to the ipython bug to reencode the
> string to sys.stdin.encoding before submitting it to readline.

For the new Ipython there's a new setting:

pyreadline.unicode_helper.pyreadline_codepage='utf8'


From keridee at jayco.net  Fri Dec 14 22:23:00 2007
From: keridee at jayco.net (Tiger12506)
Date: Fri, 14 Dec 2007 16:23:00 -0500
Subject: [Tutor] Python Versions
References: <571202.19726.qm@web45101.mail.sp1.yahoo.com>
	<006b01c83e4e$f90fe9c0$83fce004@jslaptop>
	<82b4f5810712140851x1c3f8846s39051a70e735121c@mail.gmail.com>
Message-ID: <001201c83e97$af359f90$67fde004@jslaptop>

> Despite what your english teacher might have tried to make you
> believe, they were wrong about the lack of a neutral in english. Just
> like ending sentences with prepositions has always been done and
> always will be done,  the use of "they" to refer to someone of
> indeterminate gender has been well and alive for hundreds of years.
>
> The fact you think it isn't okay is because some english teacher sold
> you a line of crap about prescriptive grammar rules that don't
> actually hold true in actual writing. Many grammar books try to make
> the language into what it is not, rather than describing it as it is.

No. I form my own opinions and do not believe individuals such as my english 
"teachers" unless I truly believe that each one is correct. Each of my 
english teachers will not tell you to use "they" or even the masculine, 
instead prefering the "proper" way to be "his/her", and equivalent forms. I 
personally believe this to be a waste of time, and efficiency is one of my 
primary motivators. Therefore, for space and time I use "he" for an unknown. 
Proper english (as it is from my viewpoint) would be to restructure the 
sentence so that it uses "one" in that instance. (My english teachers would 
gasp at this) This makes the most logical sense. For more than one person of 
unknown gender, English uses "everyone". So for one person of unknown 
gender, English uses "one". "They" does not match plurality. Using "they" as 
you describe it would mean that we should be forming sentences such as "They 
works" "They bakes" "They codes in python". Clearly this does not sound 
correct because the word "they" is meant to be used as a plural pronoun 
only. No, I do not believe in english teachers, and I believe that just 
because people have used "they" for centuries should not indicate that it is 
the correct way to speak. I feel that the only correct language is the one 
which closely follows the rules of mathematics. A few examples.

English: "In no way should I stop working".         Math: (-) * (-) = (+)
English: "This and that"                                        Math: (this) 
+ (that) = both
English: "This, but not that"                                  Math: 
(both) - (that) = this
Spanish: "Estos dos ?rboles verdes son bonitos"  Math: 2(a+b) = 2a+2b

That is why I like to program so much. Computer languages are very closely 
mapped to mathematical theory. No, I do not listen to my english teachers 
because they do not understand what it is to be a musician, mathematician, 
scientist, and philospher simultaneously.

> Leave the sexist, antediluvian notions of your grammar texts behind
> and write like people always have. Don't make a mistake about that
> next person, no matter what *their* gender may be.

I shall not make the same mistake, but I shall not write like people 
"always" have. If I were more capable, I would write exceptionally better.

This is a python list and this discussion has continued for enough time. I 
would much rather hear your opinions on a piece of python code rather than 
your criticism of an action for which I have already apologized.

Jacob Schmidt
PS - "Always" is such a strong word; in math it translates to the limit as 
time approaches infinity in both directions. So powerful that even the 
mathematical language has difficulties expressing it. 


From h.fangohr at soton.ac.uk  Sat Dec 15 07:43:15 2007
From: h.fangohr at soton.ac.uk (Hans Fangohr)
Date: Sat, 15 Dec 2007 06:43:15 +0000 (GMT)
Subject: [Tutor] python logging module: two handlers writing to the same
	file - okay?
Message-ID: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>

Dear all,

I am trying to set up a logging system with the following specs:

- all messages should be printed to stdout and to a file (here called log.log).

- we have two types of loggers that the code uses: 'normal' and 'short'.

- The 'short' logger just prints less detail (it
   basically needs another 'formatter'; the code shown here is just a
   simplified version of the actual problem.)

- the formatters appear to be attached to handlers in the logging
   module (if I interpret the module correctly)

- the loggers have handlers, of which we have four:

   - file (for the 'normal' logger to 'log.log')
   - file-short (for the 'short' logger to 'log.log')
   - console (for the 'normal' logger to stdout)
   - console-short (for the 'short' logger to stdout)

I have an example program (test.py) and the logging configuration file
(log.conf) attached below (they are also available at
http://www.soton.ac.uk/~fangohr/geheim/two_handlers_one_file)

Here are the questions:

(i) is this (as in the log.conf file) the right use of the logging
module to achieve what I need?

(ii) in particular, it appears we have two filehandlers that write to
the same file (in mode 'a+'). While this seems to work fine in the
examples I have tested, I'd like some independent advice on whether
this is 'legal' (or whether it works by chance).

(I have seen this not working when both files are opened with mode
'w'.)

Many thanks for your time, and any advice.

Best wishes,

Hans

Files:
---------------
test.py:
---------------

import logging.config
logging.config.fileConfig('log.conf')

normal_log = logging.getLogger('normal')
short_log = logging.getLogger('short')


normal_log.info("A message to file and console")
short_log.info("A short message to file and console")

-----------------
log.conf:
----------------

[loggers]
keys=root,normal,short

[handlers]
keys=console,file,file-short,console-short

[formatters]
keys=consolef,filef,shortf

[logger_root]
level=INFO
handlers=console,file

[logger_normal]
level=NOTSET
handlers=console,file
qualname=normal
propagate=0

[logger_short]
level=NOTSET
handlers=file-short,console-short
qualname=short
propagate=0

[handler_console]
class=StreamHandler
level=NOTSET
formatter=consolef
args=(sys.stdout,)

[handler_file]
class=FileHandler
level=NOTSET
formatter=filef
args=('log.log', 'a+')

[handler_console-short]
class=StreamHandler
level=NOTSET
formatter=shortf
args=(sys.stdout,)

[handler_file-short]
class=FileHandler
level=NOTSET
formatter=shortf
args=('log.log','a+')

[formatter_consolef]
format=%(name)11s:%(asctime)s %(levelname)7s %(message)s
datefmt=

[formatter_filef]
format=%(name)11s:%(asctime)s %(levelname)7s %(message)s
datefmt=

[formatter_shortf]
format=%(name)11s:%(levelname)7s %(message)s 
datefmt=



From kent37 at tds.net  Sat Dec 15 14:30:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 15 Dec 2007 08:30:27 -0500
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
Message-ID: <4763D6F3.8020905@tds.net>

Hans Fangohr wrote:

> (i) is this (as in the log.conf file) the right use of the logging
> module to achieve what I need?

I think you understand the module correctly.

> (ii) in particular, it appears we have two filehandlers that write to
> the same file (in mode 'a+'). While this seems to work fine in the
> examples I have tested, I'd like some independent advice on whether
> this is 'legal' (or whether it works by chance).

I don't know the answer, but it has nothing to do with the logging 
module. The question is, can the same file reliably be opened twice for 
writing in the same module.

Another option: If you configure logging in code, you could create two 
StreamHandlers that log to the same file - open the file yourself and 
pass it to both handlers. If you do this you will have to close the file 
yourself somehow.

Kent

From deliberatus at verizon.net  Sat Dec 15 16:10:55 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sat, 15 Dec 2007 10:10:55 -0500
Subject: [Tutor] windowsfiles permissions
Message-ID: <4763EE7F.9020103@verizon.net>

So, in windows, when my wiki's editor saves a file, i  want to have the 
option to set it to read only. In  windows, how do i get python to set a 
file's permissions?

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From ricaraoz at gmail.com  Sat Dec 15 17:10:14 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 15 Dec 2007 13:10:14 -0300
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <4763D6F3.8020905@tds.net>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
	<4763D6F3.8020905@tds.net>
Message-ID: <4763FC66.40609@bigfoot.com>

Kent Johnson wrote:
> Hans Fangohr wrote:
> 
>> (i) is this (as in the log.conf file) the right use of the logging
>> module to achieve what I need?
> 
> I think you understand the module correctly.
> 
>> (ii) in particular, it appears we have two filehandlers that write to
>> the same file (in mode 'a+'). While this seems to work fine in the
>> examples I have tested, I'd like some independent advice on whether
>> this is 'legal' (or whether it works by chance).
> 
> I don't know the answer, but it has nothing to do with the logging 
> module. The question is, can the same file reliably be opened twice for 
> writing in the same module.
> 
> Another option: If you configure logging in code, you could create two 
> StreamHandlers that log to the same file - open the file yourself and 
> pass it to both handlers. If you do this you will have to close the file 
> yourself somehow.
> 
> Kent
>

Well, the question would actually be if the logging module is smart
enough to find out that both your filehandlers are referring to the same
file and open it only once.


From kent37 at tds.net  Sat Dec 15 17:34:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 15 Dec 2007 11:34:37 -0500
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <4763FC66.40609@bigfoot.com>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
	<4763D6F3.8020905@tds.net> <4763FC66.40609@bigfoot.com>
Message-ID: <4764021D.6020707@tds.net>

Ricardo Ar?oz wrote:
> Kent Johnson wrote:
>> I don't know the answer, but it has nothing to do with the logging 
>> module. The question is, can the same file reliably be opened twice for 
>> writing in the same module.
> 
> Well, the question would actually be if the logging module is smart
> enough to find out that both your filehandlers are referring to the same
> file and open it only once.

A quick glance at the logging module shows that it is not that smart. It 
just opens the file twice; hence my original question.

Kent

From keridee at jayco.net  Sat Dec 15 17:32:20 2007
From: keridee at jayco.net (Tiger12506)
Date: Sat, 15 Dec 2007 11:32:20 -0500
Subject: [Tutor] user-given variable names for objects
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl><4760E612.1030109@gmail.com><BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>	<fjru43$54g$1@ger.gmane.org>
	<008201c95d67$a8eed990$a1fce004@jslaptop>
	<4761A312.9000808@tds.net>
Message-ID: <000b01c83f38$6741e7b0$d4fde004@jslaptop>

> Mmm, to nit-pick a little, dictionaries are iterables, not iterators. They 
> don't have a next() method.

I'm a little fuzzy on the details of that, I will have to look over some 
reference material again.

>> [a for a in eventData if eventData[a] < time.time()]
>>
>> This is more efficient. The keys method creates a list in memory first 
>> and then it iterates over it.
>
> I've never tested it but I suspect that when you need keys and values, it 
> is more efficient to use itervalues():
>
> [ k for k, v in eventData.itervalues() if v < time.time() ]

Oh! This is new to me! When did they put in itervalues? See what happens 
when you leave the python community so you can learn C and assembly~

> and of course if you care about efficiency you should hoist the call to 
> time.time() out of the loop!

Oh, I thought it was necessary for the time to change within the loop which 
might or might not be necessary, depending on just what exactly is supposed 
to happen. I would guess that in an unordered data structure like that, it 
wouldn't be of any use to update the time within the loop.
Ask me if you are curious and can't follow my reasoning. 


From kent37 at tds.net  Sat Dec 15 17:57:29 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 15 Dec 2007 11:57:29 -0500
Subject: [Tutor] user-given variable names for objects
In-Reply-To: <000b01c83f38$6741e7b0$d4fde004@jslaptop>
References: <BAY105-W38E995508CA5B16E1BACD8E0660@phx.gbl><4760E612.1030109@gmail.com><BAY105-W28994BBBF5C3E4C6EF9103E0660@phx.gbl>	<fjru43$54g$1@ger.gmane.org>	<008201c95d67$a8eed990$a1fce004@jslaptop>	<4761A312.9000808@tds.net>
	<000b01c83f38$6741e7b0$d4fde004@jslaptop>
Message-ID: <47640779.1020003@tds.net>

Tiger12506 wrote:
>> Mmm, to nit-pick a little, dictionaries are iterables, not iterators. They 
>> don't have a next() method.
> 
> I'm a little fuzzy on the details of that, I will have to look over some 
> reference material again.

An iterable is something that produces an iterator when you call iter() 
on it. An iterator has a next() method. More here:
http://personalpages.tds.net/~kent37/kk/00004.html

> Oh! This is new to me! When did they put in itervalues? See what happens 
> when you leave the python community so you can learn C and assembly~

Python 2.2, when explicit iterators were introduced.

>> and of course if you care about efficiency you should hoist the call to 
>> time.time() out of the loop!
> 
> Oh, I thought it was necessary for the time to change within the loop which 
> might or might not be necessary

Yes, the functionality is slightly different if the time() call is 
hoisted out of the loop.

Kent

From earlylightpublishing at yahoo.com  Sat Dec 15 18:06:06 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Sat, 15 Dec 2007 09:06:06 -0800 (PST)
Subject: [Tutor] upper and lower case input for file name
Message-ID: <74954.79180.qm@web45112.mail.sp1.yahoo.com>

I don't know if this'll help or not but I just learned about this:
   
  file = raw_input(info).lower
   
  The .lower is supposed to convert any input to lower case.  
   
  ------------------------------

Message: 4
Date: Fri, 14 Dec 2007 11:14:13 -0500
From: "Bryan Fodness" <bryan.fodness at gmail.com>
Subject: [Tutor] upper and lower case input for file name
To: tutor-python <tutor at python.org>
Message-ID:
 <fbf64d2b0712140814o27351c35l23ed6259e2120ac7 at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

Is there an easy way that an input can be upper or lower case?

The file name is TEST.TXT, and I get.

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

Enter File (if not local, enter path):    test.txt

Traceback (most recent call last):
  File "test.py", line 52, in <module>
    for line in open(file) :
IOError: [Errno 2] No such file or directory: 'test.txt'

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

This is a non-issue on Windows, but now I have migrated to Ubuntu.

Bryan


       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071215/f2f3d9cf/attachment.htm 

From earlylightpublishing at yahoo.com  Sat Dec 15 18:21:45 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Sat, 15 Dec 2007 09:21:45 -0800 (PST)
Subject: [Tutor] Python Versions
Message-ID: <801231.69611.qm@web45104.mail.sp1.yahoo.com>

No prob about the gender confusion.  :-)  I'd be willing to bet most folks around here are male so it's not unreasonable to assume.  I wasn't offended, just thought I'd share in the interest of accuracy.  Thanks for the kind appology anyway.  Hope I haven't set off a firestorm!
   
  Message: 1
Date: Fri, 14 Dec 2007 07:43:42 -0500
From: "Tiger12506" <keridee at jayco.net>
Subject: 
  To: <tutor at python.org>
Message-ID: <006b01c83e4e$f90fe9c0$83fce004 at jslaptop>
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
 reply-type=original

My apologies for mistaking your gender. Because English does not have 
adequate neutral gender indication, I tend to use the male as such, as
 they 
do in Spanish, and perhaps many other languages. At any rate, that's
 how 
it's written in the Bible.

I presumed that it was an issue with raw input because not many other
 things
are truly different within the prompt. An extra line is necessary
 within the
prompt after blocks of code such as classes and function declarations.
 (I 
guess this didn't bother me when I first started learning python
 because I 
got irritated when I hit enter and it didn't do anything, so I hit
 enter 
again, much more violently. ;-)

My apologies also to you for assuming what was the issue. I have a
 knack for 
knowing just what goes wrong, but there are many occasions where I am
 wrong. 
:-)


       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071215/cac56dc5/attachment.htm 

From alan.gauld at btinternet.com  Sat Dec 15 18:29:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 15 Dec 2007 17:29:40 -0000
Subject: [Tutor] upper and lower case input for file name
References: <74954.79180.qm@web45112.mail.sp1.yahoo.com>
Message-ID: <fk12u7$ctr$1@ger.gmane.org>


"earlylight publishing" <earlylightpublishing at yahoo.com> wrote 

>I don't know if this'll help or not but I just learned about this:
>   
>  file = raw_input(info).lower

file = raw_input(prompt).lower()     # note the parens!

>  The .lower is supposed to convert any input to lower case.  

It will indeed. There is also an upper() if you want to make it 
uppercase instead.


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



From deliberatus at verizon.net  Sat Dec 15 17:52:57 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sat, 15 Dec 2007 11:52:57 -0500
Subject: [Tutor] windowsfiles permissions
In-Reply-To: <4763EE7F.9020103@verizon.net>
References: <4763EE7F.9020103@verizon.net>
Message-ID: <47640669.50500@verizon.net>

Found it. tested it. worked it. sgharinig it for otheers.

# os.chmod(filename,stat.S_IREAD  )
#	print 'This page is now set to read only. Use WindowsExplorer to turn this 
off.<P>'

Let's me edit the terms and conditions page then set it to read only- 
thought others would also value a convenient way to set pages to read only 
once polished up to a finished state. just be sure to import stat module.

And addressing the windows thread fro  adayor so ago; There's gold in them 
dar hills, even if it is a tad smelly, unlike linux gold; gold washes off 
nicely. There's one heck of a lot of windows customers out there.

Kirk Bailey wrote:
> So, in windows, when my wiki's editor saves a file, i  want to have the 
> option to set it to read only. In  windows, how do i get python to set a 
> file's permissions?
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From keridee at jayco.net  Sat Dec 15 19:04:52 2007
From: keridee at jayco.net (Tiger12506)
Date: Sat, 15 Dec 2007 13:04:52 -0500
Subject: [Tutor] python logging module: two handlers writing to the
	samefile - okay?
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
Message-ID: <008c01c83f45$339400d0$d4fde004@jslaptop>


----- Original Message ----- 
From: "Hans Fangohr" <h.fangohr at soton.ac.uk>
To: <tutor at python.org>
Sent: Saturday, December 15, 2007 1:43 AM
Subject: [Tutor] python logging module: two handlers writing to the 
samefile - okay?

> I have an example program (test.py) and the logging configuration file
> (log.conf) attached below (they are also available at
> http://www.soton.ac.uk/~fangohr/geheim/two_handlers_one_file)

> (ii) in particular, it appears we have two filehandlers that write to
> the same file (in mode 'a+'). While this seems to work fine in the
> examples I have tested, I'd like some independent advice on whether
> this is 'legal' (or whether it works by chance).
>
> (I have seen this not working when both files are opened with mode
> 'w'.)

I think this makes sense. 'w' mode automatically blanks out the file before 
writing. So each time that the file is opened, whatever was in it before is 
gone. Also, there may be some sort of difference due to the '+' which means 
to open the file in update mode. What that means still makes little sense to 
me. I *think* it has something to do with whether the file can be read and 
written without different file handles. But that doesn't seem to matter in 
python. Does someone know about this? Maybe a new thread...

Thanks,
JS 


From thorsten at thorstenkampe.de  Sat Dec 15 19:16:13 2007
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 15 Dec 2007 18:16:13 -0000
Subject: [Tutor] Python Versions
References: <801231.69611.qm@web45104.mail.sp1.yahoo.com>
Message-ID: <fk15ld$jof$1@ger.gmane.org>

* earlylight publishing (Sat, 15 Dec 2007 09:21:45 -0800 (PST))
> No prob about the gender confusion.  :-)

That's why people put Firstname Lastname in the From field of their 
newsreader or mail reader. And please do a line break after about 70 
characters. Your reply was one(!) big line.

Thorsten


From keridee at jayco.net  Sat Dec 15 19:14:25 2007
From: keridee at jayco.net (Tiger12506)
Date: Sat, 15 Dec 2007 13:14:25 -0500
Subject: [Tutor] upper and lower case input for file name
References: <74954.79180.qm@web45112.mail.sp1.yahoo.com>
	<fk12u7$ctr$1@ger.gmane.org>
Message-ID: <00c601c83f46$ce5819c0$d4fde004@jslaptop>

> "earlylight publishing" <earlylightpublishing at yahoo.com> wrote
>
>>I don't know if this'll help or not but I just learned about this:
>>
>>  file = raw_input(info).lower
>
> file = raw_input(prompt).lower()     # note the parens!
>
>>  The .lower is supposed to convert any input to lower case.
>
> It will indeed. There is also an upper() if you want to make it
> uppercase instead.

And not just input either. All strings have this method. (just for those who 
are not aware)
>>> a = "JaCoB"
>>> a.lower()
"jacob"
>>> a.upper()
"JACOB"
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__
ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', 
'__g
t__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', 
'__mul__
', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__rmod__', '
__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 
'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 
'isdi
git', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 
'lst
rip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 
'rsplit'
, 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 
'title', '
translate', 'upper', 'zfill']
>>>

Just look at all the possibilities! ;-) 


From thorsten at thorstenkampe.de  Sat Dec 15 19:29:46 2007
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 15 Dec 2007 18:29:46 -0000
Subject: [Tutor] Python Versions
References: <571202.19726.qm@web45101.mail.sp1.yahoo.com>
	<006b01c83e4e$f90fe9c0$83fce004@jslaptop>
	<82b4f5810712140851x1c3f8846s39051a70e735121c@mail.gmail.com>
	<001201c83e97$af359f90$67fde004@jslaptop>
Message-ID: <fk16eq$jof$2@ger.gmane.org>

* Tiger12506 (Fri, 14 Dec 2007 16:23:00 -0500)
> > Despite what your english teacher might have tried to make you
> > believe, they were wrong about the lack of a neutral in english.
> > Just like ending sentences with prepositions has always been done
> > and always will be done, the use of "they" to refer to someone of
> > indeterminate gender has been well and alive for hundreds of
> > years.
> >
> > The fact you think it isn't okay is because some english teacher
> > sold you a line of crap about prescriptive grammar rules that
> > don't actually hold true in actual writing. Many grammar books try
> > to make the language into what it is not, rather than describing
> > it as it is.
> 
> No. I form my own opinions and do not believe individuals such as my
> english "teachers" unless I truly believe that each one is correct.
> Each of my english teachers will not tell you to use "they" or even
> the masculine, instead prefering the "proper" way to be "his/her",
> and equivalent forms. I personally believe this to be a waste of
> time, and efficiency is one of my primary motivators. Therefore, for
> space and time I use "he" for an unknown.

That's common English usage:
'In languages with a masculine and feminine gender (and possibly a 
neuter), the masculine is usually employed by default to refer to 
persons of unknown gender. This is still done sometimes in English, 
although an alternative is to use the singular "they".'[1]

> Proper english (as it is from my viewpoint) would be to restructure
> the sentence so that it uses "one" in that instance. (My english
> teachers would gasp at this) This makes the most logical sense. For
> more than one person of unknown gender, English uses "everyone". So
> for one person of unknown gender, English uses "one".

No (see above).

> "They" does not match plurality. Using "they" as you describe it
> would mean that we should be forming sentences such as "They works"
> "They bakes" "They codes in python". Clearly this does not sound
> correct because the word "they" is meant to be used as a plural
> pronoun only.

No (see above).

Thorsten
[1] 
http://en.wikipedia.org/wiki/Grammatical_gender#Indeterminate_gender


From kuffert_med_hat at hotmail.com  Sat Dec 15 23:29:34 2007
From: kuffert_med_hat at hotmail.com (2face xzibit)
Date: Sat, 15 Dec 2007 22:29:34 +0000
Subject: [Tutor] binary translator
Message-ID: <BAY112-W1656FA21B4125E43A58684A3600@phx.gbl>


Hey i have created a program that turns a string into a binary one. But when i began to test the program it turned out that it could not handle  some special characters (e.g ???). Could someone please help me?   

p.s i am a newbie so if you have any comments on the source code please let me know  

here is the source code:

#!/usr/bin/python
# -*- coding: Latin-1 -*-
import os, sys
import sys

def ChooSe():
	print
	print " encrypt " 
	print " quit    "
	print
	
	choice = raw_input("What do you need: ")
	
	if choice == "encrypt": 
		encrypt()
	elif choice == "quit": 
		kExit()
	else:
		print "Invalid choice"
		ChooSe()	 

def kExit():
	xit = raw_input("Do you really want to quit? ")
	kY = ('y','Y','yes','yah','yeah')
	kN = ('n','N','no','nah')
	if xit in kN:
		ChooSe()
	elif xit in kY:
		print "Goodbye!"
		print
		sys.exit()
	else:
		print "Invalid choice"
		ChooSe()
def encrypt():
	
	print
	print "  encryption  "
	print		
			
	secret = raw_input('Text to encrypt: ')
	code = list(secret)
	
	
	chartobinary = {
		'A' : '01000001',
		'B' : '01000010',
		'C' : '01000011',
		'D' : '01000100',
		'E' : '01000101',
		'F' : '01000110',
		'G' : '01000111',
		'H' : '01001000',
		'I' : '01001001',
		'J' : '01001010',
		'K' : '01001011',
		'L' : '01001100',
		'M' : '01001101',
		'N' : '01001110',
		'O' : '01001111',
		'P' : '01010000',
		'Q' : '01010001',
		'R' : '01010010',
		'S' : '01010011',
		'T' : '01010100',
		'U' : '01010101',
		'V' : '01010110',
		'W' : '01010111',
		'X' : '01011000',
		'Y' : '01011001',
		'Z' : '01011010',
		'a' : '01100001',
		'b' : '01100010',
		'c' : '01100011',
		'd' : '01100100',
		'e' : '01100101',
		'f' : '01100110',
		'g' : '01100111',
		'h' : '01101000',
		'i' : '01101001',
		'j' : '01101010',
		'k' : '01101011',
		'l' : '01101100',
		'm' : '01101101',
		'n' : '01101110',
		'o' : '01101111',
		'p' : '01110000',
		'q' : '01110001',
		'r' : '01110010',
		's' : '01110011',
		't' : '01110100',
		'u' : '01110101',
		'v' : '01110110',
		'w' : '01110111',
		'x' : '01111000',
		'y' : '01111001',
		'z' : '01111010',
		' ' : '00100000',
		'!' : '00100001',
		"\\" : '00100010',
		'#' : '00100011',
		'$' : '00100100',
		'%' : '00100101',
		'&' : '00100110',
		"'" : '00100111',
		'(' : '00101000',
		')' : '00101001',
		'*' : '00101010',
		'+' : '00101011',
		',' : '00101100',
		'-' : '00101101',
		'.' : '00101110',
		'/' : '00101111',
		':' : '00111010',
		';' : '00111011',
		'<' : '00111100',
		'=' : '00111101',
		'>' : '00111110',
		'?' : '00111111',
		'@' : '01000000',
		'[' : '01011011',
		']' : '01011101',
		'^' : '01011110',
		'_' : '01011111',
		'`' : '01100000',
		'{' : '01111011',
		'|' : '01111100',
		'}' : '01111101',
		'~' : '01111110',
		'?' : '10000000',
		'?' : '10100001',
		'?' : '10100010',
		'?' : '10100011',
		'?' : '10100100',
		'?' : '10100101',
		'?' : '10100110',
		'?' : '10100111',
		'?' : '10101000',
		'?' : '10101001',
		'?' : '10101010',
		'?' : '10101011',
		'?' : '10101100',
		'?' : '10101110',
		'?' : '10101111',
		'?' : '10110000',
		'?' : '10110001',
		'?' : '10110010',
		'?' : '10110011',
		'?' : '10110100',
		'?' : '10110101',
		'?' : '10110110',
		'?' : '10110111',
		'?' : '10111000',
		'?' : '10111001',
		'?' : '10111010',
		'?' : '10111011',
		'?' : '10111100',
		'?' : '10111101',
		'?' : '01111110',
		'?' : '10111111',
		'?' : '11000000',
		'?' : '11000001',
		'?' : '11000010',
		'?' : '11000011',
		'?' : '11000100',
		'?' : '11000101',
		'?' : '11000110',
		'?' : '11000111',
		'?' : '11001000',
		'?' : '11001001',
		'?' : '11001010',
		'?' : '11001011',
		'?' : '11001100',
		'?' : '11001101',
		'?' : '11001110',
		'?' : '11001111',
		'?' : '11010000',
		'?' : '11010001',
		'?' : '11010010',
		'?' : '11010011',
		'?' : '11010100',
		'?' : '11010101',
		'?' : '11010110',
		'?' : '11010111',
		'?' : '11011000',
		'?' : '11011001',
		'?' : '11011010',
		'?' : '11011011',
		'?' : '11011100',
		'?' : '11011101',
		'?' : '11011110',
		'?' : '11011111',
		'?' : '11100000',
		'?' : '11100001',
		'?' : '11100010',
		'?' : '11100011',
		'?' : '11100100',
		'?' : '11100101',
		'?' : '11100110',
		'?' : '11100111',
		'?' : '11101000',
		'?' : '11101001',
		'?' : '11101010',
		'?' : '11101011',
		'?' : '11101100',
		'?' : '11101101',
		'?' : '11101110',
		'?' : '11101111',
		'?' : '11110000',
		'?' : '11110001',
		'?' : '11110010',
		'?' : '11110011',
		'?' : '11110100',
		'?' : '11110101',
		'?' : '11110110',
		'?' : '11110111',
		'?' : '11111000',
		'?' : '11111001',
		'?' : '11111010',
		'?' : '11111011',
		'?' : '11111100',
		'?' : '11111101',
		'?' : '11111110',
		'?' : '11111111',
		'0' : '00110000',
		'1' : '00110001',
		'2' : '00110010',
		'3' : '00110011',
		'4' : '00110100',
		'5' : '00110101',
		'6' : '00110110',
		'7' : '00110111',
		'8' : '00111000',
		'9' : '00111001',
			}	
	def TransLate():
		key = 1
		fTransLaTion = chartobinary[code[0]]
		aTransLaTion = ""
		while key <= len(code) - 1:
			TransLaTion = chartobinary[code[key]]
			key = key + 1
			aTransLaTion = aTransLaTion+TransLaTion
		lTranslation = fTransLaTion+aTransLaTion
		print lTranslation	
	TransLate()		
	ChooSe()
ChooSe()		 
 
_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today it's FREE!
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

From keridee at jayco.net  Sun Dec 16 00:39:30 2007
From: keridee at jayco.net (Tiger12506)
Date: Sat, 15 Dec 2007 18:39:30 -0500
Subject: [Tutor] binary translator
References: <BAY112-W1656FA21B4125E43A58684A3600@phx.gbl>
Message-ID: <002f01c83f74$259ad740$99fce004@jslaptop>

>
> Hey i have created a program that turns a string into a binary one. But 
> when i began to test the program it turned out that it could not handle 
> some special characters (e.g ???). Could someone please help me?

These special characters have different values than those you have put into 
your big list. I have suggestions down below.

>
> p.s i am a newbie so if you have any comments on the source code please 
> let me know

I have a couple.

> here is the source code:
>
> #!/usr/bin/python
> # -*- coding: Latin-1 -*-
> import os, sys
> import sys
>
> def ChooSe():
> print
> print " encrypt "
> print " quit    "
> print

You know that you can make this one print statement if you wish? ( \n is the 
escape character for a new-line)
print "\nencrypt\nquit"

or more easily readable~

print """\
encrypt
quit
"""

> choice = raw_input("What do you need: ")
>
> if choice == "encrypt":
> encrypt()
> elif choice == "quit":
> kExit()
> else:
> print "Invalid choice"
> ChooSe()


> def kExit():
> xit = raw_input("Do you really want to quit? ")
> kY = ('y','Y','yes','yah','yeah')
> kN = ('n','N','no','nah')

You could put those tuples directly into the if statement, it is not 
necessary to assign them to a variable first. I think it makes it more 
readable. You do not have to.

if xit in ('n','N','no','nah'):

> if xit in kN:
> ChooSe()
> elif xit in kY:
> print "Goodbye!"
> print
> sys.exit()
> else:
> print "Invalid choice"
> ChooSe()


> def encrypt():
>
> print
> print "  encryption  "
> print
>
> secret = raw_input('Text to encrypt: ')
> code = list(secret)
^^^^^^^^^^^^^^^^^
This is unnecessary. secret is already iterable.
secret[0] == code[0]

>
> chartobinary = {
> 'A' : '01000001',
> 'B' : '01000010',
> 'C' : '01000011',
> 'D' : '01000100',
> 'E' : '01000101',
> 'F' : '01000110',
> 'G' : '01000111',
> 'H' : '01001000',
> 'I' : '01001001',
> 'J' : '01001010',
> 'K' : '01001011',
> 'L' : '01001100',
> 'M' : '01001101',
> 'N' : '01001110',
> 'O' : '01001111',
> 'P' : '01010000',
> 'Q' : '01010001',
> 'R' : '01010010',
> 'S' : '01010011',
> 'T' : '01010100',
> 'U' : '01010101',
> 'V' : '01010110',
> 'W' : '01010111',
> 'X' : '01011000',
> 'Y' : '01011001',
> 'Z' : '01011010',
> 'a' : '01100001',
> 'b' : '01100010',
> 'c' : '01100011',
> 'd' : '01100100',
> 'e' : '01100101',
> 'f' : '01100110',
> 'g' : '01100111',
> 'h' : '01101000',
> 'i' : '01101001',
> 'j' : '01101010',
> 'k' : '01101011',
> 'l' : '01101100',
> 'm' : '01101101',
> 'n' : '01101110',
> 'o' : '01101111',
> 'p' : '01110000',
> 'q' : '01110001',
> 'r' : '01110010',
> 's' : '01110011',
> 't' : '01110100',
> 'u' : '01110101',
> 'v' : '01110110',
> 'w' : '01110111',
> 'x' : '01111000',
> 'y' : '01111001',
> 'z' : '01111010',
> ' ' : '00100000',
> '!' : '00100001',
> "\\" : '00100010',
> '#' : '00100011',
> '$' : '00100100',
> '%' : '00100101',
> '&' : '00100110',
> "'" : '00100111',
> '(' : '00101000',
> ')' : '00101001',
> '*' : '00101010',
> '+' : '00101011',
> ',' : '00101100',
> '-' : '00101101',
> '.' : '00101110',
> '/' : '00101111',
> ':' : '00111010',
> ';' : '00111011',
> '<' : '00111100',
> '=' : '00111101',
> '>' : '00111110',
> '?' : '00111111',
> '@' : '01000000',
> '[' : '01011011',
> ']' : '01011101',
> '^' : '01011110',
> '_' : '01011111',
> '`' : '01100000',
> '{' : '01111011',
> '|' : '01111100',
> '}' : '01111101',
> '~' : '01111110',
> '?' : '10000000',
> '?' : '10100001',
> '?' : '10100010',
> '?' : '10100011',
> '?' : '10100100',
> '?' : '10100101',
> '?' : '10100110',
> '?' : '10100111',
> '?' : '10101000',
> '?' : '10101001',
> '?' : '10101010',
> '?' : '10101011',
> '?' : '10101100',
> '?' : '10101110',
> '?' : '10101111',
> '?' : '10110000',
> '?' : '10110001',
> '?' : '10110010',
> '?' : '10110011',
> '?' : '10110100',
> '?' : '10110101',
> '?' : '10110110',
> '?' : '10110111',
> '?' : '10111000',
> '?' : '10111001',
> '?' : '10111010',
> '?' : '10111011',
> '?' : '10111100',
> '?' : '10111101',
> '?' : '01111110',
> '?' : '10111111',
> '?' : '11000000',
> '?' : '11000001',
> '?' : '11000010',
> '?' : '11000011',
> '?' : '11000100',
> '?' : '11000101',
> '?' : '11000110',
> '?' : '11000111',
> '?' : '11001000',
> '?' : '11001001',
> '?' : '11001010',
> '?' : '11001011',
> '?' : '11001100',
> '?' : '11001101',
> '?' : '11001110',
> '?' : '11001111',
> '?' : '11010000',
> '?' : '11010001',
> '?' : '11010010',
> '?' : '11010011',
> '?' : '11010100',
> '?' : '11010101',
> '?' : '11010110',
> '?' : '11010111',
> '?' : '11011000',
> '?' : '11011001',
> '?' : '11011010',
> '?' : '11011011',
> '?' : '11011100',
> '?' : '11011101',
> '?' : '11011110',
> '?' : '11011111',
> '?' : '11100000',
> '?' : '11100001',
> '?' : '11100010',
> '?' : '11100011',
> '?' : '11100100',
> '?' : '11100101',
> '?' : '11100110',
> '?' : '11100111',
> '?' : '11101000',
> '?' : '11101001',
> '?' : '11101010',
> '?' : '11101011',
> '?' : '11101100',
> '?' : '11101101',
> '?' : '11101110',
> '?' : '11101111',
> '?' : '11110000',
> '?' : '11110001',
> '?' : '11110010',
> '?' : '11110011',
> '?' : '11110100',
> '?' : '11110101',
> '?' : '11110110',
> '?' : '11110111',
> '?' : '11111000',
> '?' : '11111001',
> '?' : '11111010',
> '?' : '11111011',
> '?' : '11111100',
> '?' : '11111101',
> '?' : '11111110',
> '?' : '11111111',
> '0' : '00110000',
> '1' : '00110001',
> '2' : '00110010',
> '3' : '00110011',
> '4' : '00110100',
> '5' : '00110101',
> '6' : '00110110',
> '7' : '00110111',
> '8' : '00111000',
> '9' : '00111001',
> }

Holy cow! I can't believe you went to all of this work! Why write a program? 
Why not just do it all by hand?
If you can think of no other way to do it, I suggest that you look at the 
documentation for this function
ord()        which stands for 'ordinal'
and also do a search for a function that converts an integer to a binary 
string representation.

> def TransLate():
> key = 1
> fTransLaTion = chartobinary[code[0]]
> aTransLaTion = ""
> while key <= len(code) - 1:
>   TransLaTion = chartobinary[code[key]]
>   key = key + 1
>   aTransLaTion = aTransLaTion+TransLaTion
>   lTranslation = fTransLaTion+aTransLaTion
> print lTranslation
> TransLate()
> ChooSe()
> ChooSe()

A general comment: I DoN't lIkE tHe mIxeD CaSe YoU hAvE iN YouR COdE, AnD 
i'M sURe oThERs wIlL AgrEe ThAT iT mAKeS iT LeSs ReADabLe.

Okay I have to write this down so that I can follow the code in translate.
1) set key = 1, set ftrans to the binary of the first character
2) establish atrans as a string
3) loop from the second character all the way until the last using key as an 
incrementor
       4) set trans to the binary string of the character
       5) add this character to the string atrans
       6) add this whole string to the first string ftrans, then set to 
ltrans

How about:

def translate():
    trans = []
    for c in secret:
        trans.append(chartobinary[c])
    return "".join(trans)

First, establishes trans as a list. Then sets up a loop so that each time 
through, the variable 'c' is set to the next character in the *string* 
secret. (Or the list code, but as I said above, this is unnecessary). Each 
time through the loop I append the binary string of c to the end of the list 
trans. After the loop, I take every element of the list trans and combine 
them directly together into one string with this -> "".join(trans)


From alan.gauld at btinternet.com  Sun Dec 16 01:03:32 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 16 Dec 2007 00:03:32 -0000
Subject: [Tutor] binary translator
References: <BAY112-W1656FA21B4125E43A58684A3600@phx.gbl>
Message-ID: <fk1q0n$9l5$1@ger.gmane.org>


"2face xzibit" <kuffert_med_hat at hotmail.com> wrote 

> ...f you have any comments on the source code please let me know  

I'll add a few.


> def ChooSe():

Its kind of conventional to have function names start lowercase 
and use uppercase for classes. Not a rule but it helps when 
code includes both to know wwhat the names refer to...

> kN = ('n','N','no','nah')
> if xit in kN:

You could cover more options by just checking for the 
first letter being in 'nN':

if xit[0] in 'nN'

> chartobinary = {
> 'A' : '01000001',
> 'B' : '01000010',
> ...
> '9' : '00111001',

wow!
There are usually easier ways to create these kinds of lists
programmatically. Unless you have invented your own encoding 
of  course! - I didn't check...

> def TransLate():
     
> TransLate() 
> ChooSe()
> ChooSe() 

Calling ChooSe repeatedly like this is not a good idea, 
it could run into the recursion limit. You would be better 
to restructure the code to use a loop.

HTH,

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




From jonvspython at gmail.com  Sun Dec 16 14:17:32 2007
From: jonvspython at gmail.com (jon vs. python)
Date: Sun, 16 Dec 2007 14:17:32 +0100
Subject: [Tutor] Nested, line by line, file reading
Message-ID: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>

Hi everyone,
I have a file with this content:

"1
1
1
1
1
1
1
2
1
1"

I wanted a little script that would print the line containing "2" and every
line containing "1" after it. I've tried this:

>>> def p():
    f = file("prueba.txt",'r')
    for startline in f.read():
        if startline.find("2") != -1:
            print startline
            for endline in f.read():
                if endline.find("1") != -1:
                    print endline
                    break
    f.close()


>>> p()
2

I found a way for doing it.

But still I don't really understand why I don't get two "1" lines printed.
It seems that every line is read in "for startline f.read()" so "for endline
in f.read()" will start reading but find no data, am I right?

Thanks, Jon.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071216/61cd37c2/attachment.htm 

From globophobe at gmail.com  Sun Dec 16 14:38:36 2007
From: globophobe at gmail.com (Luis N)
Date: Sun, 16 Dec 2007 22:38:36 +0900
Subject: [Tutor] Nested, line by line, file reading
In-Reply-To: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
References: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
Message-ID: <c6e072940712160538w50dc4d55pd5b9ffee38e3ae30@mail.gmail.com>

On Dec 16, 2007 10:17 PM, jon vs. python <jonvspython at gmail.com> wrote:
> Hi everyone,
> I have a file with this content:
>
> "1
> 1
> 1
> 1
> 1
> 1
> 1
> 2
> 1
> 1"
>
> I wanted a little script that would print the line containing "2" and every
> line containing "1" after it. I've tried this:
>
> >>> def p():
>     f = file("prueba.txt",'r')
>     for startline in f.read():
>         if startline.find("2") != -1:
>             print startline
>             for endline in f.read():
>                 if endline.find("1") != -1:
>                     print endline
>                     break
>     f.close()
>
>
> >>> p()
> 2
>
> I found a way for doing it.
>
> But still I don't really understand why I don't get two "1" lines printed.
> It seems that every line is read in "for startline f.read()" so "for endline
> in f.read()" will start reading but find no data, am I right?
>
> Thanks, Jon.
>


Try something like:

show_ones = False

for line in f.read():
    if line.find(2) != -1 or show_ones == True:
       print line
       show_ones = True

From bgailer at alum.rpi.edu  Sun Dec 16 14:39:05 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sun, 16 Dec 2007 08:39:05 -0500
Subject: [Tutor] Nested, line by line, file reading
In-Reply-To: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
References: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
Message-ID: <47652A79.4040903@alum.rpi.edu>

jon vs. python wrote:
> Hi everyone,
> I have a file with this content:
>
> "1
> 1
> 1
> 1
> 1
> 1
> 1
> 2
> 1
> 1"
>
> I wanted a little script that would print the line containing "2" and 
> every line containing "1" after it. I've tried this:
>
> >>> def p():
>     f = file("prueba.txt",'r')
>     for startline in f.read():
>         if startline.find("2") != -1:
>             print startline
>             for endline in f.read():
>                 if endline.find("1") != -1:
>                     print endline
>                     break
>     f.close()
>
>    
> >>> p()
> 2
>
> I found a way for doing it.
>
> But still I don't really understand why I don't get two "1" lines 
> printed. It seems that every line is read in "for startline f.read()" 
> so "for endline in f.read()" will start reading but find no data, am I 
> right?
 From the manual: "read([size]) Read at most size bytes from the file 
(less if the read hits EOF before obtaining size bytes). If the size 
argument is negative or omitted, read all data until EOF is reached."

Instead use readline().

Then realize that will also consume the entire file, so a nested 
readline() will return "".


From bgailer at alum.rpi.edu  Sun Dec 16 14:44:57 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 16 Dec 2007 08:44:57 -0500
Subject: [Tutor] Nested, line by line, file reading
In-Reply-To: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
References: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
Message-ID: <47652BD9.4090107@alum.rpi.edu>

[snip]

now ponder this:

f=file("prueba.txt.log")
for startline in f:
	if startline.find("2") != -1:
		for endline in f:
			print endline
  			# etc.

From bgailer at alum.rpi.edu  Sun Dec 16 14:47:22 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sun, 16 Dec 2007 08:47:22 -0500
Subject: [Tutor] Nested, line by line, file reading
In-Reply-To: <c6e072940712160538w50dc4d55pd5b9ffee38e3ae30@mail.gmail.com>
References: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
	<c6e072940712160538w50dc4d55pd5b9ffee38e3ae30@mail.gmail.com>
Message-ID: <47652C6A.2010104@alum.rpi.edu>

Luis N wrote:
> On Dec 16, 2007 10:17 PM, jon vs. python <jonvspython at gmail.com> wrote:
>   
>> Hi everyone,
>> I have a file with this content:
>>
>> "1
>> 1
>> 1
>> 1
>> 1
>> 1
>> 1
>> 2
>> 1
>> 1"
>>
>> I wanted a little script that would print the line containing "2" and every
>> line containing "1" after it. I've tried this:
>>
>>     
>>>>> def p():
>>>>>           
>>     f = file("prueba.txt",'r')
>>     for startline in f.read():
>>         if startline.find("2") != -1:
>>             print startline
>>             for endline in f.read():
>>                 if endline.find("1") != -1:
>>                     print endline
>>                     break
>>     f.close()
>>
>>
>>     
>>>>> p()
>>>>>           
>> 2
>>
>> I found a way for doing it.
>>
>> But still I don't really understand why I don't get two "1" lines printed.
>> It seems that every line is read in "for startline f.read()" so "for endline
>> in f.read()" will start reading but find no data, am I right?
>>
>> Thanks, Jon.
>>
>>     
>
>
> Try something like:
>
> show_ones = False
>
> for line in f.read():
>     if line.find(2) != -1 or show_ones == True:
>        print line
>        show_ones = True
>   
See my post re use of readline instead of read

Also note that when testing booleans you don't need == True. Just write

if line.find(2) != -1 or show_ones:


From kent37 at tds.net  Sun Dec 16 15:33:21 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 16 Dec 2007 09:33:21 -0500
Subject: [Tutor] Nested, line by line, file reading
In-Reply-To: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
References: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
Message-ID: <47653731.9030506@tds.net>

jon vs. python wrote:
> Hi everyone,
> I have a file with this content:
> 
> "1
> 1
> 1
> 1
> 1
> 1
> 1
> 2
> 1
> 1"
> 
> I wanted a little script that would print the line containing "2" and 
> every line containing "1" after it. I've tried this:
> 
>  >>> def p():
>     f = file("prueba.txt",'r')
>     for startline in f.read():

As Bob pointed out, f.read() reads the entire file into a single string. 
Iterating over a string yields individual characters, not lines. So 
startline is actually a single character.

>         if startline.find("2") != -1:

More simply:
   if "2" in startline:

Kent

From alan.gauld at btinternet.com  Sun Dec 16 16:12:46 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 16 Dec 2007 15:12:46 -0000
Subject: [Tutor] Nested, line by line, file reading
References: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
Message-ID: <fk3f9i$vaj$1@ger.gmane.org>


"jon vs. python" <jonvspython at gmail.com> wrote in

> I wanted a little script that would print the line containing "2" 
> and every
> line containing "1" after it. I've tried this:
>
>>>> def p():
>    f = file("prueba.txt",'r')
>    for startline in f.read():
>        if startline.find("2") != -1:
>            print startline
>            for endline in f.read():
>                if endline.find("1") != -1:
>                    print endline
>                    break
>    f.close()

Its easier to iterate over the file itself

found2 = False
for line in file("prueba.txt"):
     if '2' in line: found2 = True
     if found2: print line
     else: continue

Should be close.

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  Sun Dec 16 16:38:28 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 16 Dec 2007 15:38:28 -0000
Subject: [Tutor] Nested, line by line, file reading
References: <4d070c130712160517r656032c9mcda9aa66c61d2e5@mail.gmail.com>
	<fk3f9i$vaj$1@ger.gmane.org>
Message-ID: <fk3gpo$3qi$1@ger.gmane.org>

"Alan Gauld" <alan.gauld at btinternet.com> wrote 

> found2 = False
> for line in file("prueba.txt"):
>     if '2' in line: found2 = True
>     if found2: print line
>     else: continue

Just after posting I realised it would be better to do:

found2 = False
for line in file("prueba.txt"):
    found2 = found2 or line.startswith('2')
    if found2: print line

The continue was superfluous and the if test 
less efficient that the boolean test.
line.startswith seems a more appropriate test too, 
and should be more efficient on long lines.

HTH,

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





From h.fangohr at soton.ac.uk  Sun Dec 16 21:33:02 2007
From: h.fangohr at soton.ac.uk (Hans Fangohr)
Date: Sun, 16 Dec 2007 20:33:02 +0000
Subject: [Tutor] python logging module: two handlers writing to the same
	file - okay?
In-Reply-To: <4764021D.6020707@tds.net>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
	<4763D6F3.8020905@tds.net> <4763FC66.40609@bigfoot.com>
	<4764021D.6020707@tds.net>
Message-ID: <6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>

Dear all,

thanks to everybody who replied to my question.

On 15 Dec 2007, at 16:34, Kent Johnson wrote:

> Ricardo Ar?oz wrote:
>> Kent Johnson wrote:
>>> I don't know the answer, but it has nothing to do with the logging
>>> module. The question is, can the same file reliably be opened  
>>> twice for
>>> writing in the same module.
>>
>> Well, the question would actually be if the logging module is smart
>> enough to find out that both your filehandlers are referring to  
>> the same
>> file and open it only once.
>
> A quick glance at the logging module shows that it is not that  
> smart. It
> just opens the file twice; hence my original question.
>

To summarise the situation: the logging module is not clever enough  
to detect that I am opening the same file twice. If I use 'w' as the  
opening mode, then I know (and have an example program for this) that  
the logging 'fails': I suppose this can be tracked to the first part  
of the log file being overriden when the second filehandler attempts  
to log its first message, and thus opens the file (again) in 'w' mode.

Using 'a' (append) or 'a+' (?)  *seems* to solve this problem but we  
are still short of knowing as to whether this is guaranteed to work  
(on all platforms...) or whether it just happened to be okay on Mac  
OS X and (Debian) Linux (on which I have tested this).

I think my example raises another question (in particular in context  
with openening the files in 'w' mode): would it be worth contacting  
the developers of the logging module to suggest that it
- tracks which files it writes to and
- warns if the same file is opened twice (or more ofter) using 'w'?

Alternatively, one could enhance the internal logic of the logging  
module so that it is aware of the same file being used twice (or more  
times) so that it only opens the file once, but I suppose this raises  
some other questions (if the two filehandlers have been given  
different opening modes, say 'a' and 'w', which one should it take  
when opening the file only once?). Therefore, just issueing a warning  
may be the better solution: should be easy to implement, doesn't  
change the interface, and prevents (naive) users (like myself) from  
wasting time trying to track down the problem of the beginning of the  
log file missing.

What is the recommended method to make such a suggestion to the  
python team, or the people who look after the logging module?

Many thanks,

Hans





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

--
Hans Fangohr
School of Engineering Sciences
University of Southampton
Phone: +44 (0) 238059 8345

Email: fangohr at soton.ac.uk
http://www.soton.ac.uk/~fangohr







From kent37 at tds.net  Sun Dec 16 22:42:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 16 Dec 2007 16:42:07 -0500
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
	<4763D6F3.8020905@tds.net> <4763FC66.40609@bigfoot.com>
	<4764021D.6020707@tds.net>
	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
Message-ID: <47659BAF.3050208@tds.net>

Hans Fangohr wrote:
> Dear all,
> 
> thanks to everybody who replied to my question.
> 
> On 15 Dec 2007, at 16:34, Kent Johnson wrote:
> 
>> Ricardo Ar?oz wrote:

> What is the recommended method to make such a suggestion to the python 
> team, or the people who look after the logging module?

You could post a feature request (possibly including a patch or 
suggested implementation) to the Python bug tracker:
http://www.python.org/dev/patches/

You could contact the developer directly via the feedback link here:
http://www.red-dove.com/python_logging.html

You could start a discussion on comp.lang.python.

Note: when I was researching my original answer I found a thread about a 
similar problem with shelve. The discussion was not sympathetic to the 
OP for two reasons:
- in general it's difficult to determine if the same file is being 
opened twice
- it is trying too hard to protect the programmer against himself.
http://groups.google.com/group/comp.lang.python/browse_frm/thread/4aafd9a8192cfbe7/5803ea195210a28f?hl=en&lnk=gst&q=open+file+twice#5803ea195210a28f

From ricaraoz at gmail.com  Mon Dec 17 00:27:27 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 16 Dec 2007 20:27:27 -0300
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
	<4763D6F3.8020905@tds.net> <4763FC66.40609@bigfoot.com>
	<4764021D.6020707@tds.net>
	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
Message-ID: <4765B45F.3050500@bigfoot.com>

Hans Fangohr wrote:
> Dear all,
> 
> thanks to everybody who replied to my question.
> 
> On 15 Dec 2007, at 16:34, Kent Johnson wrote:
> 
>> Ricardo Ar?oz wrote:
>>> Kent Johnson wrote:
>>>> I don't know the answer, but it has nothing to do with the logging
>>>> module. The question is, can the same file reliably be opened twice for
>>>> writing in the same module.
>>>
>>> Well, the question would actually be if the logging module is smart
>>> enough to find out that both your filehandlers are referring to the same
>>> file and open it only once.
>>
>> A quick glance at the logging module shows that it is not that smart. It
>> just opens the file twice; hence my original question.
>>
> 
> To summarise the situation: the logging module is not clever enough to
> detect that I am opening the same file twice. If I use 'w' as the
> opening mode, then I know (and have an example program for this) that
> the logging 'fails': I suppose this can be tracked to the first part of
> the log file being overriden when the second filehandler attempts to log
> its first message, and thus opens the file (again) in 'w' mode.
> 
> Using 'a' (append) or 'a+' (?)  *seems* to solve this problem but we are
> still short of knowing as to whether this is guaranteed to work (on all
> platforms...) or whether it just happened to be okay on Mac OS X and
> (Debian) Linux (on which I have tested this).
> 
> I think my example raises another question (in particular in context
> with openening the files in 'w' mode): would it be worth contacting the
> developers of the logging module to suggest that it
> - tracks which files it writes to and
> - warns if the same file is opened twice (or more ofter) using 'w'?
> 
> Alternatively, one could enhance the internal logic of the logging
> module so that it is aware of the same file being used twice (or more
> times) so that it only opens the file once, but I suppose this raises
> some other questions (if the two filehandlers have been given different
> opening modes, say 'a' and 'w', which one should it take when opening
> the file only once?). Therefore, just issueing a warning may be the
> better solution: should be easy to implement, doesn't change the
> interface, and prevents (naive) users (like myself) from wasting time
> trying to track down the problem of the beginning of the log file missing.
> 


As far as I can see, the only reason in your example program to open the
same file twice is to use two different formatters (i.e. two different
type of lines) in the same log, if you'd drop the requirement for two
different format of line in the same log (which is itself somewhat
questionable) then you could use the same handler for both loggers, thus
opening only one file.



From ricaraoz at gmail.com  Mon Dec 17 00:30:54 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 16 Dec 2007 20:30:54 -0300
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <47659BAF.3050208@tds.net>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>	<4763D6F3.8020905@tds.net>
	<4763FC66.40609@bigfoot.com>	<4764021D.6020707@tds.net>	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
	<47659BAF.3050208@tds.net>
Message-ID: <4765B52E.3090205@bigfoot.com>

Kent Johnson wrote:
> Hans Fangohr wrote:
>> Dear all,
>>
>> thanks to everybody who replied to my question.
>>
>> On 15 Dec 2007, at 16:34, Kent Johnson wrote:
>>
>>> Ricardo Ar?oz wrote:
> 
>> What is the recommended method to make such a suggestion to the python 
>> team, or the people who look after the logging module?
> 
> You could post a feature request (possibly including a patch or 
> suggested implementation) to the Python bug tracker:
> http://www.python.org/dev/patches/
> 
> You could contact the developer directly via the feedback link here:
> http://www.red-dove.com/python_logging.html
> 
> You could start a discussion on comp.lang.python.
> 
> Note: when I was researching my original answer I found a thread about a 
> similar problem with shelve. The discussion was not sympathetic to the 
> OP for two reasons:
> - in general it's difficult to determine if the same file is being 
> opened twice
> - it is trying too hard to protect the programmer against himself.
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/4aafd9a8192cfbe7/5803ea195210a28f?hl=en&lnk=gst&q=open+file+twice#5803ea195210a28f

Why should it be all or nothing. Couldn't the programmer indicate that
both handlers use the same file? For example if instead of pointing to a
file the formatter points to another formatter then it is using the same
file of the pointed formatter.
Then both your points would be answered and the module would be a little
bit better (I don't think I'll ever need that feature as I believe that
a log should have all it's lines in the same format).




From kent37 at tds.net  Mon Dec 17 02:56:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 16 Dec 2007 20:56:19 -0500
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <4765B52E.3090205@bigfoot.com>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>	<4763D6F3.8020905@tds.net>
	<4763FC66.40609@bigfoot.com>	<4764021D.6020707@tds.net>	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
	<47659BAF.3050208@tds.net> <4765B52E.3090205@bigfoot.com>
Message-ID: <4765D743.5060404@tds.net>

Ricardo Ar?oz wrote:
> Why should it be all or nothing. Couldn't the programmer indicate that
> both handlers use the same file?

It would be very easy to do this using StreamHandlers instead of 
FileHandlers. It would also be easy to make a FileHandler subclass that 
keeps a map from file name to file objects so if the same file is given 
to two instances it reuses the first one. This could be specified as the 
handler in the config file even.

Python has 'batteries included' but sometimes you have to add some 
wiring ;-)

Kent

From malexiuk at gmail.com  Mon Dec 17 03:32:53 2007
From: malexiuk at gmail.com (Mark Alexiuk)
Date: Sun, 16 Dec 2007 18:32:53 -0800
Subject: [Tutor] python links
In-Reply-To: <c4711c50712141943q5f59c664ndfa74ec6af01fb85@mail.gmail.com>
References: <c4711c50712141943q5f59c664ndfa74ec6af01fb85@mail.gmail.com>
Message-ID: <c4711c50712161832g2adc1a44gae18f7198f7bf044@mail.gmail.com>

Hi All,

I have no experience using Python in an embedded application (industrial
microcontrollers) but I'm sure it can be done and feel that Python offers
many advantages for new OOP developers over C++.

I would appreciate any suggestions on embedded processors compatible with
Python or some variant and what libraries people find useful, such as
UnitTest and Logging.

What follows are some links and excerpts I found looking for information on
this topic.

Cheers,
Mark

===========================================

*Open Embedded*

OpenEmbedded is a tool which allows developers to create a fully usable
Linux base for various embedded systems.

http://www.openembedded.org/

===========================================

*Embedded Python*

Some modern *embedded* devices have enough memory and a fast enough CPU to
run a typical Linux-based environment, for example, and running CPython on
such devices is mostly a matter of compilation (or cross-compilation) and
tuning.

Devices which could be considered as "*embedded*" by modern standards and
which can run tuned versions of CPython include the following:

   -

   [image: [WWW]] Gumstix <http://www.gumstix.org/>
   -

   FIC [image: [WWW]] Neo1973 <http://wiki.openmoko.org/wiki/Neo1973> ( [image:
   [WWW]] Python on OpenMoko <http://wiki.openmoko.org/wiki/Python>)

See also PythonForArmLinux <http://wiki.python.org/moin/PythonForArmLinux>and
Open*Embedded* <http://wiki.python.org/moin/OpenEmbedded>.

http://wiki.python.org/moin/EmbeddedPython?highlight=%28embedded%29


===========================================
Python compilers are available for some popular microcontrollers.
Pyastra[1]<http://pyastra.sourceforge.net/>compiles for all Microchip
PIC12, PIC14 and PIC16 microcontrollers.
PyMite[2]<http://pymite.python-hosting.com/wiki/>compiles for "any
device in the AVR family that has at least 64 KiB program
memory and 4 KiB RAM". PyMite also targets (some) ARM microcontrollers.
Notice that these embedded Python compilers typically can only compile a
subset of the Python language for these devices.

http://en.wikibooks.org/wiki/Embedded_Systems/Embedded_Systems_Introduction

===========================================

PyMite: A Flyweight Python Interpreter for 8-bit Architectures
http://python.fyxm.net/pycon/papers/pymite/

===========================================

*George Belotsky is a software architect who has done extensive work on high
performance Internet servers as well as hard real time and embedded systems.
His technology interests include C++, Python and Linux.*

SOURCE: http://pythonology.org/success&story=carmanah

===========================================
*Embedding Python with Boost.Python Part 1 *

Python has been called a language optimized for development speed. This puts
it in contrast with compiled languages like C and C++, which can be called
languages optimized for execution speed. This contrast between Python and
C/C++ often fuels a development methodology in Python circles: code the
application in Python, profile the application, and rewrite the performance
critical parts in C or C++. This makes the topic of developing hybrid
systems by extending Python very well covered in various Python
documentation.
SOURCE:
http://members.gamedev.net/sicrane/articles/EmbeddingPythonPart1.html

===========================================

*Java Embedded Python*
Jepp embeds CPython in Java. It is safe to use in a heavily threaded
environment, it is quite fast and its stability is a main feature and goal.

Some benefits of CPython over Java-based languages:

   - Using the native Python interpreter may mean a massive speed
   improvement over Java-based languages.
   - Python is mature so authors needn't fear the interpreter will
   suddenly change widely-used features.
   - Access to the high quality Python modules, both native and
   Python-based.
   - Compilers and assorted Python tools are as mature as the language.
   - Python is an ideal language for your business logic. It is easy to
   learn, eminently readable and generally immune to programming gotchas.


SOURCE: http://jepp.sourceforge.net/

===========================================
*DePython*

In the DePython  (Deeply Embeddable Python) project we have created a
stripped-down version of Python  that provides a platform for implementing
embedded systems in the Python language.  Specifically the DePython system
provides the following advantages of Javatm:

   - absolutely free, even for commercial use (including resale),
   - small footprint (<200K)
   - easy maintenance of software: objects and methods can be replaced
   ``on-the-fly''
   - reference counting garbage-collection giving more deterministic
   performance

Currently DePython runs on a Hitachi SH1 evaluation board with some extra
hardware.  The SH1 is a 32 bits RISC micro-controller running at 16Mhz.  T
he evaluation is equipped with 256Kb of RAM, 64Kb of ROM, two RS-232 ports,
and a number of I/O ports.

SOURCE: http://www.tucs.fi/magazin/output.php?ID=2000.N2.LilDeEmPy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071216/2c8bfbe5/attachment.htm 

From mlangford.cs03 at gtalumni.org  Mon Dec 17 04:15:31 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Sun, 16 Dec 2007 22:15:31 -0500
Subject: [Tutor] python links
In-Reply-To: <c4711c50712161832g2adc1a44gae18f7198f7bf044@mail.gmail.com>
References: <c4711c50712141943q5f59c664ndfa74ec6af01fb85@mail.gmail.com>
	<c4711c50712161832g2adc1a44gae18f7198f7bf044@mail.gmail.com>
Message-ID: <82b4f5810712161915q7e6d152akca7c10825d0e5c1f@mail.gmail.com>

Cross compiling python can be a bit of a bear. There build process has
python scripts that assume that you're building python for the machine
you are building on. There is a patch to help for that which Chris
Lambacher has recently updated:
http://whatschrisdoing.com/blog/2006/10/06/howto-cross-compile-python-25/

I've not tried it yet, as I've not had an applicable project. If you
use it, please let me know how it goes, as I love to see python on
these systems. Please keep me in the loop on this matter if you don't
mind...I like to see my two primary skill areas overlap as much as
possible.

Before Lambacher did his updates, I have had success on one Linux
platform and failure on another with the original patch.

Keep in mind the term "Embedding" in the python world means something
entirely unrelated to embedded systems. It means adding the
interpreter as a scripting language into an application, usually that
runs on a normal, desktop OS. For instance, the computer game
Civilization IV did this, so the graphics parts are written in C, and
the "game" part is written in python. It's a cool process, however
it's not what you're looking for. This will probably plague some of
your web searching and reading. I find looking for cross compiling
helps with this, as well as identifying embedded projects, such as
gumstix. If their stuff compiles on your target board, I've had some
success in the past with some of their stuff, (their buildroot I
think), although the python compile didn't work for my platform.

Disregard Jepp and Embedding Python with Boost.Python Part 1. They are
not the type of embedding you're looking for.

PyMite looks promising for the type of processor I think you're
interested in targeting (http://pymite.python-hosting.com/wiki/PyMite
is their new site). This could most likely be brought up for you by a
consultant if you don't meet sucess and then the actual application
code could then be written by you. With a little flexability on
processor, I am pretty sure you could get it running from their
description as long as you don't need floating point.

DePython doesn't appear to still be under active development (Broken
links, no visible source repository, etc). I usually run kicking and
screaming away from abandoned projects, and this looks like an
abandoned academic project to boot.

If you are going to go with a processor on which you can embed Linux,
there is a python in the buildroot tree, however buildroot can be
quite the crap shoot, depending on processor and mix of applications
(It didn't work on the last board I was using buildroot on).

         --Michael


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com



On Dec 16, 2007 9:32 PM, Mark Alexiuk <malexiuk at gmail.com> wrote:
> Hi All,
>
> I have no experience using Python in an embedded application (industrial
> microcontrollers) but I'm sure it can be done and feel that Python offers
> many advantages for new OOP developers over C++.
>
> I would appreciate any suggestions on embedded processors compatible with
> Python or some variant and what libraries people find useful, such as
> UnitTest and Logging.
>
> What follows are some links and excerpts I found looking for information on
> this topic.
>
> Cheers,
> Mark
>
> ===========================================
>
> Open Embedded
>
>  OpenEmbedded is a tool which allows developers to create a fully usable
> Linux base for various embedded systems.
>
> http://www.openembedded.org/
>
> ===========================================
>
> Embedded Python
>
>
> Some modern embedded devices have enough memory and a fast enough CPU to run
> a typical Linux-based environment, for example, and running CPython on such
> devices is mostly a matter of compilation (or cross-compilation) and tuning.
>
> Devices which could be considered as "embedded" by modern standards and
> which can run tuned versions of CPython include the following:
>
>
>  Gumstix
>
>
>  FIC Neo1973 ( Python on OpenMoko)
>
> See also PythonForArmLinux and OpenEmbedded.
>  http://wiki.python.org/moin/EmbeddedPython?highlight=%28embedded%29
>
>
> ===========================================
> Python compilers are available for some popular microcontrollers. Pyastra
> [1] compiles for all Microchip PIC12, PIC14 and PIC16 microcontrollers.
> PyMite [2] compiles for "any device in the AVR family that has at least 64
> KiB program memory and 4 KiB RAM". PyMite also targets (some) ARM
> microcontrollers. Notice that these embedded Python compilers typically can
> only compile a subset of the Python language for these devices.
>
> http://en.wikibooks.org/wiki/Embedded_Systems/Embedded_Systems_Introduction
>
> ===========================================
>
> PyMite: A Flyweight Python Interpreter for 8-bit
> Architectureshttp://python.fyxm.net/pycon/papers/pymite/
>
> ===========================================
>
>  George Belotsky is a software architect who has done extensive work on high
> performance Internet servers as well as hard real time and embedded systems.
> His technology interests include C++, Python and Linux.
>
> SOURCE: http://pythonology.org/success&story=carmanah
>
> ===========================================
> Embedding Python with Boost.Python Part 1
>
>
>  Python has been called a language optimized for development speed. This
> puts it in contrast with compiled languages like C and C++, which can be
> called languages optimized for execution speed. This contrast between Python
> and C/C++ often fuels a development methodology in Python circles: code the
> application in Python, profile the application, and rewrite the performance
> critical parts in C or C++. This makes the topic of developing hybrid
> systems by extending Python very well covered in various Python
> documentation.SOURCE:
> http://members.gamedev.net/sicrane/articles/EmbeddingPythonPart1.html
>
>
> ===========================================
>
> Java Embedded Python Jepp embeds CPython in Java. It is safe to use in a
> heavily threaded environment, it is quite fast and its stability is a main
> feature and goal.
>
> Some benefits of CPython over Java-based languages:
> Using the native Python interpreter may mean a massive speed improvement
> over Java-based languages.
> Python is mature so authors needn't fear the interpreter will suddenly
> change widely-used features.
> Access to the high quality Python modules, both native and Python-based.
> Compilers and assorted Python tools are as mature as the language.
> Python is an ideal language for your business logic. It is easy to learn,
> eminently readable and generally immune to programming gotchas.
> SOURCE: http://jepp.sourceforge.net/
>
> ===========================================
> DePython
>
>
> In the DePython  (Deeply Embeddable Python) project we have created a
> stripped-down version of Python  that provides a platform for implementing
> embedded systems in the Python language.  Specifically the DePython system
> provides the following advantages of Javatm:
> absolutely free, even for commercial use (including resale),
> small footprint (<200K)
> easy maintenance of software: objects and methods can be replaced
> ``on-the-fly''
> reference counting garbage-collection giving more deterministic performance
> Currently DePython runs on a Hitachi SH1 evaluation board with some extra
> hardware.  The SH1 is a 32 bits RISC micro-controller running at 16Mhz.  T
> he evaluation is equipped with 256Kb of RAM, 64Kb of ROM, two RS-232 ports,
> and a number of I/O ports.
>
> SOURCE: http://www.tucs.fi/magazin/output.php?ID=2000.N2.LilDeEmPy
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From h.fangohr at soton.ac.uk  Mon Dec 17 10:43:39 2007
From: h.fangohr at soton.ac.uk (Hans Fangohr)
Date: Mon, 17 Dec 2007 09:43:39 +0000 (GMT)
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <4765B45F.3050500@bigfoot.com>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
	<4763D6F3.8020905@tds.net> <4763FC66.40609@bigfoot.com>
	<4764021D.6020707@tds.net>
	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
	<4765B45F.3050500@bigfoot.com>
Message-ID: <Pine.OSX.4.61.0712170938280.21405@jarjar.kk.soton.ac.uk>

>>> Ricardo Ar?oz wrote:
>>>> Kent Johnson wrote:
>>>>> I don't know the answer, but it has nothing to do with the logging
>>>>> module. The question is, can the same file reliably be opened twice for
>>>>> writing in the same module.
>>>>
>>>> Well, the question would actually be if the logging module is smart
>>>> enough to find out that both your filehandlers are referring to the same
>>>> file and open it only once.
>>>
>>> A quick glance at the logging module shows that it is not that smart. It
>>> just opens the file twice; hence my original question.
>>>
>>
>> To summarise the situation: the logging module is not clever enough to
>> detect that I am opening the same file twice. If I use 'w' as the
>> opening mode, then I know (and have an example program for this) that
>> the logging 'fails': I suppose this can be tracked to the first part of
>> the log file being overriden when the second filehandler attempts to log
>> its first message, and thus opens the file (again) in 'w' mode.
>>
>> Using 'a' (append) or 'a+' (?)  *seems* to solve this problem but we are
>> still short of knowing as to whether this is guaranteed to work (on all
>> platforms...) or whether it just happened to be okay on Mac OS X and
>> (Debian) Linux (on which I have tested this).
>>
>> I think my example raises another question (in particular in context
>> with openening the files in 'w' mode): would it be worth contacting the
>> developers of the logging module to suggest that it
>> - tracks which files it writes to and
>> - warns if the same file is opened twice (or more ofter) using 'w'?
>>
>> Alternatively, one could enhance the internal logic of the logging
>> module so that it is aware of the same file being used twice (or more
>> times) so that it only opens the file once, but I suppose this raises
>> some other questions (if the two filehandlers have been given different
>> opening modes, say 'a' and 'w', which one should it take when opening
>> the file only once?). Therefore, just issueing a warning may be the
>> better solution: should be easy to implement, doesn't change the
>> interface, and prevents (naive) users (like myself) from wasting time
>> trying to track down the problem of the beginning of the log file missing.
>>
>
>
> As far as I can see, the only reason in your example program to open the
> same file twice is to use two different formatters (i.e. two different
> type of lines) in the same log, 
Absolutely right.

> if you'd drop the requirement for two
> different format of line in the same log (which is itself somewhat
> questionable) then you could use the same handler for both loggers, thus
> opening only one file.

True.

FYI: The reason for wanting to use two different file formats is this:
we have a somewhat larger project (http://nmag.soton.ac.uk) where we
combine high-level Python code with low-level Objective Caml code (and
a number of libraries). We would like to use the Python-logging module
to log all sorts of messages coming from various parts of the code. In
particular, we find having the line number (and function name if the
python version provides this) useful information in the log messages
(which can bedone for Python code issueing log messages). However,
this information cannot be obtained from the OCaml code; thus we do
not want to waste space in the log messages, and therefore we'd like
to use different formatters.

I'll reply to Ken's email in a minute, and I think that closes my query.

Best wishes,

Hans


From h.fangohr at soton.ac.uk  Mon Dec 17 10:46:31 2007
From: h.fangohr at soton.ac.uk (Hans Fangohr)
Date: Mon, 17 Dec 2007 09:46:31 +0000 (GMT)
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <4765D743.5060404@tds.net>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>
	<4763D6F3.8020905@tds.net> <4763FC66.40609@bigfoot.com>
	<4764021D.6020707@tds.net>
	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>
	<47659BAF.3050208@tds.net>
	<4765B52E.3090205@bigfoot.com> <4765D743.5060404@tds.net>
Message-ID: <Pine.OSX.4.61.0712170943520.21405@jarjar.kk.soton.ac.uk>

> Ricardo Ar?oz wrote:
>> Why should it be all or nothing. Couldn't the programmer indicate that
>> both handlers use the same file?
>
> It would be very easy to do this using StreamHandlers instead of
> FileHandlers. It would also be easy to make a FileHandler subclass that
> keeps a map from file name to file objects so if the same file is given
> to two instances it reuses the first one. This could be specified as the
> handler in the config file even.

This is probably just the right suggestion (subclassing FileHandler,
including a map of files and overriding the open() method).

I realise that our requirements are somewhat special (needing
different formatters for one file), and that it maybe unwise trying to
'protect' the programmer from himself.

On the positive side: while the logging module is not clever enough to provide the discussed functionality, it is easy to understand (and extend).

> Python has 'batteries included' but sometimes you have to add some
> wiring ;-)

Thanks to everybody who contributed to this; I think we have  found a good solution.

Regards,

Hans




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


From ricaraoz at gmail.com  Mon Dec 17 11:56:17 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 17 Dec 2007 07:56:17 -0300
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <Pine.OSX.4.61.0712170938280.21405@jarjar.kk.soton.ac.uk>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>	<4763D6F3.8020905@tds.net>
	<4763FC66.40609@bigfoot.com>	<4764021D.6020707@tds.net>	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>	<4765B45F.3050500@bigfoot.com>
	<Pine.OSX.4.61.0712170938280.21405@jarjar.kk.soton.ac.uk>
Message-ID: <476655D1.10507@bigfoot.com>

Hans Fangohr wrote:
>>>> Ricardo Ar?oz wrote:
>>>>> Kent Johnson wrote:
>>>>>> I don't know the answer, but it has nothing to do with the logging
>>>>>> module. The question is, can the same file reliably be opened
>>>>>> twice for
>>>>>> writing in the same module.
>>>>>
>>>>> Well, the question would actually be if the logging module is smart
>>>>> enough to find out that both your filehandlers are referring to the
>>>>> same
>>>>> file and open it only once.
>>>>
>>>> A quick glance at the logging module shows that it is not that
>>>> smart. It
>>>> just opens the file twice; hence my original question.
>>>>
>>>
>>> To summarise the situation: the logging module is not clever enough to
>>> detect that I am opening the same file twice. If I use 'w' as the
>>> opening mode, then I know (and have an example program for this) that
>>> the logging 'fails': I suppose this can be tracked to the first part of
>>> the log file being overriden when the second filehandler attempts to log
>>> its first message, and thus opens the file (again) in 'w' mode.
>>>
>>> Using 'a' (append) or 'a+' (?)  *seems* to solve this problem but we are
>>> still short of knowing as to whether this is guaranteed to work (on all
>>> platforms...) or whether it just happened to be okay on Mac OS X and
>>> (Debian) Linux (on which I have tested this).
>>>
>>> I think my example raises another question (in particular in context
>>> with openening the files in 'w' mode): would it be worth contacting the
>>> developers of the logging module to suggest that it
>>> - tracks which files it writes to and
>>> - warns if the same file is opened twice (or more ofter) using 'w'?
>>>
>>> Alternatively, one could enhance the internal logic of the logging
>>> module so that it is aware of the same file being used twice (or more
>>> times) so that it only opens the file once, but I suppose this raises
>>> some other questions (if the two filehandlers have been given different
>>> opening modes, say 'a' and 'w', which one should it take when opening
>>> the file only once?). Therefore, just issueing a warning may be the
>>> better solution: should be easy to implement, doesn't change the
>>> interface, and prevents (naive) users (like myself) from wasting time
>>> trying to track down the problem of the beginning of the log file
>>> missing.
>>>
>>
>>
>> As far as I can see, the only reason in your example program to open the
>> same file twice is to use two different formatters (i.e. two different
>> type of lines) in the same log, 
> Absolutely right.
> 
>> if you'd drop the requirement for two
>> different format of line in the same log (which is itself somewhat
>> questionable) then you could use the same handler for both loggers, thus
>> opening only one file.
> 
> True.
> 
> FYI: The reason for wanting to use two different file formats is this:
> we have a somewhat larger project (http://nmag.soton.ac.uk) where we
> combine high-level Python code with low-level Objective Caml code (and
> a number of libraries). We would like to use the Python-logging module
> to log all sorts of messages coming from various parts of the code. In
> particular, we find having the line number (and function name if the
> python version provides this) useful information in the log messages
> (which can bedone for Python code issueing log messages). However,
> this information cannot be obtained from the OCaml code; thus we do
> not want to waste space in the log messages, and therefore we'd like
> to use different formatters.
> 
> I'll reply to Ken's email in a minute, and I think that closes my query.
> 
> Best wishes,
> 
> Hans
> 

One last thing Hans. If you are concerned about the space the log files
will use maybe it would be interesting to check out the zlib module
which could be used to compress your log strings before sending them to
the logging module, then a utility to read the modules would close the
cycle (caveat: I've never done this, just a crazy idea, but... what if
it works?).
Best of luck.

Ricardo

From h.fangohr at soton.ac.uk  Mon Dec 17 12:31:31 2007
From: h.fangohr at soton.ac.uk (Hans Fangohr)
Date: Mon, 17 Dec 2007 11:31:31 +0000
Subject: [Tutor] python logging module: two handlers writing to the same
	file - okay?
In-Reply-To: <476655D1.10507@bigfoot.com>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>	<4763D6F3.8020905@tds.net>
	<4763FC66.40609@bigfoot.com>	<4764021D.6020707@tds.net>	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>	<4765B45F.3050500@bigfoot.com>
	<Pine.OSX.4.61.0712170938280.21405@jarjar.kk.soton.ac.uk>
	<476655D1.10507@bigfoot.com>
Message-ID: <225987F1-0713-4040-9D28-10D2E95D7185@soton.ac.uk>

HI Riccardo,

>>>
>>> As far as I can see, the only reason in your example program to  
>>> open the
>>> same file twice is to use two different formatters (i.e. two  
>>> different
>>> type of lines) in the same log,
>> Absolutely right.
>>
>>> if you'd drop the requirement for two
>>> different format of line in the same log (which is itself somewhat
>>> questionable) then you could use the same handler for both  
>>> loggers, thus
>>> opening only one file.
>>
>> True.
>>
>> FYI: The reason for wanting to use two different file formats is  
>> this:
>> we have a somewhat larger project (http://nmag.soton.ac.uk) where we
>> combine high-level Python code with low-level Objective Caml code  
>> (and
>> a number of libraries). We would like to use the Python-logging  
>> module
>> to log all sorts of messages coming from various parts of the  
>> code. In
>> particular, we find having the line number (and function name if the
>> python version provides this) useful information in the log messages
>> (which can bedone for Python code issueing log messages). However,
>> this information cannot be obtained from the OCaml code; thus we do
>> not want to waste space in the log messages, and therefore we'd like
>> to use different formatters.
>>
>> I'll reply to Ken's email in a minute, and I think that closes my  
>> query.
>>
>> Best wishes,
>>
>> Hans
>>
>
> One last thing Hans. If you are concerned about the space the log  
> files
> will use maybe it would be interesting to check out the zlib module
> which could be used to compress your log strings before sending  
> them to
> the logging module, then a utility to read the modules would close the
> cycle (caveat: I've never done this, just a crazy idea, but... what if
> it works?).

Apologies, I wasn't clear: just wanted to be nice to the user and  
avoid getting "(unknown)" entries in the log messages for the line  
number and the function name which pushes the useful message further  
to the right.

If we are talking compression, I guess you could inherit from the  
RotatingFileHandler and modify such that you gzip the rotated log files.

> Best of luck.
>
Many thanks,

Hans





From kent37 at tds.net  Mon Dec 17 12:44:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 17 Dec 2007 06:44:55 -0500
Subject: [Tutor] python logging module: two handlers writing to the same
 file - okay?
In-Reply-To: <Pine.OSX.4.61.0712170938280.21405@jarjar.kk.soton.ac.uk>
References: <Pine.OSX.4.61.0712150642001.18348@jarjar.kk.soton.ac.uk>	<4763D6F3.8020905@tds.net>
	<4763FC66.40609@bigfoot.com>	<4764021D.6020707@tds.net>	<6C48D630-DFC2-41F7-A41E-6B587F3F7882@soton.ac.uk>	<4765B45F.3050500@bigfoot.com>
	<Pine.OSX.4.61.0712170938280.21405@jarjar.kk.soton.ac.uk>
Message-ID: <47666137.3050003@tds.net>

Hans Fangohr wrote:
> FYI: The reason for wanting to use two different file formats is this:
> we have a somewhat larger project (http://nmag.soton.ac.uk) where we
> combine high-level Python code with low-level Objective Caml code (and
> a number of libraries). We would like to use the Python-logging module
> to log all sorts of messages coming from various parts of the code. In
> particular, we find having the line number (and function name if the
> python version provides this) useful information in the log messages
> (which can bedone for Python code issueing log messages). However,
> this information cannot be obtained from the OCaml code; thus we do
> not want to waste space in the log messages, and therefore we'd like
> to use different formatters.

Perhaps you could write a formatter that holds two different format 
strings and selects between them based on whether the line number is 
available.

Kent

From earlylightpublishing at yahoo.com  Mon Dec 17 21:16:00 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Mon, 17 Dec 2007 12:16:00 -0800 (PST)
Subject: [Tutor] Bound To Be A Typo
Message-ID: <208320.1227.qm@web45101.mail.sp1.yahoo.com>

Okay I copied this code directly from a book (author Michael Dawson) and it's not working.  I'm sure I've missed something obvious like the spacing or something but I've been staring at it for 10 minutes and I can't see it.  I'll put the code and error message below.  Can someone else spot the problem?
   
  class Critter(object):
    """A virtual pet"""
    def ___init___(self, name):
        print "A new critter has been born!"
        self.name = name
  
    def __str__(self):
        rep = "Critter object\n"
        rep += "name: " + self.name + "\n"
        return rep
  
    def talk(self):
        print "Hi, I'm", self.name, "\n"
  #main
crit1 = Critter("Poochie")
crit1.talk()
   
  Here's the error message:
   
  Traceback (most recent call last):
  File "C:/Python25/attributecrit.py", line 15, in <module>
    crit1 = Critter("Poochie")
TypeError: default __new__ takes no parameters
   

       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071217/4fa32746/attachment.htm 

From std3rr at gmail.com  Mon Dec 17 21:19:41 2007
From: std3rr at gmail.com (Joshua Simpson)
Date: Mon, 17 Dec 2007 12:19:41 -0800
Subject: [Tutor] Bound To Be A Typo
In-Reply-To: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
Message-ID: <3ed9caa10712171219m2410aa68xdc3b02ed9955e639@mail.gmail.com>

On Dec 17, 2007 12:16 PM, earlylight publishing <
earlylightpublishing at yahoo.com> wrote:

>
> class Critter(object):
>     """A virtual pet"""
>     def ___init___(self, name):
>         print "A new critter has been born!"
>
>

You're using 3 underscores before and after 'init'.  The constructor for
Python classes is '__init__' not '___init___'


-- 
-
http://stderr.ws/
"Insert pseudo-insightful quote here." - Some Guy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071217/a197fe68/attachment.htm 

From mlangford.cs03 at gtalumni.org  Mon Dec 17 21:22:03 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 17 Dec 2007 15:22:03 -0500
Subject: [Tutor] Bound To Be A Typo
In-Reply-To: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
Message-ID: <82b4f5810712171222v1aa95356i1a0abf5814e36ba4@mail.gmail.com>

Its "under under", not "under under under" before and after init

         --Michael

On 12/17/07, earlylight publishing <earlylightpublishing at yahoo.com> wrote:
> Okay I copied this code directly from a book (author Michael Dawson) and
> it's not working.  I'm sure I've missed something obvious like the spacing
> or something but I've been staring at it for 10 minutes and I can't see it.
> I'll put the code and error message below.  Can someone else spot the
> problem?
>
> class Critter(object):
>     """A virtual pet"""
>     def ___init___(self, name):
>         print "A new critter has been born!"
>         self.name = name
>
>     def __str__(self):
>         rep = "Critter object\n"
>         rep += "name: " + self.name + "\n"
>         return rep
>
>     def talk(self):
>         print "Hi, I'm", self.name, "\n"
> #main
> crit1 = Critter("Poochie")
> crit1.talk()
>
> Here's the error message:
>
> Traceback (most recent call last):
>   File "C:/Python25/attributecrit.py", line 15, in <module>
>     crit1 = Critter("Poochie")
> TypeError: default __new__ takes no parameters
>
>
>  ________________________________
> Looking for last minute shopping deals? Find them fast with Yahoo! Search.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From kent37 at tds.net  Mon Dec 17 21:25:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 17 Dec 2007 15:25:37 -0500
Subject: [Tutor] Bound To Be A Typo
In-Reply-To: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
Message-ID: <4766DB41.9040901@tds.net>

earlylight publishing wrote:

> class Critter(object):
>     """A virtual pet"""
>     def ___init___(self, name):

Too many underscores, just use two before and two behind, i.e. __init__

Kent

From goldwamh at slu.edu  Mon Dec 17 21:27:41 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Mon, 17 Dec 2007 14:27:41 -0600
Subject: [Tutor]  Bound To Be A Typo
In-Reply-To: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
Message-ID: <18278.56253.796501.565585@euclid.slu.edu>


You've inadvertently used three underscores around __init__ rather
than two, and therefore you are not really defining __init__ but
instead are relying upon the inherited one from object (which takes no
parameters).

With regard,
Michael

On Monday December 17, 2007, earlylight publishing wrote: 

>    Okay I copied this code directly from a book (author Michael Dawson) and it's not working.  I'm sure I've missed something obvious like the spacing or something but I've been staring at it for 10 minutes and I can't see it.  I'll put the code and error message below.  Can someone else spot the problem?
>       
>      class Critter(object):
>        """A virtual pet"""
>        def ___init___(self, name):
>            print "A new critter has been born!"
>            self.name = name
>      
>        def __str__(self):
>            rep = "Critter object\n"
>            rep += "name: " + self.name + "\n"
>            return rep
>      
>        def talk(self):
>            print "Hi, I'm", self.name, "\n"
>      #main
>    crit1 = Critter("Poochie")
>    crit1.talk()
>       
>      Here's the error message:
>       
>      Traceback (most recent call last):
>      File "C:/Python25/attributecrit.py", line 15, in <module>
>        crit1 = Critter("Poochie")
>    TypeError: default __new__ takes no parameters


From alan.gauld at btinternet.com  Mon Dec 17 21:33:07 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 17 Dec 2007 20:33:07 -0000
Subject: [Tutor] Bound To Be A Typo
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
Message-ID: <fk6me8$vru$1@ger.gmane.org>

Your init method has 3 underscores each side, it should be 2.
(As all the magic methods in Python do)

The result is the init is not recognised as an initialiser and
the default object.new method is called. as the messaage
says it takes no parameters...

HTH,

Alan G.

"earlylight publishing" <earlylightpublishing at yahoo.com> wrote in 
message news:208320.1227.qm at web45101.mail.sp1.yahoo.com...
> Okay I copied this code directly from a book (author Michael Dawson) 
> and it's not working.  I'm sure I've missed something obvious like 
> the spacing or something but I've been staring at it for 10 minutes 
> and I can't see it.  I'll put the code and error message below.  Can 
> someone else spot the problem?
>
>  class Critter(object):
>    """A virtual pet"""
>    def ___init___(self, name):
>        print "A new critter has been born!"
>        self.name = name
>
>    def __str__(self):
>        rep = "Critter object\n"
>        rep += "name: " + self.name + "\n"
>        return rep
>
>    def talk(self):
>        print "Hi, I'm", self.name, "\n"
>  #main
> crit1 = Critter("Poochie")
> crit1.talk()
>
>  Here's the error message:
>
>  Traceback (most recent call last):
>  File "C:/Python25/attributecrit.py", line 15, in <module>
>    crit1 = Critter("Poochie")
> TypeError: default __new__ takes no parameters
>
>
>
> ---------------------------------
> Looking for last minute shopping deals?  Find them fast with Yahoo! 
> Search.


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


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



From earlylightpublishing at yahoo.com  Mon Dec 17 21:42:31 2007
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Mon, 17 Dec 2007 12:42:31 -0800 (PST)
Subject: [Tutor] Bound To Be A Typo Thank You
In-Reply-To: <18278.56253.796501.565585@euclid.slu.edu>
Message-ID: <698473.9717.qm@web45105.mail.sp1.yahoo.com>

I have no idea why I did that either.  I know perfectly well it's supposed to be 2 underscores!  Thanks to everyone who spotted the problem.  

"Michael H. Goldwasser" <goldwamh at slu.edu> wrote:  
You've inadvertently used three underscores around __init__ rather
than two, and therefore you are not really defining __init__ but
instead are relying upon the inherited one from object (which takes no
parameters).

With regard,
Michael

On Monday December 17, 2007, earlylight publishing wrote: 

> Okay I copied this code directly from a book (author Michael Dawson) and it's not working. I'm sure I've missed something obvious like the spacing or something but I've been staring at it for 10 minutes and I can't see it. I'll put the code and error message below. Can someone else spot the problem?
> 
> class Critter(object):
> """A virtual pet"""
> def ___init___(self, name):
> print "A new critter has been born!"
> self.name = name
> 
> def __str__(self):
> rep = "Critter object\n"
> rep += "name: " + self.name + "\n"
> return rep
> 
> def talk(self):
> print "Hi, I'm", self.name, "\n"
> #main
> crit1 = Critter("Poochie")
> crit1.talk()
> 
> Here's the error message:
> 
> Traceback (most recent call last):
> File "C:/Python25/attributecrit.py", line 15, in 
> crit1 = Critter("Poochie")
> TypeError: default __new__ takes no parameters



       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071217/923166bf/attachment-0001.htm 

From jmorcombe at westnet.com.au  Tue Dec 18 02:44:30 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Tue, 18 Dec 2007 10:44:30 +0900
Subject: [Tutor] Something I don't understand
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
	<82b4f5810712171222v1aa95356i1a0abf5814e36ba4@mail.gmail.com>
Message-ID: <001501c84117$8958a380$6a00a8c0@ASC000E7B84CF9F>

Below, "student_seats" is a list of the class "student".

Why does this code set every student.row to zero when there is only one 
student in the list with row > 5?
It still sets them all to zero if I change the test to ">200" when there are 
no student.rows > 200.
But if I change the test to "<1" then nothing gets set to zero.


Jim


class student:
     def __init__ (self, name, row, column):
             self.name = name
             self.row = row
             self.column = column



for student in student_seats:
        print student.name, "row = ", student.row, "column = ", 
student.column
                if student.row > 5:
                        student.row = 0
         print student.name, "row = ", student.row, "column = ", 
student.column


From jmorcombe at westnet.com.au  Tue Dec 18 03:50:54 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Tue, 18 Dec 2007 11:50:54 +0900
Subject: [Tutor] Oops:
Message-ID: <000a01c84121$1a3f9580$6a00a8c0@ASC000E7B84CF9F>

I solved my last problem.  The data was string data and of course  '1' is > 5.

Now, if I take int(string) the code will work, except it crashes out when the data is null.  

student.row = int(student.row)
ValueError: invalid literal for int() with base 10: ''

What is the easiest and recomended way of turning the strings into numerics?

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071218/20cd8ba2/attachment.htm 

From john at fouhy.net  Tue Dec 18 04:34:17 2007
From: john at fouhy.net (John Fouhy)
Date: Tue, 18 Dec 2007 16:34:17 +1300
Subject: [Tutor] Oops:
In-Reply-To: <000a01c84121$1a3f9580$6a00a8c0@ASC000E7B84CF9F>
References: <000a01c84121$1a3f9580$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <5e58f2e40712171934s45bef93ar5d172ebaa7390aad@mail.gmail.com>

On 18/12/2007, Jim Morcombe <jmorcombe at westnet.com.au> wrote:
> Now, if I take int(string) the code will work, except it crashes out when
> the data is null.
>
> student.row = int(student.row)
> ValueError: invalid literal for int() with base 10: ''
>
> What is the easiest and recomended way of turning the strings into numerics?

It doesn't crash -- it just throws an exception.  Exceptions are a big
part of python; you should learn to love them :-)

As an example, you could do this:

try:
  student.row = int(student.row)
except ValueError:
  student.row = None

(assuming that setting student.row to None is the appropriate thing to
do when it's blank)

-- 
John.

From keridee at jayco.net  Tue Dec 18 15:44:14 2007
From: keridee at jayco.net (Tiger12506)
Date: Tue, 18 Dec 2007 09:44:14 -0500
Subject: [Tutor] Something I don't understand
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com><82b4f5810712171222v1aa95356i1a0abf5814e36ba4@mail.gmail.com>
	<001501c84117$8958a380$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <001a01c84184$7b02aac0$6efce004@jslaptop>

> Below, "student_seats" is a list of the class "student".
>
> Why does this code set every student.row to zero when there is only one
> student in the list with row > 5?
> It still sets them all to zero if I change the test to ">200" when there 
> are
> no student.rows > 200.
> But if I change the test to "<1" then nothing gets set to zero.
>
>
> Jim
>
>
> class student:
>     def __init__ (self, name, row, column):
>             self.name = name
>             self.row = row
>             self.column = column
>
>
>
> for student in student_seats:
>        print student.name, "row = ", student.row, "column = ",
> student.column
>                if student.row > 5:
>                        student.row = 0
>         print student.name, "row = ", student.row, "column = ",
> student.column

Probably a naming clash. You have student defined as a class, yet when you 
run the for loop, student is named for each instance of that class in the 
list. Python is most likely getting confused when you say student.row = 0, 
thinking that you mean All student classes' rows set to zero. At any rate, 
it's a bad idea to mix names like that. 


From timmichelsen at gmx-topmail.de  Tue Dec 18 17:44:57 2007
From: timmichelsen at gmx-topmail.de (Tim Michelsen)
Date: Tue, 18 Dec 2007 16:44:57 +0000 (UTC)
Subject: [Tutor] detecting a change in a iterable object (list, array,
	etc.)
References: <fifo3d$6no$1@ger.gmane.org> <474B7404.6010309@tds.net>
Message-ID: <loom.20071218T163858-427@post.gmane.org>

Hello,
> A list comprehension will work for this. If data is a list of triples of 
> (year, month, volume) then this will give you a list of the 1997 triples:
> 
> data1997 = [ item for item in data if item[0]==1997 ]

I tried your code out (see below).

Here is the output:


[]
[]
[]
[]
[]
[1990, 0, 1, -18.0]
[1990, 0, 2, -0.5]
[1990, 0, 3, -14.0]
[1990, 0, 4, -21.0]

How do I avoid the []?

What whould be the easiest way to save this list (without the "[]") into a file
and append a newline after each row?

Thanks for your help in advance,
Timmie

Here's the code:
#!/usr/bin/env python
# currently used modules
import csv

# SOME VARIABLES
#~ stattion_name = 'Sosan'
input_file_name = '../data/filter_test_data.csv'
output_file_name = '../data/filter_test_data_result.csv'

# prepare files
input_file = open(input_file_name, 'r')
output_file = open(output_file_name ,'w')
header = u"Year, Month, Day, Hour_of_day [h], values, \n"
input_data = csv.reader(input_file, delimiter=';')

#~ skip the first rows
line1 = input_file.readline()
line2 = input_file.readline()

#~ write the header
output_file.write(header.encode('utf-8'))

counter = 0
value_col = 6
for line in input_data:
    #~ print line
    #~ year month day temp_3hr
    year = int(line[1])
    month = int(line[2])-1
    day = int(line[3])
    value = float(line[6])*0.5
    compact_list = [year, month, day, value]
    res_rows = [ item for item in compact_list if compact_list[0] == 1990 ]
    print res_rows
input_file.close()
output_file.close()





From remco at gerlich.nl  Tue Dec 18 18:21:15 2007
From: remco at gerlich.nl (Remco Gerlich)
Date: Tue, 18 Dec 2007 18:21:15 +0100
Subject: [Tutor] Something I don't understand
In-Reply-To: <001501c84117$8958a380$6a00a8c0@ASC000E7B84CF9F>
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>
	<82b4f5810712171222v1aa95356i1a0abf5814e36ba4@mail.gmail.com>
	<001501c84117$8958a380$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <7ae3ca10712180921s2cf24ea1y95873b34a5d80735@mail.gmail.com>

On Dec 18, 2007 2:44 AM, Jim Morcombe <jmorcombe at westnet.com.au> wrote:

> Below, "student_seats" is a list of the class "student".


How do you create the list?

And yes, the naming is confusing, but I believe that only masks the class,
it shouldn't cause this problem.

Remco Gerlich
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071218/2a0ad722/attachment.htm 

From alan.gauld at btinternet.com  Tue Dec 18 19:01:41 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 18 Dec 2007 18:01:41 -0000
Subject: [Tutor] detecting a change in a iterable object (list, array,
	etc.)
References: <fifo3d$6no$1@ger.gmane.org> <474B7404.6010309@tds.net>
	<loom.20071218T163858-427@post.gmane.org>
Message-ID: <fk91u5$2q9$1@ger.gmane.org>


"Tim Michelsen" <timmichelsen at gmx-topmail.de> wrote


>> A list comprehension will work for this. If data is a list of 
>> triples of
>> (year, month, volume) then this will give you a list of the 1997 
>> triples:
>>
>> data1997 = [ item for item in data if item[0]==1997 ]

Note4 that for this to work it assumes a *list of triples*

> I tried your code out (see below).

> for line in input_data:
>    #~ print line
>    #~ year month day temp_3hr
>    year = int(line[1])
>    month = int(line[2])-1
>    day = int(line[3])
>    value = float(line[6])*0.5
>    compact_list = [year, month, day, value]

You are overwriting the same list with a new set of values so your
final list is just the last set of 4 values. I suspect you meant to 
have

compact_list.append( (year,month,day,value) )

>    res_rows = [ item for item in compact_list if compact_list[0] == 
> 1990 ]

And this becomes the same as the original suggestion

    res_rows = [ item for item in compact_list if item[0] == 1990 ]

If I understand what you are trying to do...

HTH,

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



From geekomancerone at gmail.com  Tue Dec 18 20:21:46 2007
From: geekomancerone at gmail.com (Michael Schultz)
Date: Tue, 18 Dec 2007 13:21:46 -0600
Subject: [Tutor] Application Tutorials
Message-ID: <9a326b160712181121w3d226990i890ac514dcecf5e0@mail.gmail.com>

Hello everyone.

I'm one of those people stuck in that odd space between total noob and
partially competent :)

What I'm looking for are nicely structured intermediate tutorials that focus
on creating actual applications, even if fairly useless :) But mainly
something that can give me an understanding of how you can structure an app.

I hope this isn't an arcane request, but I've been having problems finding
tutes like this.

Thanks in advance!


~Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071218/378b8400/attachment.htm 

From kent37 at tds.net  Tue Dec 18 20:37:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Dec 2007 14:37:13 -0500
Subject: [Tutor] Application Tutorials
In-Reply-To: <9a326b160712181121w3d226990i890ac514dcecf5e0@mail.gmail.com>
References: <9a326b160712181121w3d226990i890ac514dcecf5e0@mail.gmail.com>
Message-ID: <47682169.7080508@tds.net>

Michael Schultz wrote:

> What I'm looking for are nicely structured intermediate tutorials that 
> focus on creating actual applications, even if fairly useless :) But 
> mainly something that can give me an understanding of how you can 
> structure an app.

Not tutorials, but application skeletons:
http://www.artima.com/weblogs/viewpost.jsp?thread=4829
http://aspn.activestate.com/ASPN/search_results/index?cx=005567415255730122040%3A9qxhdmxv2eq&cof=FORID%3A9&q=+skeleton+site%3Ahttp%3A%2F%2Faspn.activestate.com%2FASPN%2FCookbook%2FPython&sa.x=0&sa.y=0&category=#1072

HTH,
Kent

From brunson at brunson.com  Tue Dec 18 21:48:56 2007
From: brunson at brunson.com (Eric Brunson)
Date: Tue, 18 Dec 2007 13:48:56 -0700
Subject: [Tutor] Something I don't understand
In-Reply-To: <001501c84117$8958a380$6a00a8c0@ASC000E7B84CF9F>
References: <208320.1227.qm@web45101.mail.sp1.yahoo.com>	<82b4f5810712171222v1aa95356i1a0abf5814e36ba4@mail.gmail.com>
	<001501c84117$8958a380$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <47683238.4040206@brunson.com>

Jim Morcombe wrote:
> Below, "student_seats" is a list of the class "student".
>
> Why does this code set every student.row to zero when there is only one 
> student in the list with row > 5?
> It still sets them all to zero if I change the test to ">200" when there are 
> no student.rows > 200.
> But if I change the test to "<1" then nothing gets set to zero.
>
>
> Jim
>
>
> class student:
>      def __init__ (self, name, row, column):
>              self.name = name
>              self.row = row
>              self.column = column
>
>
>
> for student in student_seats:
>   

Try making your index variable (student) something that is not the same 
name as the class.

>         print student.name, "row = ", student.row, "column = ", 
> student.column
>                 if student.row > 5:
>                         student.row = 0
>          print student.name, "row = ", student.row, "column = ", 
> student.column
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From adam.jtm30 at gmail.com  Wed Dec 19 03:03:46 2007
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Wed, 19 Dec 2007 02:03:46 +0000
Subject: [Tutor] Required method to make foo(*Vector(0,0,0)) work.
Message-ID: <be4fbf920712181803j322b5566lff97ed3667d5ff7e@mail.gmail.com>

I want to be able to get the values for my vector class but I don't know
what method you need to get the * thing to work ie how to make it a sequence
i think. Anybody know how to do this?
Thanks in advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071219/e45f23b2/attachment.htm 

From deliberatus at verizon.net  Wed Dec 19 03:07:35 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Tue, 18 Dec 2007 21:07:35 -0500
Subject: [Tutor] MAKING MONEY WITH OUR PYTHON CODE-A YULE GIFT TO ALL
Message-ID: <47687CE7.40302@verizon.net>

OK, who's a large customer base? Folk i the world running around with laptops,
non geek business folk. they knowfrom Adam when it comes to hand installing code.

So when we write things hard to install, who buys it? not very many. A few geeks maybe.
So we need to make our code easy to install and use if we want to sell much of it
to real no kidding non geek customers.

So I started learning the inno free windows installer. It's good, and it is free.

To practice and learn, I wrote an installer for the very nice and robust but totally
manual install tinyweb http server. And in classic refuse to give upmanner, finally
succeeded.

It works, and is located on the web HERE:
http://www.tinylist.org/tinyweb193Asetup.exe
So anyone can have a small good utility server in their windows computer.

SO WHAT?

So now all that fine python code has a ready windows market is so what.

(And I can start marketing my windows wiki, which requires a server for it to talk through.)

Happy Yule, one and all. Thanks for helping me to learn python.

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From kent37 at tds.net  Wed Dec 19 03:28:31 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 18 Dec 2007 21:28:31 -0500
Subject: [Tutor] Required method to make foo(*Vector(0,0,0)) work.
In-Reply-To: <be4fbf920712181803j322b5566lff97ed3667d5ff7e@mail.gmail.com>
References: <be4fbf920712181803j322b5566lff97ed3667d5ff7e@mail.gmail.com>
Message-ID: <476881CF.1080904@tds.net>

Adam Bark wrote:
> I want to be able to get the values for my vector class but I don't know 
> what method you need to get the * thing to work ie how to make it a 
> sequence i think. Anybody know how to do this?

I'm not a very good mind reader!

What vector class are you talking about? What are you trying to do with 
it? Why do you need a sequence?

Some context, maybe some code you have tried and the error messages you 
got, would be very helpful.

Kent

From john at fouhy.net  Wed Dec 19 03:42:48 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 19 Dec 2007 15:42:48 +1300
Subject: [Tutor] Required method to make foo(*Vector(0,0,0)) work.
In-Reply-To: <be4fbf920712181803j322b5566lff97ed3667d5ff7e@mail.gmail.com>
References: <be4fbf920712181803j322b5566lff97ed3667d5ff7e@mail.gmail.com>
Message-ID: <5e58f2e40712181842t3496c12bmfe22a1af46822a6a@mail.gmail.com>

On 19/12/2007, Adam Bark <adam.jtm30 at gmail.com> wrote:
> I want to be able to get the values for my vector class but I don't know
> what method you need to get the * thing to work ie how to make it a sequence
> i think. Anybody know how to do this?
> Thanks in advance.

If you're confused about python's *args / **kwargs syntax, this post I
wrote a while ago might help:
http://mail.python.org/pipermail/tutor/2007-April/053725.html

Otherwise, as Kent says, we need more information.

-- 
John.

From adam.jtm30 at gmail.com  Wed Dec 19 04:02:17 2007
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Wed, 19 Dec 2007 03:02:17 +0000
Subject: [Tutor] Required method to make foo(*Vector(0,0,0)) work.
In-Reply-To: <5e58f2e40712181842t3496c12bmfe22a1af46822a6a@mail.gmail.com>
References: <be4fbf920712181803j322b5566lff97ed3667d5ff7e@mail.gmail.com>
	<5e58f2e40712181842t3496c12bmfe22a1af46822a6a@mail.gmail.com>
Message-ID: <be4fbf920712181902r554179ccm8086cce6119f9d17@mail.gmail.com>

On 19/12/2007, John Fouhy <john at fouhy.net> wrote:
>
> On 19/12/2007, Adam Bark <adam.jtm30 at gmail.com> wrote:
> > I want to be able to get the values for my vector class but I don't know
> > what method you need to get the * thing to work ie how to make it a
> sequence
> > i think. Anybody know how to do this?
> > Thanks in advance.
>
> If you're confused about python's *args / **kwargs syntax, this post I
> wrote a while ago might help:
> http://mail.python.org/pipermail/tutor/2007-April/053725.html
>
> Otherwise, as Kent says, we need more information.
>
> --
> John.
>

Sorry I wasn't quite sure how to explain it it's a vector class i've written
myself.
I've worked it out now, I was using a vector as part of a quaternion and
wanted to
be able to pass a vector or individual numbers so it seemed the easiest way
to be
able to use the *sequence syntax. Apparently you have to have to have a
__getitem__ method for it to work.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071219/186638c6/attachment.htm 

From jmorcombe at westnet.com.au  Wed Dec 19 02:54:56 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Wed, 19 Dec 2007 10:54:56 +0900
Subject: [Tutor] Placing entire Application inside a class
Message-ID: <008601c841ea$a34f6020$6a00a8c0@ASC000E7B84CF9F>

I have just read through "Creating a GUI in Python - by Dakota Lemaster"

In it, Dakota recomends placing the entire application within a class.

Why is this so?  Surely in many cases you end up with a constructor for the class that is cumbersome and complex?

Is this a recomended Python programming technique?

http://student-iat.ubalt.edu/sde/students/lemaster/COSC330/Final/sec4_AppClass.html


Why is this so?  Surely in many cases you end up with a constructor for the class that is cumbersome and complex?

Is this a recomended Python programming technique?

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071219/8e7d0fbc/attachment.htm 

From keridee at jayco.net  Wed Dec 19 05:03:02 2007
From: keridee at jayco.net (Tiger12506)
Date: Tue, 18 Dec 2007 23:03:02 -0500
Subject: [Tutor] Placing entire Application inside a class
References: <008601c841ea$a34f6020$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <002301c841f4$11019080$c6fce004@jslaptop>

It is helpful for GUI applications because of what it says about halfway 
down the page, within __init__ you can bind certain messages to methods of 
the class.

I would not say that it is recommended pers? but I'm sure that there are 
those out there that cannot write a program without putting it into a class. 
And yet there are those out there who cannot write a program without making 
it all functional in nature. Do what feels right to you.

This sort of thing is very popular in C++ because of the way MFC is 
structured, but no one here likes MFC right? ;-)

As I said, do what you like, just as long as it doesn't get messy.



----- Original Message ----- 
From: "Jim Morcombe" <jmorcombe at westnet.com.au>
To: "python tutor mailing list" <tutor at python.org>
Sent: Tuesday, December 18, 2007 8:54 PM
Subject: [Tutor] Placing entire Application inside a class


I have just read through "Creating a GUI in Python - by Dakota Lemaster"

In it, Dakota recomends placing the entire application within a class.

Why is this so?  Surely in many cases you end up with a constructor for the 
class that is cumbersome and complex?

Is this a recomended Python programming technique?

http://student-iat.ubalt.edu/sde/students/lemaster/COSC330/Final/sec4_AppClass.html


Why is this so?  Surely in many cases you end up with a constructor for the 
class that is cumbersome and complex?

Is this a recomended Python programming technique?

Jim



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


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


From keridee at jayco.net  Wed Dec 19 05:08:42 2007
From: keridee at jayco.net (Tiger12506)
Date: Tue, 18 Dec 2007 23:08:42 -0500
Subject: [Tutor] Required method to make foo(*Vector(0,0,0)) work.
References: <be4fbf920712181803j322b5566lff97ed3667d5ff7e@mail.gmail.com><5e58f2e40712181842t3496c12bmfe22a1af46822a6a@mail.gmail.com>
	<be4fbf920712181902r554179ccm8086cce6119f9d17@mail.gmail.com>
Message-ID: <004101c841f4$db02d240$c6fce004@jslaptop>

> Sorry I wasn't quite sure how to explain it it's a vector class i've 
> written
> myself.
> I've worked it out now, I was using a vector as part of a quaternion and
> wanted to
> be able to pass a vector or individual numbers so it seemed the easiest 
> way
> to be
> able to use the *sequence syntax. Apparently you have to have to have a
> __getitem__ method for it to work.

Actually I think you can define a __list__ method. Hmmm. A quick python doc 
check shows that I lied. Nevermind. Please disregard this email. Or I 
suppose I could just not send it. But then again, I would have wasted all of 
this time writing this. Gee. What to do? Hmmm.... hmm... I think it's 
getting late. Yeah, I think you have the __getitem__ idea right. 


From alan.gauld at btinternet.com  Wed Dec 19 09:25:21 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 19 Dec 2007 08:25:21 -0000
Subject: [Tutor] Placing entire Application inside a class
References: <008601c841ea$a34f6020$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <fkakhi$bfu$1@ger.gmane.org>

"Jim Morcombe" <jmorcombe at westnet.com.au> wrote

> In it, Dakota recomends placing the entire application within a 
> class.
> Why is this so?  Surely in many cases you end up with a constructor
> for the class that is cumbersome and complex?

This is a very common OOP technique, especially in languages which
only support objects, like Java and SmallTalk. Indeed some OOP purists
would claim that its the only way to wsrite a pure OOP application.

The constructor should not be very complex in a well constructed OOP
program because it should only consist of processing any startup args
and then the creation of a few top level objects. And without a top
level class this would be done in some kind of initialisation function
anyhow. Usually the App class will have a Run method or similar
so that the module code looks like:

#### module here

class MyApp:
     def __init__(...)
          # process sys.argv
          # create top level classes as attributes
     def run(...)
         # control logic for application

if __name__ == '__main__':
     MyApp().run()

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

The advantage is that it is relatively easy to create  variations of 
the
program by subclassing the application. The disadvantage is that you
don't often sub class applications in practice! (At least in my 
experience)

> Is this a recomended Python programming technique?

I've never seen it recommended for Python in general, but it is quite
common, particularly in GUI apps. Indeed it is the recommend way for
wxPython where you must create an Application class or use the built
in SimpleApp class,

HTH,

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



From kent37 at tds.net  Wed Dec 19 13:26:03 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 19 Dec 2007 07:26:03 -0500
Subject: [Tutor] Placing entire Application inside a class
In-Reply-To: <008601c841ea$a34f6020$6a00a8c0@ASC000E7B84CF9F>
References: <008601c841ea$a34f6020$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <47690DDB.9050602@tds.net>

Jim Morcombe wrote:
> I have just read through "Creating a GUI in Python - by Dakota Lemaster"
>  
> In it, Dakota recomends placing the entire application within a class.
>  
> Why is this so?  Surely in many cases you end up with a constructor for 
> the class that is cumbersome and complex?

Many GUI frameworks (though not Tkinter) include an application class 
that you must instantiate and to start the application's event loop. It 
is convenient to subclass the framework's application class for your own 
initialization.

Event callbacks for button presses, etc, generally must access some 
shared state, either the app's data model or other GUI elements or both. 
Shared state requires either global variables or a class instance to 
hold the state. Here again, an app class is useful.

In my experience most apps don't have that many constructor arguments. 
If there are many options, usually some kind of settings object is 
created and used by the app.

> Is this a recomended Python programming technique?

For GUI programs it works well. For non-GUI programs classes may not be 
needed at all, it depends on the requirements of the program. One of the 
strengths of Python is that it allows different programming styles, you 
can pick the one that fits the problem and your preferences.

> http://student-iat.ubalt.edu/sde/students/lemaster/COSC330/Final/sec4_AppClass.html

In TicTacToe.py, notice that the event handler labelClicked() accesses 
self.labelList and self.gameOver. This is an example of shared state.

The reset button is bound to a nested function; I think this would be 
better written as another method of the class also.

Kent

From sammandandy at googlemail.com  Wed Dec 19 11:08:12 2007
From: sammandandy at googlemail.com (Samm and Andy)
Date: Wed, 19 Dec 2007 10:08:12 +0000
Subject: [Tutor] Condensed python2.5 cheat sheet
Message-ID: <4768ED8C.3010803@googlemail.com>

Hi people,

I've a competent programmer friend who I'm trying to convert to the ways 
of python and I was wondering if people could recommend a decent cheat 
sheet for python 2.5.
He know how to program but just needs the syntax to become pythonic

Thanks

Andy


From kent37 at tds.net  Wed Dec 19 13:34:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 19 Dec 2007 07:34:38 -0500
Subject: [Tutor] Condensed python2.5 cheat sheet
In-Reply-To: <4768ED8C.3010803@googlemail.com>
References: <4768ED8C.3010803@googlemail.com>
Message-ID: <47690FDE.6020805@tds.net>

Samm and Andy wrote:
> Hi people,
> 
> I've a competent programmer friend who I'm trying to convert to the ways 
> of python and I was wondering if people could recommend a decent cheat 
> sheet for python 2.5.
> He know how to program but just needs the syntax to become pythonic

Maybe one of these?
http://rgruet.free.fr/
http://www.python.org/doc/QuickRef.html
http://www.limsi.fr/Individu/pointal/python/pqrc/

Also Python in a Nutshell has a good, brief introduction to the language.

Good luck!
Kent

From jeff at san-dc.com  Wed Dec 19 14:23:06 2007
From: jeff at san-dc.com (Jeff Johnson)
Date: Wed, 19 Dec 2007 06:23:06 -0700
Subject: [Tutor] Condensed python2.5 cheat sheet
In-Reply-To: <4768ED8C.3010803@googlemail.com>
References: <4768ED8C.3010803@googlemail.com>
Message-ID: <1198070586.6429.3.camel@HPLAPTOPUBUNTU>

There is an excellent book for programmers from other languages.  Dive
Into Python.  http://www.diveintopython.org/toc/index.html

Jeff

On Wed, 2007-12-19 at 10:08 +0000, Samm and Andy wrote:
> Hi people,
> 
> I've a competent programmer friend who I'm trying to convert to the ways 
> of python and I was wondering if people could recommend a decent cheat 
> sheet for python 2.5.
> He know how to program but just needs the syntax to become pythonic
> 
> Thanks
> 
> Andy
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From alan.gauld at btinternet.com  Wed Dec 19 16:06:01 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 19 Dec 2007 15:06:01 -0000
Subject: [Tutor] Condensed python2.5 cheat sheet
References: <4768ED8C.3010803@googlemail.com>
Message-ID: <fkbc0q$otf$1@ger.gmane.org>


"Samm and Andy" <sammandandy at googlemail.com> wrote

> of python and I was wondering if people could recommend a decent 
> cheat
> sheet for python 2.5.

There is a quick reference linked on the Python web site:

Here is the URL:

http://rgruet.free.fr/PQR25/PQR2.5.html

However I'd still recommend an afternoon going through the official
tutorial which introduces the idioms of Python aswell as the features
and syntax.


HTH,


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



From tetsuo2k6 at web.de  Wed Dec 19 19:14:40 2007
From: tetsuo2k6 at web.de (Paul Schewietzek)
Date: Wed, 19 Dec 2007 19:14:40 +0100
Subject: [Tutor] Handling MySQLdb exceptions
Message-ID: <47695F90.8090705@web.de>

Hi there!

I'm writing a script that inserts data from a .csv file into a 
MySQL-Database.

Actually, it works fine (the data make it into the database correctly), 
however everytime it runs it raises an exception coming from the 
MySQLdb-module.

Here's the code:

--------------------------------------------------------------
#!/usr/bin/env python

import MySQLdb
import sys

if len(sys.argv) <> 2:
         print("""Usage: put_data_into_pool <well formatted .csv-file>
                         Columns need to be:
                         title, firstname, lastname, street, number of 
house, postal code, city, phone number""")
         sys.exit(0)

tabelle = open(sys.argv[1], "r")

db = MySQLdb.connect(host="localhost", user="user", passwd="xxxxxxxx", 
db="db")

cursor = MySQLdb.cursors.Cursor(db)

line = tabelle.readline()

while line <> "":
#        try:
                 cursor.execute('INSERT INTO pool (titel, vorname, 
nachname, strasse, hausnummer, plz, ort, rufnummer, datum) VALUES (' + 
line + ');')
                 line = tabelle.readline()
#        except(_mysql_exceptions.OperationalError):
#                pass

tabelle.close()
------------------------------------------------------------------

The exception goes like this:

------------------------------------------------------------------
Traceback (most recent call last):
   File "bin/auftragserfassung/put_data_into_pool.py", line 22, in <module>
     cursor.execute('INSERT INTO pool (titel, vorname, nachname, 
strasse, hausnummer, plz, ort, rufnummer, datum) VALUES (' + line + ');')
   File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line 
166, in execute
     self.errorhandler(self, exc, value)
   File "/var/lib/python-support/python2.5/MySQLdb/connections.py", line 
35, in defaulterrorhandler
     raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1136, "Column count doesn't match 
value count at row 1")
-------------------------------------------------------------------

Is there any way to handle this exception? As you can see, I already 
tried it with _mysql_exceptions.OperationalError (the lines that are 
commented out), but _mysql_exceptions is not defined to Python....

Just so you don't need to wonder: The .csv-file I give to the script for 
testing is absolutely OK.

On a side note, would you think I should post this somewhere else? If 
so, where?

Any help is appreciated - I'll answer tomorrow (have to go now).

Kindest regards, Paul

From std3rr at gmail.com  Wed Dec 19 19:21:27 2007
From: std3rr at gmail.com (Joshua Simpson)
Date: Wed, 19 Dec 2007 10:21:27 -0800
Subject: [Tutor] Handling MySQLdb exceptions
In-Reply-To: <47695F90.8090705@web.de>
References: <47695F90.8090705@web.de>
Message-ID: <3ed9caa10712191021u7424cf5axa2c122ceb0d7f490@mail.gmail.com>

On Dec 19, 2007 10:14 AM, Paul Schewietzek <tetsuo2k6 at web.de> wrote:

>
> Is there any way to handle this exception? As you can see, I already
> tried it with _mysql_exceptions.OperationalError (the lines that are
> commented out), but _mysql_exceptions is not defined to Python....
>
>
"OperationalError" is contained in the MySQLdb module and thus namespace, so
you'll have to reference it like so:

except MySQLdb.OperationalError:


-- 
-
http://stderr.ws/
"Insert pseudo-insightful quote here." - Some Guy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071219/1dfb7a0a/attachment.htm 

From kent37 at tds.net  Wed Dec 19 20:39:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 19 Dec 2007 14:39:06 -0500
Subject: [Tutor] Handling MySQLdb exceptions
In-Reply-To: <47695F90.8090705@web.de>
References: <47695F90.8090705@web.de>
Message-ID: <4769735A.3060809@tds.net>

Paul Schewietzek wrote:
> Just so you don't need to wonder: The .csv-file I give to the script for 
> testing is absolutely OK.

Except that it contains data that the insert statement doesn't 
like...does it contain any blank lines? Printing 'line' in the exception 
handler would be useful.

Also this code is vulnerable to SQL injection attacks, if you don't 
trust the source of the input file you should not use this. For example 
if the file contained a line like
titel, vorname, nachname, strasse, hausnummer, plz, ort, 
rufnummer,datum); delete from pool; --
that would be bad.

From jmorcombe at westnet.com.au  Thu Dec 20 02:44:06 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Thu, 20 Dec 2007 10:44:06 +0900
Subject: [Tutor] constants, flags or whatever
Message-ID: <005601c842a9$cee3c900$6a00a8c0@ASC000E7B84CF9F>

In a program, I want to set some kind of variable or object to indicate what "mode" the program is currently in.
What is the most elegant way of doing this?

Jim
---------------------------------------------------------------------------
constant: moving = "m"
constant: inserting = "i"
constant:jumping = "j"
.
.
action = moving
.
.
.
if action == jumping:
        jumpSomewhere()
elseif action == moving:
        moveSomewhere()
elseif action == inserting:
        insertSomething()
------------------------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071220/50155295/attachment.htm 

From bhaaluu at gmail.com  Thu Dec 20 03:35:34 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 19 Dec 2007 21:35:34 -0500
Subject: [Tutor] constants, flags or whatever
In-Reply-To: <005601c842a9$cee3c900$6a00a8c0@ASC000E7B84CF9F>
References: <005601c842a9$cee3c900$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <ea979d70712191835v5cf58c43vbe1e82c91c9d90aa@mail.gmail.com>

This isn't elegant, but it is a start. My method is: get SOMETHING working,
then work from there. 8^D

"""
constant: moving = "m"
constant: inserting = "i"
constant: jumping = "j"
.
.
action = moving
.
.
.
if action == jumping:
    jumpSomewhere()
elseif action == moving:
    moveSomewhere()
elseif action == inserting:
    insertSomething()
"""
##############################
moving = False
inserting = False
jumping = False

def jumpingSomewhere():
    global jumping
    print jumping
    jumping = True
    return jumping

def insertingSomething():
    global inserting
    print inserting
    inserting = True
    return inserting

def movingSomewhere():
    global moving
    print moving
    moving = True
    return moving

jumpingSomewhere()
insertingSomething()
movingSomewhere()

print jumping
print inserting
print moving
#############################

Output:
False
False
False
True
True
True


On Dec 19, 2007 8:44 PM, Jim Morcombe <jmorcombe at westnet.com.au> wrote:
>
>
> In a program, I want to set some kind of variable or object to indicate what
> "mode" the program is currently in.
> What is the most elegant way of doing this?
>
> Jim
> ---------------------------------------------------------------------------
> constant: moving = "m"
> constant: inserting = "i"
> constant:jumping = "j"
> .
> .
> action = moving
> .
> .
> .
> if action == jumping:
>         jumpSomewhere()
> elseif action == moving:
>         moveSomewhere()
> elseif action == inserting:
>         insertSomething()
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
b h a a l u u at g m a i l dot c o m

From bgailer at alum.rpi.edu  Thu Dec 20 03:41:13 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Wed, 19 Dec 2007 21:41:13 -0500
Subject: [Tutor] constants, flags or whatever
In-Reply-To: <005601c842a9$cee3c900$6a00a8c0@ASC000E7B84CF9F>
References: <005601c842a9$cee3c900$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <4769D649.90501@alum.rpi.edu>

Jim Morcombe wrote:
> In a program, I want to set some kind of variable or object to 
> indicate what "mode" the program is currently in.
> What is the most elegant way of doing this?
>  
> Jim
> ---------------------------------------------------------------------------
> constant: moving = "m"
> constant: inserting = "i"
> constant:jumping = "j"
> .
> .
> action = moving
> .
> .
> .
> if action == jumping:
>         jumpSomewhere()
> elseif action == moving:
>         moveSomewhere()
> elseif action == inserting:
>         insertSomething()
> ------------------------------------------------------------------------
1 - I see no value in introducing variables. I'd just use string constants:

action = "moving"
.
.
if action == "jumping":

etc.


2 - It is common in Python to use a dictionary to map the constants to 
the functions instead of if-elif statements:

actions = dict( jumping = jumpSomewhere, 
		moving = moveSomewhere, 
		inserting = insertSomething)


the entire if-elif construct now becomes:

actions[action]()

adding new action-function pairs is now a lot easier.

From dkuhlman at rexx.com  Thu Dec 20 05:00:04 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 19 Dec 2007 20:00:04 -0800
Subject: [Tutor] constants, flags or whatever
In-Reply-To: <4769D649.90501@alum.rpi.edu>
References: <005601c842a9$cee3c900$6a00a8c0@ASC000E7B84CF9F>
	<4769D649.90501@alum.rpi.edu>
Message-ID: <20071220040004.GA54397@cutter.rexx.com>

On Wed, Dec 19, 2007 at 09:41:13PM -0500, bob gailer wrote:

> 1 - I see no value in introducing variables. I'd just use string constants:
> 
> action = "moving"
> .
> .
> if action == "jumping":
> 
> etc.

I agree.  But, some people do prefer something that looks a bit
like an enum.  If so, here is a Python idiom for enums:

Mode_none, Mode_moving, Mode_inserting, Mode_jumping = range(4)

action = Mode_moving

if action == Mode_jumping:
    o
    o
    o

- Dave


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

From steve at alchemy.com  Thu Dec 20 05:44:47 2007
From: steve at alchemy.com (Steve Willoughby)
Date: Wed, 19 Dec 2007 20:44:47 -0800
Subject: [Tutor] constants, flags or whatever
In-Reply-To: <20071220040004.GA54397@cutter.rexx.com>
References: <005601c842a9$cee3c900$6a00a8c0@ASC000E7B84CF9F>	<4769D649.90501@alum.rpi.edu>
	<20071220040004.GA54397@cutter.rexx.com>
Message-ID: <4769F33F.5010902@alchemy.com>

Dave Kuhlman wrote:
> On Wed, Dec 19, 2007 at 09:41:13PM -0500, bob gailer wrote:
> 
>> 1 - I see no value in introducing variables. I'd just use string constants:
>>
>> action = "moving"
>> .
>> .
>> if action == "jumping":
>>
>> etc.
> 
> I agree.  But, some people do prefer something that looks a bit
> like an enum.  If so, here is a Python idiom for enums:

One big advantage to using variables over string constants is that
there is a big danger of misspelling one of the constants and not
noticing the error.

action = "moving"
...
if action == "moveing":
   # oops, this never gets executed


if you had used variables, Python would catch the error as an
attempt to use an undefined variable:

action = MOVING
...
if action == MOVEING:  <-- error caught by python


> Mode_none, Mode_moving, Mode_inserting, Mode_jumping = range(4)
> 
> action = Mode_moving
> 
> if action == Mode_jumping:
>     o
>     o
>     o
> 
> - Dave
> 
> 



From tetsuo2k6 at web.de  Thu Dec 20 11:08:32 2007
From: tetsuo2k6 at web.de (Paul Schewietzek)
Date: Thu, 20 Dec 2007 11:08:32 +0100
Subject: [Tutor] Handling MySQLdb exceptions
In-Reply-To: <3ed9caa10712191021u7424cf5axa2c122ceb0d7f490@mail.gmail.com>
References: <47695F90.8090705@web.de>
	<3ed9caa10712191021u7424cf5axa2c122ceb0d7f490@mail.gmail.com>
Message-ID: <476A3F20.6030103@web.de>

Joshua Simpson schrieb:
> On Dec 19, 2007 10:14 AM, Paul Schewietzek <tetsuo2k6 at web.de 
> <mailto:tetsuo2k6 at web.de>> wrote:
> 
> 
>     Is there any way to handle this exception? As you can see, I already
>     tried it with _mysql_exceptions.OperationalError (the lines that are
>     commented out), but _mysql_exceptions is not defined to Python....
> 
> 
> "OperationalError" is contained in the MySQLdb module and thus 
> namespace, so you'll have to reference it like so:
> 
> except MySQLdb.OperationalError:
> 
> 
> -- 
> -
> http://stderr.ws/
> "Insert pseudo-insightful quote here." - Some Guy

Thanks a lot! It works 8D

-paul

From tetsuo2k6 at web.de  Thu Dec 20 19:00:00 2007
From: tetsuo2k6 at web.de (Paul Schewietzek)
Date: Thu, 20 Dec 2007 19:00:00 +0100
Subject: [Tutor] Handling MySQLdb exceptions
In-Reply-To: <476A5B06.90005@tds.net>
References: <47695F90.8090705@web.de> <4769735A.3060809@tds.net>
	<476A42BF.7010406@web.de> <476A5B06.90005@tds.net>
Message-ID: <476AADA0.8090106@web.de>

Kent Johnson schrieb:
> A more robust solution would be to read the file with the csv module and 
> use cursor.execute() with a proper parameter list. This lets the csv and 
> database modules correctly (un)escape the data values.
> 
> Kent
> 

WOW thanks! I never thought about that there might be a csv-module! I'm 
on my way exploring it ;)

-paul

From LockhartL at Ripon.EDU  Thu Dec 20 22:15:54 2007
From: LockhartL at Ripon.EDU (Lockhart, Luke)
Date: Thu, 20 Dec 2007 15:15:54 -0600
Subject: [Tutor] XML data reading
Message-ID: <160BF3B24FDE154DB7E0AD06FAF789F1027921C6@URANIUM.ripon.college>


Hello all,

So I'm a very novice Python programmer. I've done stuff up to the intermediate level in Microsoft flavors of BASIC and C++, but now I'm a Linux man and trying to realize my overly ambitious programming dreams with Python, mainly because I have friends who use it and because it has libraries that in general are very good at doing what I want to do.

Now, the program I'm working on would hypothetically store and read all data as XML, and yes I'm aware of the performance drawbacks and I'm willing to live with them. But I just can't figure out the various libraries that Python uses to read XML, and my friend's code doesn't help much.

Basically, what I really would like to do, without going into a lot of detail, is be able to read various tags into classes and arrays until the entire file has been read, then remove the file from memory. I first tried to use the basic Python XML libraries, and then my friend recommended SAX - but so far as I can tell, either method requires numerous lines of code to support one new tag. Is this what I'm going to have to do, or is there a simpler way?

Thanks in advance,
Luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071220/1d062eb6/attachment.htm 

From LockhartL at Ripon.EDU  Thu Dec 20 22:28:47 2007
From: LockhartL at Ripon.EDU (Lockhart, Luke)
Date: Thu, 20 Dec 2007 15:28:47 -0600
Subject: [Tutor] XML
Message-ID: <160BF3B24FDE154DB7E0AD06FAF789F1027921C7@URANIUM.ripon.college>



Hello all,

Sorry if this is a double post, I had some technical problems with subscribing to this list.

So I'm a very novice Python programmer. I've done stuff up to the intermediate level in Microsoft flavors of BASIC and C++, but now I'm a Linux man and trying to realize my overly ambitious programming dreams with Python, mainly because I have friends who use it and because it has libraries that in general are very good at doing what I want to do.

Now, the program I'm working on would hypothetically store and read all data as XML, and yes I'm aware of the performance drawbacks and I'm willing to live with them. But I just can't figure out the various libraries that Python uses to read XML, and my friend's code doesn't help much.

Basically, what I really would like to do, without going into a lot of detail, is be able to read various tags into classes and arrays until the entire file has been read, then remove the file from memory. I first tried to use the basic Python XML libraries, and then my friend recommended SAX - but so far as I can tell, either method requires numerous lines of code to support one new tag. Is this what I'm going to have to do, or is there a simpler way?

Thanks in advance,
Luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071220/f83a2421/attachment.htm 

From kent37 at tds.net  Thu Dec 20 22:46:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 20 Dec 2007 16:46:35 -0500
Subject: [Tutor] XML
In-Reply-To: <160BF3B24FDE154DB7E0AD06FAF789F1027921C7@URANIUM.ripon.college>
References: <160BF3B24FDE154DB7E0AD06FAF789F1027921C7@URANIUM.ripon.college>
Message-ID: <476AE2BB.6060105@tds.net>

Lockhart, Luke wrote:
> Now, the program I'm working on would hypothetically store and read all 
> data as XML, and yes I'm aware of the performance drawbacks and I'm 
> willing to live with them. But I just can't figure out the various 
> libraries that Python uses to read XML, and my friend's code doesn't 
> help much.
> 
> Basically, what I really would like to do, without going into a lot of 
> detail, is be able to read various tags into classes and arrays until 
> the entire file has been read, then remove the file from memory.

Do you want to create your own classes to represent the data or do you 
just want to get some kind of object model? If the latter, take a look 
at ElementTree, it is IMO the best of the included XML packages.
http://docs.python.org/lib/module-xml.etree.ElementTree.html

Kent

From mlangford.cs03 at gtalumni.org  Thu Dec 20 23:12:39 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Thu, 20 Dec 2007 17:12:39 -0500
Subject: [Tutor] XML data reading
In-Reply-To: <160BF3B24FDE154DB7E0AD06FAF789F1027921C6@URANIUM.ripon.college>
References: <160BF3B24FDE154DB7E0AD06FAF789F1027921C6@URANIUM.ripon.college>
Message-ID: <82b4f5810712201412p5de74c3ag26482b88e07e197d@mail.gmail.com>

Sax is the simplest to get started with. here is a simple example. See
http://docs.python.org/lib/content-handler-objects.html for more info
on the methods of ContentHandler. Using some list or dict of tags
you're processing such as I do in the following example will keep "tag
specific code" down to a minimum. Theoretically, you'd just have to
change the list you initialize the object with and the endElement
function to handle a new tag.

from xml import sax
from xml.sax.handler import ContentHandler
class myhandler(ContentHandler):
	def __init__(self, tagsToChirpOn=None):
        	self.last = ""
		self.info = ""
		if tagsToChirpOn is None:
               		self.chirpTags = []
         	else:
               		self.chirpTags = tagsToChirpOn


    	#then you define a start element method
	#   this is called for each open tag you see
  	def startElement(self,name,attr):
        	self.last = name
		self.info = ""
           	if name in self.chirpTags:
                	print "starting %s tag"  % name


    	#then you define a characters method, which
	#  is called on sections of text inside the
	#  tags until it is all found
    	def characters(self,content):
        	if self.last in self.chirpTags:
			self.info +=content
			
     	#then if you need to define an action to happen
	#when an end tag is hit, you write a
    	def endElement(self,name):
        	"""called at </closetag"""
		if len(self.info) > 0:
			print "In tag %s was data{{%s}}" % (self.last,self.info)
           	if name in self.chirpTags:
                	print "Now leaving the %s tag" % name

if __name__=="__main__":
     document = """
     <xml>
     	<foo>line 1
	   bars are fun
	</foo>
	<bar>line 2
	   dogs don't like celery
	</bar>
	<baz>
	   121309803124.12
	</baz>
     </xml>"""
     hand = myhandler(["bar","baz"])
     sax.parseString(document,hand)

	
You often need to build a state machine or some other stateful
tracking system to make Sax parsers do complicated things, but the
above is good enough for most things involving data. If you use the
start tag to create a new object, the characters tag to populate it
and then the endElement tag to submit the object to a greater data
structure, you can very easily build objects out of XML data of any
source. I used sax parsers most recently on parsing out REST data from
amazon.

urlib2 and sax parsers are formidable, quick technologies to perform
simple parsing needs. Look into BeautifulSoup as well:
http://www.crummy.com/software/BeautifulSoup/

                        --Michael

On Dec 20, 2007 4:15 PM, Lockhart, Luke <LockhartL at ripon.edu> wrote:
>
>
>
>
> Hello all,
>
>  So I'm a very novice Python programmer. I've done stuff up to the
> intermediate level in Microsoft flavors of BASIC and C++, but now I'm a
> Linux man and trying to realize my overly ambitious programming dreams with
> Python, mainly because I have friends who use it and because it has
> libraries that in general are very good at doing what I want to do.
>
>  Now, the program I'm working on would hypothetically store and read all
> data as XML, and yes I'm aware of the performance drawbacks and I'm willing
> to live with them. But I just can't figure out the various libraries that
> Python uses to read XML, and my friend's code doesn't help much.
>
>  Basically, what I really would like to do, without going into a lot of
> detail, is be able to read various tags into classes and arrays until the
> entire file has been read, then remove the file from memory. I first tried
> to use the basic Python XML libraries, and then my friend recommended SAX -
> but so far as I can tell, either method requires numerous lines of code to
> support one new tag. Is this what I'm going to have to do, or is there a
> simpler way?
>
>  Thanks in advance,
>  Luke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From eric at ericwalstad.com  Fri Dec 21 00:04:13 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Thu, 20 Dec 2007 15:04:13 -0800
Subject: [Tutor] XML data reading [slightly off topic/silly]
In-Reply-To: <160BF3B24FDE154DB7E0AD06FAF789F1027921C6@URANIUM.ripon.college>
References: <160BF3B24FDE154DB7E0AD06FAF789F1027921C6@URANIUM.ripon.college>
Message-ID: <476AF4ED.40808@ericwalstad.com>

Lockhart, Luke wrote:
> ...now I'm a
> Linux man and trying to realize my overly ambitious programming dreams 
> with Python
Welcome to the real world, Neo.  I'm not saying that you'll be able to 
work with XML via DOM or SAX in Python.  I'm saying that when you are 
ready, you won't have to.  :)
(with apologies to the Wachowski brothers)


 > But I just can't figure out the various
 > libraries that Python uses to read XML, and my friend's code doesn't
 > help much.
I think Google will help with many examples.  Also have a look at the 
Python Cookbook:
http://aspn.activestate.com/ASPN/Python/Cookbook/
for examples.


/me climbs onto soap box (no pun intended)
I think this might be a little off topic but my advice as you learn 
Python, considering you are parsing data and might have OOP experience, 
is to consider that there is value in simple code.  Try to keep an open 
mind and try not to use too many dots, especially if you have control 
over both ends of your data transfer.

Here's what I think is a nice example of roughly 17 lines of python code 
that elegantly parse and process a 5M record file with an impressive 
speed gain, too:
http://groups.google.com/group/comp.lang.python/msg/38a13587b6b298a2

Welcome, have fun and do post to the list when you have specific questions!

Eric.

From jmorcombe at westnet.com.au  Fri Dec 21 01:54:21 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Fri, 21 Dec 2007 09:54:21 +0900
Subject: [Tutor] re-initialising shells
Message-ID: <00f701c8436c$2819d650$6a00a8c0@ASC000E7B84CF9F>

I have had a couple of strange cases I don't understand.

I am using IDLE on Windows

My program imports some stuff from another file using the statement "from qwerty import *"

I have changed qwerty and saved it away.  I have then run my program (F5) and the program acts as if it is using an old version of qwerty.

I close down all my python windows, start it again and the changes are picked up.

What are the rules with "shells" and so on?

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071221/7da01185/attachment.htm 

From alan.gauld at btinternet.com  Fri Dec 21 09:47:24 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 21 Dec 2007 08:47:24 -0000
Subject: [Tutor] re-initialising shells
References: <00f701c8436c$2819d650$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <fkfuiu$8pc$1@ger.gmane.org>


"Jim Morcombe" <jmorcombe at westnet.com.au> wrote

> I have changed qwerty and saved it away.
> I have then run my program (F5) and the program acts as
> if it is using an old version of qwerty.

You need to "reload" the module to pick up the changes.

>>> help(reload)
Help on built-in function reload in module __builtin__:

reload(...)
    reload(module) -> module

    Reload the module.  The module must have been successfully 
imported before.
>>>

In addition there is a Restart menu option in IDLE that will 
effectively
give you a new empty shell environment if you have lots of imported 
modules.

However I'm not sure if reload will work if you use the from X import 
*
approach since that imports all of the names rather than the module 
itself.
In that case restart is probably the best bet - or switch to the safer 
import X
style.

HTH,


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



From lechtlr at yahoo.com  Fri Dec 21 17:00:41 2007
From: lechtlr at yahoo.com (lechtlr)
Date: Fri, 21 Dec 2007 08:00:41 -0800 (PST)
Subject: [Tutor] Using 'join ' function to create a string
Message-ID: <512846.88123.qm@web57904.mail.re3.yahoo.com>

Hi there,

I would like to know what is the best way to create a string object from two different lists using 'join' function. For example, I have X = ['a', 'b', 'c', 'd', 'e'] and Y = [1, 2, 3, 4, 5]. From X and Y, I want to create a string Z = 'a:1, b:2, c:3, d:4, e:5'.

Any help would greatly be appreciated.
-Lex 

  
       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071221/5a76422f/attachment.htm 

From brunson at brunson.com  Fri Dec 21 17:33:31 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 21 Dec 2007 09:33:31 -0700
Subject: [Tutor] Using 'join ' function to create a string
In-Reply-To: <512846.88123.qm@web57904.mail.re3.yahoo.com>
References: <512846.88123.qm@web57904.mail.re3.yahoo.com>
Message-ID: <476BEADB.808@brunson.com>

lechtlr wrote:
> Hi there,
>
> I would like to know what is the best way to create a string object 
> from two different lists using 'join' function. For example, I have X 
> = ['a', 'b', 'c', 'd', 'e'] and Y = [1, 2, 3, 4, 5]. From X and Y, I 
> want to create a string Z = 'a:1, b:2, c:3, d:4, e:5'.

How about something like this:

", ".join( '%s:%s' % ( x, y ) for x, y in zip( X, Y ) )

Yields:  'a:1, b:2, c:3, d:4, e:5'


> Any help would greatly be appreciated.
> -Lex
>
> ------------------------------------------------------------------------
> Looking for last minute shopping deals? Find them fast with Yahoo! 
> Search. 
> <http://us.rd.yahoo.com/evt=51734/*http://tools.search.yahoo.com/newsearch/category.php?category=shopping> 
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From dkuhlman at rexx.com  Fri Dec 21 17:51:47 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Fri, 21 Dec 2007 08:51:47 -0800
Subject: [Tutor] Using 'join ' function to create a string
In-Reply-To: <476BEADB.808@brunson.com>
References: <512846.88123.qm@web57904.mail.re3.yahoo.com>
	<476BEADB.808@brunson.com>
Message-ID: <20071221165147.GA56260@cutter.rexx.com>

On Fri, Dec 21, 2007 at 09:33:31AM -0700, Eric Brunson wrote:
> lechtlr wrote:
> > Hi there,
> >
> > I would like to know what is the best way to create a string object 
> > from two different lists using 'join' function. For example, I have X 
> > = ['a', 'b', 'c', 'd', 'e'] and Y = [1, 2, 3, 4, 5]. From X and Y, I 
> > want to create a string Z = 'a:1, b:2, c:3, d:4, e:5'.
> 
> How about something like this:
> 
> ", ".join( '%s:%s' % ( x, y ) for x, y in zip( X, Y ) )

Slick.  I believe that the argument you are passing to join() is
the result of a generator expression.  Am I right?

And, I did not know that str.join(seq) could take an iterator as
opposed to a plain sequence.  Thanks for showing us that.

Back to the original poster's problem, you could also try map() and
a lambda:

    ', '.join(map(lambda x,y: '%s:%s' % (x, y, ), X, Y))

Or, maybe unrolling it makes it more readable:

    In [31]: fn = lambda x,y: '%s:%s' % (x, y, )
    In [32]: ', '.join(map(fn, a, b))
    Out[32]: 'aa:11, bb:22, cc:33'

- Dave

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

From bgailer at alum.rpi.edu  Fri Dec 21 17:56:16 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 21 Dec 2007 11:56:16 -0500
Subject: [Tutor] Using 'join ' function to create a string
In-Reply-To: <512846.88123.qm@web57904.mail.re3.yahoo.com>
References: <512846.88123.qm@web57904.mail.re3.yahoo.com>
Message-ID: <476BF030.1040005@alum.rpi.edu>

lechtlr wrote:
> Hi there,
>
> I would like to know what is the best way to create a string object 
> from two different lists using 'join' function. For example, I have X 
> = ['a', 'b', 'c', 'd', 'e'] and Y = [1, 2, 3, 4, 5]. From X and Y, I 
> want to create a string Z = 'a:1, b:2, c:3, d:4, e:5'.

Best way? Depends on what you mean by "best".

My solution:

Z = ', '.join(i+':'+str(j) for i, j in zip(X,Y))

It's interesting to note how close your output is to a dictionary display:

dict(zip(X,Y)) -> {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

BTW is is customary in Python to start variable names with lower case 
letters (x,y,z) in this case.
Title case  is then used for Classes
CAPS is used for CONSTANTS

From dave6502 at googlemail.com  Fri Dec 21 18:03:19 2007
From: dave6502 at googlemail.com (dave selby)
Date: Fri, 21 Dec 2007 17:03:19 +0000
Subject: [Tutor] Cant write new line at end of file append
Message-ID: <f52017b60712210903o257fab50xf9aeb5d8f1ba957@mail.gmail.com>

Hi all,

I need to write a newline at the end of a string I am appending to a
file. I tried ...

journal.write('%s#%s\n' % (jpeg[:-4], self.snap_init[feed]))

The text is all there but no new line at the end .... any idea what I
am doing wrong ? ... thought \n would do it.

Cheers

Dave


-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

From christopher.henk at allisontransmission.com  Fri Dec 21 17:53:18 2007
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Fri, 21 Dec 2007 11:53:18 -0500
Subject: [Tutor] Using 'join ' function to create a string
In-Reply-To: <512846.88123.qm@web57904.mail.re3.yahoo.com>
Message-ID: <OF1D02AA75.72AA6FD9-ON852573B8.005C9688-852573B8.005CC585@gm.com>

this works for me.

Z=", ".join(["%s:%s" %(a,Y[b]) for b,a in enumerate(X)])






lechtlr <lechtlr at yahoo.com> 
Sent by: tutor-bounces at python.org
12/21/2007 11:00 AM

To
tutor at python.org
cc

Subject
[Tutor] Using 'join ' function to create a string






Hi there,

I would like to know what is the best way to create a string object from 
two different lists using 'join' function. For example, I have X = ['a', 
'b', 'c', 'd', 'e'] and Y = [1, 2, 3, 4, 5]. From X and Y, I want to 
create a string Z = 'a:1, b:2, c:3, d:4, e:5'.
Any help would greatly be appreciated.
-Lex 
 Looking for last minute shopping deals? Find them fast with Yahoo! 
Search._______________________________________________
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/20071221/fafef961/attachment.htm 

From davholla2002 at yahoo.co.uk  Fri Dec 21 18:37:15 2007
From: davholla2002 at yahoo.co.uk (David Holland)
Date: Fri, 21 Dec 2007 17:37:15 +0000 (GMT)
Subject: [Tutor] Python Challenge 2
Message-ID: <717116.11960.qm@web25609.mail.ukl.yahoo.com>

I did this and got this string :-

"i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url"
Is that the answer because it does not solve the problem when I apply it to the url.


------------------------------------------------------------------------------------------------------------------------------------
 First they came for the Danes, but I did not speak out because I am not a Dane.

       
---------------------------------
 Support the World Aids Awareness campaign this month with Yahoo! for Good
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071221/516ab954/attachment.htm 

From martin at marcher.name  Fri Dec 21 17:18:50 2007
From: martin at marcher.name (Martin Marcher)
Date: Fri, 21 Dec 2007 17:18:50 +0100
Subject: [Tutor] python CLI parser
Message-ID: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>

Hello,

could you have a short review of my CLI package.

What it provides is a simple interface to create a "shell". I'll be
using it inside a bot I'm writing to manage it.

Features:
 * pluggable commands
 * works over streams instead of stdin/stdout/stderr so it should be
network aware (right?)

"Unfeatures":
 * not documented at all, right now

Todos (for me of course, not for you, but open to suggestions):
 * import readline
 * provide <TAB> completion
 * make "CTRL+d" also a quitcommand
 * remove hardcoded quitCommands only provide defaults

Necessary interface for a command:
function(*args) returning a string (No smart output of dicts, list or suche yet)

Builtin commands are noop and and echo.

To run it do "python main.py"
To leave it use "quit" or "exit"

any comments are welcome, especially how I could make CTRL+d leave my "shell"

and I'm not looking at something that provides, I'm pretty sure
someone did a similiar thing already :)

thanks
martin

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-------------- next part --------------
A non-text attachment was scrubbed...
Name: cli.tar.bz2
Type: application/x-bzip2
Size: 2929 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20071221/12e6812e/attachment-0001.bin 

From smlltlk at jupiterlovejoy.com  Fri Dec 21 20:45:40 2007
From: smlltlk at jupiterlovejoy.com (jupiejupe)
Date: Fri, 21 Dec 2007 11:45:40 -0800 (PST)
Subject: [Tutor]  Design Outline question for personal project
Message-ID: <14460833.post@talk.nabble.com>


(please forgive the unclear thought process i am still trying to figure out
what i need done and the order there of)
i am going to set up a network of "zigbee" nodes.
when a event such as: motion movement or touch awakens node 
i want it's alert to the network to trigger a programmed response.

what i have to figure out is 
using a database maybe mysql or (cherrypy seems interesting as a http frame
(can it send pop3 or imap? do i need a database if it does?).
to store the node id's numbers and the email address i want sent.
i need that node number to send it's associated email message to me at my
account.

so i believe that the zigbee node's have id already pre-programmed
so that should not be an issuse.

once the event (i'll need to have a program to take that report? or does the
database do that already?) has been reported to the database, 
the node id should trigger an email? (do i need an email client to send that
or does sockets have some thing to do with that?) that's really all that i
can think i need which most likey means i am missing the boat.


so i figure that i need to study as well as python.
cherrypy:
          has a mini sever and database so i can use that instead of mysql?
Twisted mail?
          do i have to use all of twisted or can i just use to mail part?
socket?
          okay i will google it for some gen. info but pointers of focus can
really help
am i missing anything? 


thanks any bits of info helps just an non-cpu kinda guy with a plan.
-- 
View this message in context: http://www.nabble.com/Design-Outline-question-for-personal-project-tp14460833p14460833.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From smlltlk at jupiterlovejoy.com  Fri Dec 21 19:58:44 2007
From: smlltlk at jupiterlovejoy.com (jupiejupe)
Date: Fri, 21 Dec 2007 10:58:44 -0800 (PST)
Subject: [Tutor]  Public Python Library Code
Message-ID: <14460465.post@talk.nabble.com>


hello everyone i have just started to learn python, i know a little html, so
this is my real first language. i am finding so much wondering advice
sharing and tips, (a special nod to alan g. & kent j.) :clap:

i am wondering if there is a place a code library. i have spent way to much
time window shopping all of the message, some give me ideas (yes i am going
to be writing a program, if i get enough of a grasp). although i do count it
as study time, it's a messing place to find code, (alan, i have checked out
your site. you know your stuff but it's a full meal=)). i enjoy looking at
the different ways ya'll write the different code for the same task. i would
not mind starting a new child forum and start collecting code to jump start
a code library.
question::confused:
is that out of line? copyrights and what not, or is that okay, being this is
a public forum and those are like opinions?%-|

if anyone has any suggests i am all ears.

also if you one would like to point me in the right direct as to what i
should be focusing on in regard to my personaly project.
  
-- 
View this message in context: http://www.nabble.com/Public-Python-Library-Code-tp14460465p14460465.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From smlltlk at jupiterlovejoy.com  Fri Dec 21 20:18:34 2007
From: smlltlk at jupiterlovejoy.com (jupiejupe)
Date: Fri, 21 Dec 2007 11:18:34 -0800 (PST)
Subject: [Tutor]  Design Outline question for personal project
Message-ID: <14460833.post@talk.nabble.com>


(please forgive the unclear thought process i am still trying to figure out
what i need done and the order there of)
i am going to set up a network of "zigbee" nodes.
when a event such as: motion movement or touch awakens node 
i want it's alert to the network to trigger a programmed response.

what i have to figure out is 
using a database maybe mysql or (cherrypy seems interesting as a http frame
(can it send pop3 or imap? do i need a database if it does?).
to store the node id's numbers and the email address i want sent.
i need that node number to send it's associated email message to me at my
account.

so i believe that the zigbee node's have id already pre-programmed
so that should not be an issuse.

once the event (i'll need to have a program to take that report? or does the
database do that already?) has been reported to the database, 
the node id should trigger an email? (do i need an email client to send that
or does sockets have some thing to do with that?) that's really all that i
can think i need which most likey means i am missing the boat.


so i figure that i need to study as well as python.
databases
cherrypy?
socket?
email clients? or protocol? 
am i missing anything?
thanks any bits of info helps just an non-cpu kinda guy with a plan.
-- 
View this message in context: http://www.nabble.com/Design-Outline-question-for-personal-project-tp14460833p14460833.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From smlltlk at jupiterlovejoy.com  Fri Dec 21 20:36:04 2007
From: smlltlk at jupiterlovejoy.com (jupiejupe)
Date: Fri, 21 Dec 2007 11:36:04 -0800 (PST)
Subject: [Tutor] Design Outline question for personal project
In-Reply-To: <14460833.post@talk.nabble.com>
References: <14460833.post@talk.nabble.com>
Message-ID: <14461182.post@talk.nabble.com>




jupiejupe wrote:
> 
> so i figure that i need to study as well as python.
> 
> thanks any bits of info helps just an non-cpu kinda guy with a plan.
> 

redefining list:
cherrypy:
          has a mini sever and database so i can use that instead of mysql?
Twisted mail? 
          do i have to use all of twisted or can i just use to mail part? 
socket?
          okay i will google it
am i missing anything?
 
-- 
View this message in context: http://www.nabble.com/Design-Outline-question-for-personal-project-tp14460833p14461182.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From alan.gauld at btinternet.com  Fri Dec 21 21:17:46 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 21 Dec 2007 20:17:46 -0000
Subject: [Tutor] Python Challenge 2
References: <717116.11960.qm@web25609.mail.ukl.yahoo.com>
Message-ID: <fkh71c$ip8$1@ger.gmane.org>

"David Holland" <davholla2002 at yahoo.co.uk> wrote

>
> "i hope you didnt translate it by hand. thats what computers are 
> for.
> doing it in by hand is inefficient and that's why this text is so 
> long.
> using string.maketrans() is recommended. now apply on the url"
>
> Is that the answer because it does not solve the problem when I 
> apply it to the url.

I believe (its a while since I did the challenge) that you have solved 
it and
got to that page. However you could have solved it the hard way so the 
note
is telling you the esy way. Now apply that easy way to the url to get 
the url
of the next challenge.

At least thats how I remember it, but it is an adventure game after 
all...

Alan G. 



From alan.gauld at btinternet.com  Fri Dec 21 21:22:46 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 21 Dec 2007 20:22:46 -0000
Subject: [Tutor] Public Python Library Code
References: <14460465.post@talk.nabble.com>
Message-ID: <fkh7ao$jjd$1@ger.gmane.org>


"jupiejupe" <smlltlk at jupiterlovejoy.com> wrote

> i am wondering if there is a place a code library.

There are several.
For production code look in the standard library and
the Python "Cheeseshop" - a place fort contributed modules.
And don't forget to read the sample scripts that come with
the Python download

For sample programs and simpler projects try the Useless
Python web site. The old site (linked from the page) had a
lot of contributed short code samples. I'm not sure about the
latest incarnation.

Finally try the ActiveState site which has a Recipes section
(or Cookbook) for solving common problems (there is a paper
book containing the most common).

There are plebnty other sites too but that should be enough
to start!

i have spent way to much
> time window shopping all of the message, some give me ideas (yes i 
> am going
> to be writing a program, if i get enough of a grasp). although i do 
> count it
> as study time, it's a messing place to find code, (alan, i have 
> checked out
> your site. you know your stuff but it's a full meal=)). i enjoy 
> looking at
> the different ways ya'll write the different code for the same task. 
> i would
> not mind starting a new child forum and start collecting code to 
> jump start
> a code library.
> question::confused:
> is that out of line? copyrights and what not, or is that okay, being 
> this is
> a public forum and those are like opinions?%-|
>
> if anyone has any suggests i am all ears.
>
> also if you one would like to point me in the right direct as to 
> what i
> should be focusing on in regard to my personaly project.
>
> -- 
> View this message in context: 
> http://www.nabble.com/Public-Python-Library-Code-tp14460465p14460465.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From alan.gauld at btinternet.com  Fri Dec 21 21:29:21 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 21 Dec 2007 20:29:21 -0000
Subject: [Tutor] Design Outline question for personal project
References: <14460833.post@talk.nabble.com>
Message-ID: <fkh7n3$ko6$1@ger.gmane.org>


"jupiejupe" <smlltlk at jupiterlovejoy.com> wrote

> i am going to set up a network of "zigbee" nodes.
> when a event such as: motion movement or touch awakens node
> i want it's alert to the network to trigger a programmed response.
>
> what i have to figure out is using a database maybe mysql or

Yes, and you might find it useful to define a Node as a class.

> (cherrypy seems interesting as a http frame (can it send pop3
> or imap? do i need a database if it does?).

Yes it can do pop and imap vuia standard python pop and imap email
modules and no it doesn't need a database for email. Databases just
store data and allow you to retrieve it. (OK some have fancy 
trigger/event
mechanisms too)

> so i believe that the zigbee node's have id already pre-programmed
> so that should not be an issuse.

Sounds like it.

> once the event (i'll need to have a program to take that report? or 
> does the
> database do that already?) has been reported to the database,

You probably want a node object to retrieve the data from the database
and use that to send the email usong the standard python email 
modules.

> the node id should trigger an email? (do i need an email client to 
> send that
> or does sockets have some thing to do with that?) that's really all 
> that i
> can think i need which most likey means i am missing the boat.

Sockets are involved bt the email modules should shield you from all 
of that.

> so i figure that i need to study as well as python.
> cherrypy:
>          has a mini sever and database so i can use that instead of 
> mysql?

You could use standard CGI for this but CherryPy might make it easier.

> Twisted mail?
>          do i have to use all of twisted or can i just use to mail 
> part?
> socket?

You definitely don't need Twisted at this stage.
Standard Python email modules should do all you need.

You might want some classes and hence some OOP....

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



From keridee at jayco.net  Fri Dec 21 22:39:29 2007
From: keridee at jayco.net (Tiger12506)
Date: Fri, 21 Dec 2007 16:39:29 -0500
Subject: [Tutor] Python Challenge 2
References: <717116.11960.qm@web25609.mail.ukl.yahoo.com>
Message-ID: <003001c84419$faec9920$6efce004@jslaptop>

>I did this and got this string :-
>
> "i hope you didnt translate it by hand. thats what computers are for. 
> doing it in by hand is inefficient and that's why this text is so long. 
> using string.maketrans() is recommended. now apply on the url"
> Is that the answer because it does not solve the problem when I apply it 
> to the url.

Not to the whole url! Then it wouldn't be a url anymore! Just to ___.html 
part that is three letters long. And generally you shouldn't post answers to 
the challenges on public lists, because they can spoil it for others wanting 
to take the challenge.

JS 


From keridee at jayco.net  Fri Dec 21 22:48:56 2007
From: keridee at jayco.net (Tiger12506)
Date: Fri, 21 Dec 2007 16:48:56 -0500
Subject: [Tutor] Cant write new line at end of file append
References: <f52017b60712210903o257fab50xf9aeb5d8f1ba957@mail.gmail.com>
Message-ID: <007201c8441b$4cfca290$6efce004@jslaptop>


----- Original Message ----- 
From: "dave selby" <dave6502 at googlemail.com>
To: "Python Tutor" <tutor at python.org>
Sent: Friday, December 21, 2007 12:03 PM
Subject: [Tutor] Cant write new line at end of file append


> Hi all,
>
> I need to write a newline at the end of a string I am appending to a
> file. I tried ...
>
> journal.write('%s#%s\n' % (jpeg[:-4], self.snap_init[feed]))
>
> The text is all there but no new line at the end .... any idea what I
> am doing wrong ? ... thought \n would do it.
>
> Cheers
>
> Dave

Different operating systems deal with newline differently, and sometimes 
libraries are built upon the assumption that a particular operating system 
uses a particular style of newline. Have you tried \r\n? 


From bgailer at alum.rpi.edu  Fri Dec 21 23:52:55 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 21 Dec 2007 17:52:55 -0500
Subject: [Tutor] python CLI parser
In-Reply-To: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>
References: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>
Message-ID: <476C43C7.5020308@alum.rpi.edu>

Martin Marcher wrote:
> Hello,
>
> could you have a short review of my CLI package.
>   
.bz2???  What does that extension mean? (For us Windows folk). Or could 
you attach a simple zip file?

[snip]

From tezlo at gmx.net  Sat Dec 22 02:40:50 2007
From: tezlo at gmx.net (tezlo)
Date: Sat, 22 Dec 2007 02:40:50 +0100
Subject: [Tutor] python CLI parser
In-Reply-To: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>
References: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>
Message-ID: <20071222024050.2b88f583.tezlo@gmx.net>

"Martin Marcher" <martin at marcher.name> wrote:
> Hello,
> 
> could you have a short review of my CLI package.

Hi,
it looks alright, it's really rather tiny. For one I could do with
spaces between functions for the sake of readability. And it would
make more sense to check the callback for being a callable once - while
registering it, instead of every time it's triggered. It's good to
program defensively, especially in a dynamic language like python,
where you can hardly stop anyone (yourself) from stuffing the dict
with uncallable garbage. But in this case, you deserve the exception as
it's up to you, the programmer, to register the commands. The check
should not be necessary if you write your program correctly.

As for CTRL+D, it fires an EOF. The manual for readline() says:
> A trailing newline character is kept in the string
> An empty string is returned when EOF is encountered immediately.
but you strip() the command (in two places) and lose the chance of
checking for that very case. Hope this helps.

tezlo

From queprime at gmail.com  Sat Dec 22 04:57:00 2007
From: queprime at gmail.com (Que Prime)
Date: Fri, 21 Dec 2007 19:57:00 -0800
Subject: [Tutor] Regular Expression
In-Reply-To: <17285ccf0712211641y3f91a5d5h9ac9675f41c84511@mail.gmail.com>
References: <17285ccf0712211641y3f91a5d5h9ac9675f41c84511@mail.gmail.com>
Message-ID: <17285ccf0712211957q662ddf95uedc32c9bdde14fed@mail.gmail.com>

I need to pull the highligted data from a similar file and can't seem to get
my script to work:

Script:
import re
infile = open("filter.txt","r")
outfile = open("out.txt","w")
patt = re.compile(r"~02([\d{10}])")
for line in infile:
  m = patt.match(line)
  if m:
    outfile.write("%s\n")
infile.close()
outfile.close()


File:
200~021111001491~05070
200~021111001777~05070
200~021111001995~05090
200~021111002609~05090
200~021111002789~05070
200~012~021111004169~0
200~021111004247~05090
200~021111008623~05090
200~021111010957~05090
200~02 1111011479~05090
200~0199~021111001237~
200~021111011600~05090
200~012~02 1111022305~0
200~021111023546~05090
200~021111025427~05090
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071221/11fa842e/attachment.htm 

From goldwamh at slu.edu  Sat Dec 22 05:15:42 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Fri, 21 Dec 2007 22:15:42 -0600
Subject: [Tutor]  Regular Expression
In-Reply-To: <17285ccf0712211957q662ddf95uedc32c9bdde14fed@mail.gmail.com>
References: <17285ccf0712211641y3f91a5d5h9ac9675f41c84511@mail.gmail.com>
	<17285ccf0712211957q662ddf95uedc32c9bdde14fed@mail.gmail.com>
Message-ID: <18284.36718.610247.493621@euclid.slu.edu>


Que,

I haven't tested the script, but please note that patt.match(line)
will only succeed when the pattern is at the start of the line.  Use
patt.search(line) if you want to find the pattern anywhere within the
line.

Based on your desired highlight, you might want to use the pattern,
patt = re.compile(r"~02(\d*)~")

Also, your outfile.write command below doesn't provide any substitute
for %s.   Presumably you mean outfile.write("%s\n" % m.group(1)) .

Good luck,
Michael

On Friday December 21, 2007, Que Prime wrote: 

>    I need to pull the highligted data from a similar file and can't seem to get
>    my script to work:
>    
>    Script:
>    import re
>    infile = open("filter.txt","r")
>    outfile = open("out.txt","w")
>    patt = re.compile(r"~02([\d{10}])")
>    for line in infile:
>      m = patt.match(line)
>      if m:
>        outfile.write("%s\n")
>    infile.close()
>    outfile.close()
>    
>    
>    File:
>    200~021111001491~05070
>    200~021111001777~05070
>    200~021111001995~05090
>    200~021111002609~05090
>    200~021111002789~05070
>    200~012~021111004169~0
>    200~021111004247~05090
>    200~021111008623~05090
>    200~021111010957~05090
>    200~02 1111011479~05090
>    200~0199~021111001237~
>    200~021111011600~05090
>    200~012~02 1111022305~0
>    200~021111023546~05090
>    200~021111025427~05090



From keridee at jayco.net  Sat Dec 22 05:19:51 2007
From: keridee at jayco.net (Tiger12506)
Date: Fri, 21 Dec 2007 23:19:51 -0500
Subject: [Tutor] Regular Expression
References: <17285ccf0712211641y3f91a5d5h9ac9675f41c84511@mail.gmail.com>
	<17285ccf0712211957q662ddf95uedc32c9bdde14fed@mail.gmail.com>
Message-ID: <001701c84451$e931e4a0$05fce004@jslaptop>

>I need to pull the highligted data from a similar file and can't seem to 
>get
> my script to work:
>
> Script:
> import re
> infile = open("filter.txt","r")
> outfile = open("out.txt","w")
> patt = re.compile(r"~02([\d{10}])")

You have to allow for the characters at the beginning and end too.
Try this.
re.compile(r".*~02(\d{10})~.*")

Also outfile.write("%s\n") literally writes "%s\n"
You need this I believe

outfile.write("%s\n" % m.group(1))


> for line in infile:
>  m = patt.match(line)
>  if m:
>    outfile.write("%s\n")
> infile.close()
> outfile.close()
>
>
> File:
> 200~021111001491~05070
> 200~021111001777~05070
> 200~021111001995~05090
> 200~021111002609~05090
> 200~021111002789~05070
> 200~012~021111004169~0
> 200~021111004247~05090
> 200~021111008623~05090
> 200~021111010957~05090
> 200~02 1111011479~05090
> 200~0199~021111001237~
> 200~021111011600~05090
> 200~012~02 1111022305~0
> 200~021111023546~05090
> 200~021111025427~05090
>


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


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


From mlangford.cs03 at gtalumni.org  Sat Dec 22 05:26:55 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Fri, 21 Dec 2007 23:26:55 -0500
Subject: [Tutor] Regular Expression
In-Reply-To: <17285ccf0712211957q662ddf95uedc32c9bdde14fed@mail.gmail.com>
References: <17285ccf0712211641y3f91a5d5h9ac9675f41c84511@mail.gmail.com>
	<17285ccf0712211957q662ddf95uedc32c9bdde14fed@mail.gmail.com>
Message-ID: <82b4f5810712212026g6af37fdds57fcebfca7878a74@mail.gmail.com>

You need to pass a parameter to the string in the following line:

outfile.write("%s\n" % m.string[m.start():m.end()])

And you need to use m.search, not m.match in the line where you're
actually apply the expression to the string

 m = patt.search(line)

   --Michael

On 12/21/07, Que Prime <queprime at gmail.com> wrote:
>
>
> I need to pull the highligted data from a similar file and can't seem to get
> my script to work:
>
> Script:
> import re
> infile = open("filter.txt","r")
> outfile = open("out.txt","w")
> patt = re.compile(r"~02([\d{10}])")
> for line in infile:
>   m = patt.match(line)
>   if m:
>     outfile.write("%s\n")
> infile.close()
> outfile.close()
>
>
> File:
> 200~021111001491~05070
> 200~021111001777~05070
> 200~021111001995~05090
> 200~021111002609~05090
> 200~021111002789~05070
> 200~012~021111004169~0
>  200~021111004247~05090
> 200~021111008623~05090
> 200~021111010957~05090
> 200~02 1111011479~05090
> 200~0199~021111001237~
> 200~021111011600~05090
> 200~012~02 1111022305~0
> 200~021111023546~05090
> 200~021111025427~05090
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From kuffert_med_hat at hotmail.com  Sun Dec 23 01:09:42 2007
From: kuffert_med_hat at hotmail.com (Emil)
Date: Sun, 23 Dec 2007 01:09:42 +0100
Subject: [Tutor] Output of list
Message-ID: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>


hey

I want to be capable of converting a string into a list where all the items, in  the list, have a fixed length not equal to 1 e.g i have k = 'abcdefgh' and I want the fixed length for all the the items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh']. How do i do this?


- Emil   
_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today it's FREE!
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

From ricaraoz at gmail.com  Sun Dec 23 01:45:20 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 22 Dec 2007 21:45:20 -0300
Subject: [Tutor] Output of list
In-Reply-To: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>
References: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>
Message-ID: <476DAFA0.30609@bigfoot.com>

Emil wrote:
> hey
> 
> I want to be capable of converting a string into a list where all the items, in  the list, have a fixed length not equal to 1 e.g i have k = 'abcdefgh' and I want the fixed length for all the the items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh']. How do i do this?
> 
> 

map(''.join, zip(k[::2], k[1::2]))

From ricaraoz at gmail.com  Sun Dec 23 01:47:41 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 22 Dec 2007 21:47:41 -0300
Subject: [Tutor] Output of list
In-Reply-To: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>
References: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>
Message-ID: <476DB02D.90706@bigfoot.com>

Emil wrote:
> hey
> 
> I want to be capable of converting a string into a list where all the items, in  the list, have a fixed length not equal to 1 e.g i have k = 'abcdefgh' and I want the fixed length for all the the items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh']. How do i do this?
> 
> 

Also : [''.join(i) for i in zip(k[::2], k[1::2])]

From alan.gauld at btinternet.com  Sun Dec 23 01:31:16 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 23 Dec 2007 00:31:16 -0000
Subject: [Tutor] Output of list
References: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>
Message-ID: <fkka8n$r4a$1@ger.gmane.org>


"Emil" <kuffert_med_hat at hotmail.com> wrote

> I want to be capable of converting a string into a list where all 
> the items,
>  in  the list, have a fixed length not equal to 1

You can use list slicing to do this.
Combine with the stepsize parameter of the range function

> k = 'abcdefgh' and I want the fixed length for all the the
> items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh'].

k = 'abcdefgh'
new = []
for n in range(0,len(k),2):  # 2=stepsize
     new.append(k[n:n+2])   # use slice
print new

As a list comprehension that would be:

new = [k[n:n+2] for n in range(0,len(k),2)]

And as a more general function:

def splitStringByN(s,n):
   return [s[m:m+n] for m in range(0,len(s),n)]

Should work,

HTH,

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



From mwalsh at groktech.org  Sun Dec 23 02:25:54 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sat, 22 Dec 2007 19:25:54 -0600
Subject: [Tutor] Output of list
In-Reply-To: <476DB02D.90706@bigfoot.com>
References: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>
	<476DB02D.90706@bigfoot.com>
Message-ID: <476DB922.9010103@groktech.org>

Ricardo Ar?oz wrote:
> Emil wrote:
>> hey
>>
>> I want to be capable of converting a string into a list where all the items, in  the list, have a fixed length not equal to 1 e.g i have k = 'abcdefgh' and I want the fixed length for all the the items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh']. How do i do this?
>>
>>
> 
> Also : [''.join(i) for i in zip(k[::2], k[1::2])]

Cool use of 'zip' and extended slicing!

Just thought I would add that 'zip' truncates after the shortest
sequence, which would cause data loss for strings of odd length -- of
course, the OP may not consider this a problem.

In [1]: k = 'abcdefghi' # <- note the 'i'

In [2]: len(k)
Out[2]: 9

In [3]: [''.join(i) for i in zip(k[::2], k[1::2])]
Out[3]: ['ab', 'cd', 'ef', 'gh'] # <- 'i' is gone


HTH,
Marty






From ricaraoz at gmail.com  Sun Dec 23 06:57:13 2007
From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=)
Date: Sun, 23 Dec 2007 02:57:13 -0300
Subject: [Tutor] Output of list
In-Reply-To: <476DB922.9010103@groktech.org>
References: <BAY112-W10E78E1C0733CF9C8D8338A3580@phx.gbl>	<476DB02D.90706@bigfoot.com>
	<476DB922.9010103@groktech.org>
Message-ID: <476DF8B9.7070009@bigfoot.com>

Martin Walsh wrote:
> Ricardo Ar?oz wrote:
>> Emil wrote:
>>> hey
>>>
>>> I want to be capable of converting a string into a list where all the items, in  the list, have a fixed length not equal to 1 e.g i have k = 'abcdefgh' and I want the fixed length for all the the items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh']. How do i do this?
>>>
>>>
>> Also : [''.join(i) for i in zip(k[::2], k[1::2])]
> 
> Cool use of 'zip' and extended slicing!
> 

Thx

> Just thought I would add that 'zip' truncates after the shortest
> sequence, which would cause data loss for strings of odd length -- of
> course, the OP may not consider this a problem.
> 
> In [1]: k = 'abcdefghi' # <- note the 'i'
> 
> In [2]: len(k)
> Out[2]: 9
> 
> In [3]: [''.join(i) for i in zip(k[::2], k[1::2])]
> Out[3]: ['ab', 'cd', 'ef', 'gh'] # <- 'i' is gone
> 

Could only think of :
[''.join(i) for i in zip(k[::2], k[1::2])] + list(k)[-(len(k)%2):0:-len(k)]

But maybe it is too complicated. There should be a simpler way.



From janos.juhasz at VELUX.com  Sun Dec 23 17:52:28 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sun, 23 Dec 2007 17:52:28 +0100
Subject: [Tutor] Output of list
In-Reply-To: <mailman.9.1198407604.18928.tutor@python.org>
Message-ID: <OFE1FA4AE3.6B6F711A-ONC12573BA.005C6322-C12573BA.005CB1FC@velux.com>

Dear Emil,

> I want to be capable of converting a string into a list where all 
> the items, in  the list, have a fixed length not equal to 1 e.g i 
> have k = 'abcdefgh' and I want the fixed length for all the the 
> items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh'].
> How do i do this?

> 
> - Emil

It is nice place to use a generator:

def pairs(sliceit):
    streamlist = list(sliceit)
    streamlist.reverse()
    while streamlist:
        pair = streamlist.pop() 
        try:    pair += streamlist.pop()
        except: pass
        yield pair

## Probably it is easier to understand
def pairs2(sliceit):
    try:
        while sliceit:
            yield sliceit[:2]
            sliceit = sliceit[2:]
    except: # oops, it was odd length
        yield sliceit


print '_'.join(e for e in pairs('abcd'))
print '_'.join(e for e in pairs('abcde'))
print '_'.join(e for e in pairs2('abcd'))
print '_'.join(e for e in pairs2('abcde'))


Best Regards,
Janos

From mwalsh at groktech.org  Sun Dec 23 20:40:13 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 23 Dec 2007 13:40:13 -0600
Subject: [Tutor] Output of list
In-Reply-To: <OFE1FA4AE3.6B6F711A-ONC12573BA.005C6322-C12573BA.005CB1FC@velux.com>
References: <OFE1FA4AE3.6B6F711A-ONC12573BA.005C6322-C12573BA.005CB1FC@velux.com>
Message-ID: <476EB99D.7050200@groktech.org>

J?nos Juh?sz wrote:
 > It is nice place to use a generator:
> 
> def pairs(sliceit):
>     streamlist = list(sliceit)
>     streamlist.reverse()
>     while streamlist:
>         pair = streamlist.pop() 
>         try:    pair += streamlist.pop()
>         except: pass
>         yield pair
> 
> ## Probably it is easier to understand
> def pairs2(sliceit):
>     try:
>         while sliceit:
>             yield sliceit[:2]
>             sliceit = sliceit[2:]
>     except: # oops, it was odd length
>         yield sliceit
> 

... Or, by extending Alan's solution ...

def splitStringByN(s, n):
    for m in range(0, len(s), n):
        yield s[m:m+n]

k = 'abcdefghi'
list(splitStringByN(k, 2))

As it turns out, this is similar to an ASPN Cookbook recipe contributed
by Dmitry Vasiliev:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069

HTH,
Marty

From janos.juhasz at VELUX.com  Sun Dec 23 21:09:10 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sun, 23 Dec 2007 21:09:10 +0100
Subject: [Tutor] Output of list
Message-ID: <OF80477711.889289C7-ONC12573BA.006DC596-C12573BA.006EB3EB@velux.com>

Dear Marty,


>... Or, by extending Alan's solution ...
>
>def splitStringByN(s, n):
>    for m in range(0, len(s), n):
>        yield s[m:m+n]
>
>k = 'abcdefghi'
>list(splitStringByN(k, 2))

It seems to be the most readable solution for me.


>As it turns out, this is similar to an ASPN Cookbook recipe contributed
>by Dmitry Vasiliev:
>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069
>
>HTH,
>Marty

Thanks for the link.


Best regards,
Janos

From mwalsh at groktech.org  Sun Dec 23 21:53:43 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 23 Dec 2007 14:53:43 -0600
Subject: [Tutor] Output of list
In-Reply-To: <OF80477711.889289C7-ONC12573BA.006DC596-C12573BA.006EB3EB@velux.com>
References: <OF80477711.889289C7-ONC12573BA.006DC596-C12573BA.006EB3EB@velux.com>
Message-ID: <476ECAD7.1030203@groktech.org>

J?nos Juh?sz wrote:
> Dear Marty,

Hi Janos,

>> ... Or, by extending Alan's solution ...
>>
>> def splitStringByN(s, n):
>>    for m in range(0, len(s), n):
>>        yield s[m:m+n]
>>
>> k = 'abcdefghi'
>> list(splitStringByN(k, 2))
> 
> It seems to be the most readable solution for me.

For completeness, one could also pull it out of the function def and use
a generator expression directly. If I'm not mistaken, this would be more
or less equivalent:

k = 'abcdefghi'
list((k[m:m+2] for m in range(0, len(k), 2)))

> 
> 
>> As it turns out, this is similar to an ASPN Cookbook recipe contributed
>> by Dmitry Vasiliev:
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069
>>
>> HTH,
>> Marty
> 
> Thanks for the link.

No problem.

Happy Holidays!
Marty

From chester_lab at twcny.rr.com  Sun Dec 23 20:48:54 2007
From: chester_lab at twcny.rr.com (TW)
Date: Sun, 23 Dec 2007 14:48:54 -0500
Subject: [Tutor] Py2Exe Tutorial
Message-ID: <002a01c8459c$df8577e0$0301a8c0@brucetower>


    I am wondering if there is a good tutorial on Py2Exe and its functions?
I have not been able to find one. I have samples but that is not good
enough. It would be nice to have something explain all the functions for
including directories, modules and all that stuff when making an executable.

        Bruce


From swathi.chinta at zustek.com  Mon Dec 24 12:37:08 2007
From: swathi.chinta at zustek.com (Swathi Chinta)
Date: Mon, 24 Dec 2007 17:07:08 +0530
Subject: [Tutor] (no subject)
Message-ID: <EXSMTP014-58cL3zbtm0000069f@EXSMTP014-5.exch014.msoutlookonline.net>

What is python language and what are its adventages

 

Thank you,

Swathi Chinta

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071224/1dc6313c/attachment.htm 

From agoldgod at gmail.com  Mon Dec 24 14:34:15 2007
From: agoldgod at gmail.com (goldgod a)
Date: Mon, 24 Dec 2007 19:04:15 +0530
Subject: [Tutor] (no subject)
In-Reply-To: <EXSMTP014-58cL3zbtm0000069f@EXSMTP014-5.exch014.msoutlookonline.net>
References: <EXSMTP014-58cL3zbtm0000069f@EXSMTP014-5.exch014.msoutlookonline.net>
Message-ID: <105c9ccc0712240534q2084cae4mc5ea7a05cd8d88c9@mail.gmail.com>

First write the proper "subject".

> What is python language and what are its adventages

 Answer is in http://www.python.org/

-- 
Thanks & Regards,
goldgod

From dos.fool at gmail.com  Mon Dec 24 15:55:01 2007
From: dos.fool at gmail.com (max baseman)
Date: Mon, 24 Dec 2007 07:55:01 -0700
Subject: [Tutor] war cards
Message-ID: <44818419-D690-4C6A-AB5D-A88CBF958141@gmail.com>

hello all, i have been rolling the idea of writing a simple script to  
play the classic card game war. i thought it would be good for me  
because their is no skill in the game. while thinking of how to write  
it i got stuck on one bit, how do i make it so that their is one of  
each card and i can split them?
any help would be great 
       

From roychenlei at gmail.com  Mon Dec 24 16:02:15 2007
From: roychenlei at gmail.com (Roy Chen)
Date: Tue, 25 Dec 2007 00:02:15 +0900
Subject: [Tutor] PythonCard error checking
Message-ID: <51740970712240702p731204cap3bd928f5d9005f42@mail.gmail.com>

Hello everyone,

I've just started trying PythonCard to build a simple GUI for a little
application I'm writing.
Just wondering if anyone knows the "proper" way to do some simple error
checking:
for example, I have a textField, and I wish to check that only integers
within a certain
range are entered into it.

I know I can just enclose that block of code in a try .. except clause, just
that I'm not sure
what to do once I've caught say, a ValueError exception. It certainly would
not be a fatal
error and I would like to prompt the user to re-enter the value, but how
should I return to
that point of program execution?

Any help from the PythonCard gurus would be appreciated. Happy holidays!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071225/735f191a/attachment.htm 

From bgailer at alum.rpi.edu  Mon Dec 24 16:18:31 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Mon, 24 Dec 2007 10:18:31 -0500
Subject: [Tutor] war cards
In-Reply-To: <44818419-D690-4C6A-AB5D-A88CBF958141@gmail.com>
References: <44818419-D690-4C6A-AB5D-A88CBF958141@gmail.com>
Message-ID: <476FCDC7.7060306@alum.rpi.edu>

max baseman wrote:
> hello all, i have been rolling the idea of writing a simple script to  
> play the classic card game war. i thought it would be good for me  
> because their is no skill in the game. while thinking of how to write  
> it i got stuck on one bit, how do i make it so that their is one of  
> each card and i can split them?
>   

I don't fully understand the question.

Also on this list we aim to help you where you are stuck, and  it is not 
clear where you are stuck.

Have you written any code, or even outlined (designed) an approach? Show 
us what you tried or thought out then wew can help.

FWIW in Python one would use a list to hold the cards.



From mlangford.cs03 at gtalumni.org  Mon Dec 24 17:57:46 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 24 Dec 2007 11:57:46 -0500
Subject: [Tutor] PythonCard error checking
In-Reply-To: <51740970712240702p731204cap3bd928f5d9005f42@mail.gmail.com>
References: <51740970712240702p731204cap3bd928f5d9005f42@mail.gmail.com>
Message-ID: <82b4f5810712240857s56f3depa707472a22891980@mail.gmail.com>

While I'm a user, I'm not a guru. Those are at:
https://lists.sourceforge.net/lists/listinfo/pythoncard-users for
pythoncard.

I know a common technique is on a button event for the "ok" or "apply"
button is to validate all the text fields in an exception safe setting. On
exception exit the event handler make an error notice. You could even color
the guilty text box text red then exit the event handler. Only if all the
boxes make it through, do you actually process the input.

GUI code often is...hairy...when done correctly. That's why is should be
separated into its own files: to keep the hair out of your main program.

        --Michael

On Dec 24, 2007 10:02 AM, Roy Chen <roychenlei at gmail.com> wrote:

> Hello everyone,
>
> I've just started trying PythonCard to build a simple GUI for a little
> application I'm writing.
> Just wondering if anyone knows the "proper" way to do some simple error
> checking:
> for example, I have a textField, and I wish to check that only integers
> within a certain
> range are entered into it.
>
> I know I can just enclose that block of code in a try .. except clause,
> just that I'm not sure
> what to do once I've caught say, a ValueError exception. It certainly
> would not be a fatal
> error and I would like to prompt the user to re-enter the value, but how
> should I return to
> that point of program execution?
>
> Any help from the PythonCard gurus would be appreciated. Happy holidays!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071224/778ca7e8/attachment.htm 

From alan.gauld at btinternet.com  Mon Dec 24 18:21:02 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 24 Dec 2007 17:21:02 -0000
Subject: [Tutor] war cards
References: <44818419-D690-4C6A-AB5D-A88CBF958141@gmail.com>
Message-ID: <fkopq2$5i3$1@ger.gmane.org>


"max baseman" <dos.fool at gmail.com> wrote

> it i got stuck on one bit, how do i make it so that their is one of
> each card and i can split them?

You can define the cards as a tuple of values and insert them into a 
list.
You can use random.choice() to select a card fro the list.
By applying that repeatedly you can split the list across multiple
players hands(also lists)

Is that what you mean?

-- 
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 Dec 24 18:24:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 24 Dec 2007 17:24:27 -0000
Subject: [Tutor] PythonCard error checking
References: <51740970712240702p731204cap3bd928f5d9005f42@mail.gmail.com>
Message-ID: <fkoq0f$61o$1@ger.gmane.org>


"Roy Chen" <roychenlei at gmail.com> wrote > 
> I have a textField, and I wish to check that only integers
> within a certain range are entered into it.

Not sure about PythonCard but most GUI toolkits, including 
wxPython from which PythonCard is buil;t allow you to trap the 
entry of data(usually with onKeyPress events or similar) so that 
you can check the data as it is entered. You can then beep or 
highlight the text if it is of the wrong type.

There will often be preconfigured entry boxes that automatically 
check for currency, date/time, numeric, password types etc

I think there is a PythonCard mailing list which is likely to 
be a better source than the tutor list.

HTH,


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


From shahjehan_hakim at hotmail.com  Mon Dec 24 19:19:37 2007
From: shahjehan_hakim at hotmail.com (Shahjehan Hakim)
Date: Mon, 24 Dec 2007 18:19:37 +0000
Subject: [Tutor] Telnet to Router/Switch
In-Reply-To: <mailman.11.1198494006.17771.tutor@python.org>
References: <mailman.11.1198494006.17771.tutor@python.org>
Message-ID: <BAY124-W30632D454279130771AA7F8C590@phx.gbl>


Hi everyone..
 
I have to make Telnet session with Router/switch of Cisco. Anybody has idea how it can be done? from what i researched, i got most of the telnet session like client/servers. But what I have to do here is just to create a Telnet session which writes the password when its prompted and then write the commands and fetch the result which is returned by the session.
 
 
 
 
 > From: tutor-request at python.org> Subject: Tutor Digest, Vol 46, Issue 60> To: tutor at python.org> Date: Mon, 24 Dec 2007 12:00:06 +0100> > Send Tutor mailing list submissions to> tutor at python.org> > To subscribe or unsubscribe via the World Wide Web, visit> http://mail.python.org/mailman/listinfo/tutor> or, via email, send a message with subject or body 'help' to> tutor-request at python.org> > You can reach the person managing the list at> tutor-owner at python.org> > When replying, please edit your Subject line so it is more specific> than "Re: Contents of Tutor digest..."> > > Today's Topics:> > 1. Re: Output of list (J?nos Juh?sz)> 2. Re: Output of list (Martin Walsh)> 3. Re: Output of list (J?nos Juh?sz)> 4. Re: Output of list (Martin Walsh)> 5. Py2Exe Tutorial (TW)> > > ----------------------------------------------------------------------> > Message: 1> Date: Sun, 23 Dec 2007 17:52:28 +0100> From: J?nos Juh?sz <janos.juhasz at VELUX.com>> Subject: Re: [Tutor] Output of list> To: tutor at python.org> Message-ID:> <OFE1FA4AE3.6B6F711A-ONC12573BA.005C6322-C12573BA.005CB1FC at velux.com>> Content-Type: text/plain; charset="US-ASCII"> > Dear Emil,> > > I want to be capable of converting a string into a list where all > > the items, in the list, have a fixed length not equal to 1 e.g i > > have k = 'abcdefgh' and I want the fixed length for all the the > > items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh'].> > How do i do this?> > > > > - Emil> > It is nice place to use a generator:> > def pairs(sliceit):> streamlist = list(sliceit)> streamlist.reverse()> while streamlist:> pair = streamlist.pop() > try: pair += streamlist.pop()> except: pass> yield pair> > ## Probably it is easier to understand> def pairs2(sliceit):> try:> while sliceit:> yield sliceit[:2]> sliceit = sliceit[2:]> except: # oops, it was odd length> yield sliceit> > > print '_'.join(e for e in pairs('abcd'))> print '_'.join(e for e in pairs('abcde'))> print '_'.join(e for e in pairs2('abcd'))> print '_'.join(e for e in pairs2('abcde'))> > > Best Regards,> Janos> > > ------------------------------> > Message: 2> Date: Sun, 23 Dec 2007 13:40:13 -0600> From: Martin Walsh <mwalsh at groktech.org>> Subject: Re: [Tutor] Output of list> Cc: tutor at python.org> Message-ID: <476EB99D.7050200 at groktech.org>> Content-Type: text/plain; charset=UTF-8> > J?nos Juh?sz wrote:> > It is nice place to use a generator:> > > > def pairs(sliceit):> > streamlist = list(sliceit)> > streamlist.reverse()> > while streamlist:> > pair = streamlist.pop() > > try: pair += streamlist.pop()> > except: pass> > yield pair> > > > ## Probably it is easier to understand> > def pairs2(sliceit):> > try:> > while sliceit:> > yield sliceit[:2]> > sliceit = sliceit[2:]> > except: # oops, it was odd length> > yield sliceit> > > > ... Or, by extending Alan's solution ...> > def splitStringByN(s, n):> for m in range(0, len(s), n):> yield s[m:m+n]> > k = 'abcdefghi'> list(splitStringByN(k, 2))> > As it turns out, this is similar to an ASPN Cookbook recipe contributed> by Dmitry Vasiliev:> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069> > HTH,> Marty> > > ------------------------------> > Message: 3> Date: Sun, 23 Dec 2007 21:09:10 +0100> From: J?nos Juh?sz <janos.juhasz at VELUX.com>> Subject: Re: [Tutor] Output of list> To: tutor at python.org> Message-ID:> <OF80477711.889289C7-ONC12573BA.006DC596-C12573BA.006EB3EB at velux.com>> Content-Type: text/plain; charset="US-ASCII"> > Dear Marty,> > > >... Or, by extending Alan's solution ...> >> >def splitStringByN(s, n):> > for m in range(0, len(s), n):> > yield s[m:m+n]> >> >k = 'abcdefghi'> >list(splitStringByN(k, 2))> > It seems to be the most readable solution for me.> > > >As it turns out, this is similar to an ASPN Cookbook recipe contributed> >by Dmitry Vasiliev:> >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069> >> >HTH,> >Marty> > Thanks for the link.> > > Best regards,> Janos> > > ------------------------------> > Message: 4> Date: Sun, 23 Dec 2007 14:53:43 -0600> From: Martin Walsh <mwalsh at groktech.org>> Subject: Re: [Tutor] Output of list> To: tutor at python.org> Message-ID: <476ECAD7.1030203 at groktech.org>> Content-Type: text/plain; charset=UTF-8> > J?nos Juh?sz wrote:> > Dear Marty,> > Hi Janos,> > >> ... Or, by extending Alan's solution ...> >>> >> def splitStringByN(s, n):> >> for m in range(0, len(s), n):> >> yield s[m:m+n]> >>> >> k = 'abcdefghi'> >> list(splitStringByN(k, 2))> > > > It seems to be the most readable solution for me.> > For completeness, one could also pull it out of the function def and use> a generator expression directly. If I'm not mistaken, this would be more> or less equivalent:> > k = 'abcdefghi'> list((k[m:m+2] for m in range(0, len(k), 2)))> > > > > > >> As it turns out, this is similar to an ASPN Cookbook recipe contributed> >> by Dmitry Vasiliev:> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069> >>> >> HTH,> >> Marty> > > > Thanks for the link.> > No problem.> > Happy Holidays!> Marty> > > ------------------------------> > Message: 5> Date: Sun, 23 Dec 2007 14:48:54 -0500> From: "TW" <chester_lab at twcny.rr.com>> Subject: [Tutor] Py2Exe Tutorial> To: <tutor at python.org>> Message-ID: <002a01c8459c$df8577e0$0301a8c0 at brucetower>> Content-Type: text/plain; charset="iso-8859-1"> > > I am wondering if there is a good tutorial on Py2Exe and its functions?> I have not been able to find one. I have samples but that is not good> enough. It would be nice to have something explain all the functions for> including directories, modules and all that stuff when making an executable.> > Bruce> > > > ------------------------------> > _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor> > > End of Tutor Digest, Vol 46, Issue 60> *************************************
_________________________________________________________________
Don't get caught with egg on your face. Play Chicktionary!
http://club.live.com/chicktionary.aspx?icid=chick_wlhmtextlink1_dec
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071224/5c1b1577/attachment-0001.htm 

From keridee at jayco.net  Mon Dec 24 21:09:05 2007
From: keridee at jayco.net (Tiger12506)
Date: Mon, 24 Dec 2007 15:09:05 -0500
Subject: [Tutor] Py2Exe Tutorial
References: <002a01c8459c$df8577e0$0301a8c0@brucetower>
Message-ID: <004801c84668$df079ba0$7efce004@jslaptop>

>    I am wondering if there is a good tutorial on Py2Exe and its functions?
> I have not been able to find one. I have samples but that is not good
> enough. It would be nice to have something explain all the functions for
> including directories, modules and all that stuff when making an 
> executable.
>
>        Bruce

Don't know if there is one, but usually it is not necessary to explicitly 
tell py2exe to include directories, modules and all that stuff - 
dependencies are checked and automatically included.
If you're talking about images, or other such binary data, it would be 
difficult. You would probably have to restructure your python code to load 
the binary data from a resource. I once had a setup.py that walked through 
the process of creating an executable (console or gui). I could send it if 
you're interested. 


From reed at reedobrien.com  Tue Dec 25 00:00:19 2007
From: reed at reedobrien.com (Reed O'Brien)
Date: Mon, 24 Dec 2007 18:00:19 -0500
Subject: [Tutor] Telnet to Router/Switch
In-Reply-To: <BAY124-W30632D454279130771AA7F8C590@phx.gbl>
References: <mailman.11.1198494006.17771.tutor@python.org>
	<BAY124-W30632D454279130771AA7F8C590@phx.gbl>
Message-ID: <DA81F74E-BD3F-41BC-8032-71990D9E19DB@reedobrien.com>

On Dec 24, 2007, at 1:19 PM, Shahjehan Hakim wrote:

> Hi everyone..
>
> I have to make Telnet session with Router/switch of Cisco. Anybody  
> has idea how it can be done? from what i researched, i got most of  
> the telnet session like client/servers. But what I have to do here  
> is just to create a Telnet session which writes the password when  
> its prompted and then write the commands and fetch the result which  
> is returned by the session.

I would start with the telnetlib module:

http://www.python.org/doc/current/lib/module-telnetlib.html

It has a quick example too:

http://www.python.org/doc/current/lib/telnet-example.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071224/5c4f9364/attachment.htm 

From alan.gauld at btinternet.com  Tue Dec 25 01:13:31 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 25 Dec 2007 00:13:31 -0000
Subject: [Tutor] Telnet to Router/Switch
References: <mailman.11.1198494006.17771.tutor@python.org><BAY124-W30632D454279130771AA7F8C590@phx.gbl>
	<DA81F74E-BD3F-41BC-8032-71990D9E19DB@reedobrien.com>
Message-ID: <fkphvf$qo9$1@ger.gmane.org>


"Reed O'Brien" <reed at reedobrien.com> wrote 

>> I have to make Telnet session with Router/switch of Cisco. 
> 
> I would start with the telnetlib module:
> 

You might also be able to use the pyExpect module to good effect.

Alan G


From deliberatus at verizon.net  Tue Dec 25 03:57:05 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Mon, 24 Dec 2007 21:57:05 -0500
Subject: [Tutor] updates andcompletion of goals
Message-ID: <47707181.4060703@verizon.net>

Windows Wiki self instller with http server tinyweb:
http://www.tinylist.org/WW140A.exe

Full featured personal wiki for the travelling laptop user.

TinyWeb server selfinstaller alone:
http://www.tinylist.org/tinywebsetup193B.exe

A good robust devlopment and personal server.

Bon Yule, mon ami.

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From pine508 at hotmail.com  Tue Dec 25 05:10:26 2007
From: pine508 at hotmail.com (Che M)
Date: Mon, 24 Dec 2007 23:10:26 -0500
Subject: [Tutor] Py2Exe Tutorial
In-Reply-To: <002a01c8459c$df8577e0$0301a8c0@brucetower>
References: <002a01c8459c$df8577e0$0301a8c0@brucetower>
Message-ID: <BAY105-W20125B5D4E9DF132A2D4A3E05A0@phx.gbl>


> From: chester_lab at twcny.rr.com> To: tutor at python.org> Date: Sun, 23 Dec 2007 14:48:54 -0500> Subject: [Tutor] Py2Exe Tutorial> > > I am wondering if there is a good tutorial on Py2Exe and its functions?> I have not been able to find one. I have samples but that is not good> enough. It would be nice to have something explain all the functions for> including directories, modules and all that stuff when making an executable.> 
You might want to try using Andrea Gavana's GUI2Exe program, which allows using py2exe via a GUI interface.  It's here:  http://xoomer.alice.it/infinity77/main/GUI2Exe.html
 
 
_________________________________________________________________
The best games are on Xbox 360.  Click here for a special offer on an Xbox 360 Console.
http://www.xbox.com/en-US/hardware/wheretobuy/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071224/94ce3c01/attachment.htm 

From sith618 at yahoo.com  Tue Dec 25 16:00:37 2007
From: sith618 at yahoo.com (sith .)
Date: Tue, 25 Dec 2007 07:00:37 -0800 (PST)
Subject: [Tutor] how to compare elements of 2 lists
Message-ID: <712076.66541.qm@web33208.mail.mud.yahoo.com>

Hi,
I've read the posts on comparing 2 lists and couldn't find the answer to my question.
  I have 2 lists
  a = [4,3,2,6,7,9]
b = [8,6,3,3,2,7]
  How can I determine if the elements in a are larger or smaller than the elements in b.
   
  for i in a:
    for u in b:
        i > u
  does not return the result I seek.

In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is compared to all the elements in b.
I'd like 
4 to 8, 
3 to 6, 
2 to 3 and so on; like 2 columns in excel, the third column would be a new list of boolean values.
  Can someone help please?  Thank you.

       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071225/709ae0a6/attachment.htm 

From ricaraoz at gmail.com  Tue Dec 25 16:30:26 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Tue, 25 Dec 2007 12:30:26 -0300
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <712076.66541.qm@web33208.mail.mud.yahoo.com>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
Message-ID: <47712212.9070500@bigfoot.com>

sith . wrote:
> Hi,
> I've read the posts on comparing 2 lists and couldn't find the answer to
> my question.
> I have 2 lists
> a = [4,3,2,6,7,9]
> b = [8,6,3,3,2,7]
> How can I determine if the elements in a are larger or smaller than the
> elements in b.
>  
> for i in a:
>     for u in b:
>         i > u
> does not return the result I seek.
> 
> In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
> compared to all the elements in b.
> I'd like
> 4 to 8,
> 3 to 6,
> 2 to 3 and so on; like 2 columns in excel, the third column would be a
> new list of boolean values.
> Can someone help please?  Thank you.
> 

all(all(i>j for j in b) for i in a)

HTH



From sith618 at yahoo.com  Tue Dec 25 16:52:07 2007
From: sith618 at yahoo.com (sith .)
Date: Tue, 25 Dec 2007 07:52:07 -0800 (PST)
Subject: [Tutor] how to compare elements of 2 lists
Message-ID: <525604.39677.qm@web33202.mail.mud.yahoo.com>

sith . wrote:
> Hi,
> I've read the posts on comparing 2 lists and couldn't find the answer to
> my question.
> I have 2 lists
> a = [4,3,2,6,7,9]
> b = [8,6,3,3,2,7]
> How can I determine if the elements in a are larger or smaller than the
> elements in b.
>  
> for i in a:
>     for u in b:
>         i > u
> does not return the result I seek.
> 
> In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
> compared to all the elements in b.
> I'd like
> 4 to 8,
> 3 to 6,
> 2 to 3 and so on; like 2 columns in excel, the third column would be a
> new list of boolean values.
> Can someone help please?  Thank you.
> 
  all(all(i>j for j in b) for i in a)
  HTH
   
   
  Hi,
Thanks for your reply.  This is what I get:
  >>> a = [4,3,2,6,7,9]
  >>> b = [8,6,3,3,2,7]
  >>> all(all(i>j for j in b) for i in a)
>>> all(all(i>j for j in b) for i in a)
  False
  How do I make it loop through the whole list?

       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071225/2dc1746f/attachment.htm 

From tezlo at gmx.net  Tue Dec 25 17:05:58 2007
From: tezlo at gmx.net (tezlo)
Date: Tue, 25 Dec 2007 17:05:58 +0100
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <712076.66541.qm@web33208.mail.mud.yahoo.com>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
Message-ID: <20071225170558.cfc8f8bf.tezlo@gmx.net>

"sith ." <sith618 at yahoo.com> wrote:
> How can I determine if the elements in a are larger or smaller than
> the elements in b. 
>  ..
> like 2 columns in excel, the third column would be
> a new list of boolean values. Can someone help please?  Thank you.

Hi,
in that case, you need to create the third column (list). Instead of
values, iterate over indices and use those to fetch the values, ie:
c = []
for i in range(min(len(a), len(b))):
  c.append(a[i] > b[i])

or using list comprehension:
c = [a[i] > b[i] for i in range(min(len(a), len(b)))]

tezlo

From alan.gauld at btinternet.com  Tue Dec 25 17:38:23 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 25 Dec 2007 16:38:23 -0000
Subject: [Tutor] how to compare elements of 2 lists
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
Message-ID: <fkrbm3$a47$1@ger.gmane.org>


"sith ." <sith618 at yahoo.com> wrote

> I'd like
> 4 to 8,
> 3 to 6,
> 2 to 3 and so on; like 2 columns in excel, the third column would be 
> a new list of boolean values.

results = [ A[n] == B[n] for n in len(A) ]

You should check that A and B are equal lengths of course...

You could also substitute cmp(A,B) which will return -1,0,1 depending 
on
whether A<B; A==B; A>B respectively


HTH,

Alan G



From sith618 at yahoo.com  Tue Dec 25 18:21:45 2007
From: sith618 at yahoo.com (sith .)
Date: Tue, 25 Dec 2007 09:21:45 -0800 (PST)
Subject: [Tutor] how to compare elements of 2 lists
Message-ID: <828283.16090.qm@web33208.mail.mud.yahoo.com>

"sith ." <sith618 at yahoo.com> wrote:
> How can I determine if the elements in a are larger or smaller than
> the elements in b. 
>  ..
> like 2 columns in excel, the third column would be
> a new list of boolean values. Can someone help please?  Thank you.

Hi,
in that case, you need to create the third column (list). Instead of
values, iterate over indices and use those to fetch the values, ie:
c = []
for i in range(min(len(a), len(b))):
  c.append(a[i] > b[i])

or using list comprehension:
c = [a[i] > b[i] for i in range(min(len(a), len(b)))]

tezlo

   
  I finally get it.  Thank you so much.
   
  p.s.  Thanks Alan and Ricardo.

       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071225/90c33a74/attachment.htm 

From ricaraoz at gmail.com  Tue Dec 25 20:04:43 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Tue, 25 Dec 2007 16:04:43 -0300
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <525604.39677.qm@web33202.mail.mud.yahoo.com>
References: <525604.39677.qm@web33202.mail.mud.yahoo.com>
Message-ID: <4771544B.7050608@bigfoot.com>

sith . wrote:
> sith . wrote:
>> Hi,
>> I've read the posts on comparing 2 lists and couldn't find the answer to
>> my question.
>> I have 2 lists
>> a = [4,3,2,6,7,9]
>> b = [8,6,3,3,2,7]
>> How can I determine if the elements in a are larger or smaller than the
>> elements in b.
>> 
>> for i in a:
>>     for u in b:
>>         i > u
>> does not return the result I seek.
>>
>> In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
>> compared to all the elements in b.
>> I'd like
>> 4 to 8,
>> 3 to 6,
>> 2 to 3 and so on; like 2 columns in excel, the third column would be a
>> new list of boolean values.
>> Can someone help please?  Thank you.
>>
> all(all(i>j for j in b) for i in a)
> HTH
>  
>  
> Hi,
> Thanks for your reply.  This is what I get:
>>>> a = [4,3,2,6,7,9]
>>>> b = [8,6,3,3,2,7]
>>>> all(all(i>j for j in b) for i in a)
>>>> all(all(i>j for j in b) for i in a)
> False
> How do I make it loop through the whole list?
> 

It has already looped. You said you wanted to "determine if the elements
in a are larger or smaller than the elements in b", ok there's your
answer. Check the manual and find out what does "all()" do and also
check the manual about "for j in b" and you'll see that it is already
looping through both lists.





From cfuller084 at thinkingplanet.net  Tue Dec 25 21:36:59 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Tue, 25 Dec 2007 14:36:59 -0600
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <712076.66541.qm@web33208.mail.mud.yahoo.com>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
Message-ID: <200712251436.59616.cfuller084@thinkingplanet.net>

The most concise way to do this is to transpose the list (convert a axb array
to bxa), then complare the elements that are pairs of one value each of the 
original lists.

You have two lists, a and b. ?Put these into a list and you have a 2x6 
2d "array".

>>> [a,b]
[[4, 3, 2, 6, 7, 9], [8, 6, 3, 3, 2, 7]]

A quick way to do a transposition is to use the built-in zip() function. This 
doesn't do error checking! If you need to do this in production code, you 
need to check that the lists are of even lengths. zip() will truncate the 
lists until they are all teh same size!

>>> zip(*[a,b])
[(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]

So, to get a list of booleans, you can do this:
>>> [x>y for x,y in zip(*[a,b])]
[False, False, False, True, True, True]

Cheers

On Tuesday 25 December 2007 09:00, sith . wrote:
> Hi,
> I've read the posts on comparing 2 lists and couldn't find the answer to my
> question. I have 2 lists
>   a = [4,3,2,6,7,9]
> b = [8,6,3,3,2,7]
>   How can I determine if the elements in a are larger or smaller than the
> elements in b.
>
>   for i in a:
>     for u in b:
>         i > u
>   does not return the result I seek.
>
> In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
> compared to all the elements in b. I'd like
> 4 to 8,
> 3 to 6,
> 2 to 3 and so on; like 2 columns in excel, the third column would be a new
> list of boolean values. Can someone help please?  Thank you.
>
>
> ---------------------------------
> Never miss a thing.   Make Yahoo your homepage.

From kent37 at tds.net  Wed Dec 26 02:00:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 25 Dec 2007 20:00:57 -0500
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <200712251436.59616.cfuller084@thinkingplanet.net>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
	<200712251436.59616.cfuller084@thinkingplanet.net>
Message-ID: <4771A7C9.5030807@tds.net>

Chris Fuller wrote:

>>>> zip(*[a,b])
> [(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]

This can be just zip(a, b)

Kent

From cfuller084 at thinkingplanet.net  Wed Dec 26 03:59:13 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Tue, 25 Dec 2007 20:59:13 -0600
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <4771A7C9.5030807@tds.net>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
	<200712251436.59616.cfuller084@thinkingplanet.net>
	<4771A7C9.5030807@tds.net>
Message-ID: <200712252059.13395.cfuller084@thinkingplanet.net>


I didn't think of that.  But for an arbitrary 2D list, you need the asterisk 
syntax.

On Tuesday 25 December 2007 19:00, you wrote:
> Chris Fuller wrote:
> >>>> zip(*[a,b])
> >
> > [(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]
>
> This can be just zip(a, b)
>
> Kent

From rabidpoobear at gmail.com  Wed Dec 26 07:45:34 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 26 Dec 2007 00:45:34 -0600
Subject: [Tutor] updates andcompletion of goals
In-Reply-To: <47707181.4060703@verizon.net>
References: <47707181.4060703@verizon.net>
Message-ID: <dfeb4470712252245v508ff7f5tb2fcf8141aa906ad@mail.gmail.com>

On Dec 24, 2007 8:57 PM, Kirk Bailey <deliberatus at verizon.net> wrote:

> Windows Wiki self instller with http server tinyweb:
> http://www.tinylist.org/WW140A.exe
>
> Full featured personal wiki for the travelling laptop user.
>
> My review:
Upon initialization of the installation, I read your license agreement.  I
thought it was mildly offensive, but whatever, this can be ignored.

Thereafter, I allowed your installatio script to start up my web browser and
point it to
http://localhost/cgi-bin/WW.py?FrontPage

Problem, though: No such file exists.  So I'm presented with a big fat error
page that looks something like this:
Internal Server Error: The system cannot find the path specified
Now I've heard you talk about your target market (non computer-savvy
businessmen), and making everything seamless so they don't get confused.
This is one thing you must work on.

I browsed around in the C:/Program Files/WindowsWiki/www folder (Note: not
on a Laptop) and I noticed some other file names.
Well, I tried cgi-bin/helloworld.py, which worked.  There were many other
such files (Which look to me like test files, that have nothing to do with
the Wiki itself (including some CSV files, etc)).  messageserver.py threw an
error.
There was some inconsistent naming: statscast1 vs statcast2 (note the
missing 's')
WWed1 was broken (said files were read-only)
WWmanual worked fine.

There was a missing icon (or some other broken image at the top) across all
WW pages that successfully loaded.

WWlistall worked in that it listed all of the categories of the Wiki, but
note that all links were back to WW.py?CategoryName , which of course failed
since WW.py was nonexistent.


My final suggestion:
When you package up a release, test it on a virgin computer that's never
seen your software before.  Test it on more than one, if you can.  Mess with
the options and try to break the install.  If you can't, then _maybe_ it
worked out correctly, but still try to get it tested as much as possible.
If you can break it, go back and try to fix the problems.

I will be happy to re-test your software upon next release.  Good luck.  As
of now, I see no reason why I should "pony up the dough", though.
-Luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071226/ef4d2aee/attachment.htm 

From kent37 at tds.net  Wed Dec 26 15:51:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 26 Dec 2007 09:51:45 -0500
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <200712252059.13395.cfuller084@thinkingplanet.net>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
	<200712251436.59616.cfuller084@thinkingplanet.net>
	<4771A7C9.5030807@tds.net>
	<200712252059.13395.cfuller084@thinkingplanet.net>
Message-ID: <47726A81.5030505@tds.net>

Chris Fuller wrote:
> I didn't think of that.  But for an arbitrary 2D list, you need the asterisk 
> syntax.

I don't know what you mean by "an arbitrary 2D list". You need the * 
syntax when your arguments are *already* in a list. For any number of 
arguments,
   zip(*[a, b, ..., x, y, z])
can be written more simple as
   zip(a, b, ..., x, y, z)

Kent

> 
> On Tuesday 25 December 2007 19:00, you wrote:
>> Chris Fuller wrote:
>>>>>> zip(*[a,b])
>>> [(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]
>> This can be just zip(a, b)
>>
>> Kent
> 


From cfuller084 at thinkingplanet.net  Wed Dec 26 16:30:21 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Wed, 26 Dec 2007 09:30:21 -0600
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <47726A81.5030505@tds.net>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
	<200712252059.13395.cfuller084@thinkingplanet.net>
	<47726A81.5030505@tds.net>
Message-ID: <200712260930.22083.cfuller084@thinkingplanet.net>


"Arbitrary" means any size, and particularly, an unknown size.  If you don't 
know how big the list is when you are writing the code, you need to use this 
syntax.

It's also more concise and less error prone than zip(l[0], l[1], l[2]) if you 
have got a 2D list of known length.

On Wednesday 26 December 2007 08:51, you wrote:
> Chris Fuller wrote:
> > I didn't think of that.  But for an arbitrary 2D list, you need the
> > asterisk syntax.
>
> I don't know what you mean by "an arbitrary 2D list". You need the *
> syntax when your arguments are *already* in a list. For any number of
> arguments,
>    zip(*[a, b, ..., x, y, z])
> can be written more simple as
>    zip(a, b, ..., x, y, z)
>
> Kent
>
> > On Tuesday 25 December 2007 19:00, you wrote:
> >> Chris Fuller wrote:
> >>>>>> zip(*[a,b])
> >>>
> >>> [(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]
> >>
> >> This can be just zip(a, b)
> >>
> >> Kent

From alan.gauld at btinternet.com  Wed Dec 26 17:03:08 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 26 Dec 2007 16:03:08 -0000
Subject: [Tutor] how to compare elements of 2 lists
References: <712076.66541.qm@web33208.mail.mud.yahoo.com><200712252059.13395.cfuller084@thinkingplanet.net><47726A81.5030505@tds.net>
	<200712260930.22083.cfuller084@thinkingplanet.net>
Message-ID: <fkttvt$pde$1@ger.gmane.org>

"Chris Fuller" <cfuller084 at thinkingplanet.net> wrote

> "Arbitrary" means any size, and particularly, an unknown size.  If 
> you don't
> know how big the list is when you are writing the code, you need to 
> use this
> syntax.
>
> It's also more concise and less error prone than zip(l[0], l[1], 
> l[2]) if you
> have got a 2D list of known length.

I thought I was following this but now I'm not sure.

Do you mean that if I have a list L that contains an arbitrary
number of sublists that I can call zip using:

>>> zip(*L)

rather than

>>> zip(L[0],L[1],...., L[n])

If so I agree.

But any time that you use the *[] format it is easier to
just put the content of the [] into the zip directly, which is what,
I think, Kent is saying?

>>    zip(*[a, b, ..., x, y, z])
>> can be written more simply as
>>    zip(a, b, ..., x, y, z)
>>
>> Kent


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





From cfuller at thinkingplanet.net  Wed Dec 26 19:11:51 2007
From: cfuller at thinkingplanet.net (Chris Fuller)
Date: Wed, 26 Dec 2007 12:11:51 -0600
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <fkttvt$pde$1@ger.gmane.org>
References: <712076.66541.qm@web33208.mail.mud.yahoo.com>
	<200712260930.22083.cfuller084@thinkingplanet.net>
	<fkttvt$pde$1@ger.gmane.org>
Message-ID: <200712261211.51353.cfuller@thinkingplanet.net>

On Wednesday 26 December 2007 10:03, Alan Gauld wrote:
> I thought I was following this but now I'm not sure.
>
> Do you mean that if I have a list L that contains an arbitrary
>
> number of sublists that I can call zip using:
> >>> zip(*L)
>
> rather than
>
> >>> zip(L[0],L[1],...., L[n])
>
> If so I agree.
>
Yes.  You could build up a string and call eval(), but otherwise this wouldn't 
be possible, without iterating through manually.  (using evail() is usually 
not a good idea, avoid it if you can)

> But any time that you use the *[] format it is easier to
> just put the content of the [] into the zip directly, which is what,
> I think, Kent is saying?
>

Yes, for the original example, zip(a,b) is equivalent, and probably clearer.  
Certainly simpler.  Sorry to be confusing.  I realize now that lots of my 
code have lists of known length and need a little tweaking :)

I just remembered another way to do this, with map():
>>> a=range(4)
>>> b=['a','b','c','d']
>>> map(None,a,b)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

This also doesn't complain if the lists are uneven, but instead of truncating, 
it pads the short ones with None's.  I almost never use map() now that we 
have list comprehensions, however.  map(None, *(a,b)) also works if you 
are "transposing" an unknown number of lists.

Cheers


From agoldgod at gmail.com  Thu Dec 27 13:51:42 2007
From: agoldgod at gmail.com (goldgod a)
Date: Thu, 27 Dec 2007 18:21:42 +0530
Subject: [Tutor] Festival equivalent package in python
Message-ID: <105c9ccc0712270451s2081c8edg1ac2c22490fb07c1@mail.gmail.com>

hi ,
    Is there any "festival" equivalent package in python. Any idea to
do that. Is there any modules to interact with the sounds using
python.

-- 
Thanks & Regards,
goldgod

From kent37 at tds.net  Thu Dec 27 14:27:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 27 Dec 2007 08:27:40 -0500
Subject: [Tutor] Festival equivalent package in python
In-Reply-To: <105c9ccc0712270451s2081c8edg1ac2c22490fb07c1@mail.gmail.com>
References: <105c9ccc0712270451s2081c8edg1ac2c22490fb07c1@mail.gmail.com>
Message-ID: <4773A84C.5080700@tds.net>

goldgod a wrote:
> hi ,
>     Is there any "festival" equivalent package in python. 

GIYF
http://www.freebsoft.org/speechd
http://cheeseshop.python.org/pypi/PyFest/0.1

Kent

From james.homme at highmark.com  Thu Dec 27 14:40:11 2007
From: james.homme at highmark.com (james.homme at highmark.com)
Date: Thu, 27 Dec 2007 08:40:11 -0500
Subject: [Tutor] How Do I Make Imports Work
Message-ID: <OFAF6EC072.74FC7A39-ON852573BE.004A8F19-852573BE.004B300C@highmark.com>


Hi,
I am just starting to learn about making classes, so I wanted to put some
code into a module and use it. I know the code works because when I put it
in the same file that calls it, it does what it's supposed to do. When I
move it into its own file and try to use an import statement to bring it
in, I get errors that say that methods don't exist. I looked at a Windows
tutorial that instructs me to edit my registry. The tutorial seemed to be
talking about the version of Python from python.org. I have ActiveState
Python. I'm OK with editing the registry, but  I'd rather not do it. If I
have to, is there documentation somewhere that helps me work with
ActiveState Python to do this. If I don't have to, where can I find
documentation that helps me make this work?

Thanks lots.

Jim

James D Homme, , Usability Engineering, Highmark Inc.,
james.homme at highmark.com, 412-544-1810

"Never doubt that a thoughtful group of committed citizens can change the
world.  Indeed, it is the only thing that ever has." -- Margaret Mead


From rob.andrews at gmail.com  Thu Dec 27 15:04:13 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Thu, 27 Dec 2007 08:04:13 -0600
Subject: [Tutor] How Do I Make Imports Work
In-Reply-To: <OFAF6EC072.74FC7A39-ON852573BE.004A8F19-852573BE.004B300C@highmark.com>
References: <OFAF6EC072.74FC7A39-ON852573BE.004A8F19-852573BE.004B300C@highmark.com>
Message-ID: <8d757d2e0712270604s6edf42f6s5077d28d568577d8@mail.gmail.com>

Can you show us an example of the code where you're attempting to
import and the error you get?

-Rob A.

On Dec 27, 2007 7:40 AM,  <james.homme at highmark.com> wrote:
>
> Hi,
> I am just starting to learn about making classes, so I wanted to put some
> code into a module and use it. I know the code works because when I put it
> in the same file that calls it, it does what it's supposed to do. When I
> move it into its own file and try to use an import statement to bring it
> in, I get errors that say that methods don't exist. I looked at a Windows
> tutorial that instructs me to edit my registry. The tutorial seemed to be
> talking about the version of Python from python.org. I have ActiveState
> Python. I'm OK with editing the registry, but  I'd rather not do it. If I
> have to, is there documentation somewhere that helps me work with
> ActiveState Python to do this. If I don't have to, where can I find
> documentation that helps me make this work?
>
> Thanks lots.
>
> Jim
>
> James D Homme, , Usability Engineering, Highmark Inc.,
> james.homme at highmark.com, 412-544-1810
>
> "Never doubt that a thoughtful group of committed citizens can change the
> world.  Indeed, it is the only thing that ever has." -- Margaret Mead
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
"Quise ahogar mis penas, pero las muy putas flotan"
Sabidur?a popular

From james.homme at highmark.com  Thu Dec 27 15:29:21 2007
From: james.homme at highmark.com (james.homme at highmark.com)
Date: Thu, 27 Dec 2007 09:29:21 -0500
Subject: [Tutor] How Do I Make Imports Work
In-Reply-To: <8d757d2e0712270604s6edf42f6s5077d28d568577d8@mail.gmail.com>
Message-ID: <OFD7FC663C.CFCEEFE7-ON852573BE.004F5794-852573BE.004FB060@highmark.com>

Hi,
Here is the offending code and error.

# elevator_system.py
# By Jim Homme
# Simulate the behavior of a group of elevators.
# Try to import and get error.
# The module and this file are in the same directory.
import elevator
# The elevator module
# This would be in a separate file.
# When I remove comments, it works in this file.


# class Elevator(object):
#  """Simulate the behavior of an elevator"""
#  def show_state(self):
#    """Show what floor the elevator is on"""
#    print "I am on floor 1"
#

e = Elevator()
e.show_state()

raw_input("\n\nPress the enter key to exit.")

====================

Error Message

Traceback (most recent call last):

  File "c:\scripts\ELEVAT~1.PY", line 19, in <module>

    e = Elevator()

NameError: name 'Elevator' is not defined

James D Homme, , Usability Engineering, Highmark Inc.,
james.homme at highmark.com, 412-544-1810

"Never doubt that a thoughtful group of committed citizens can change the
world.  Indeed, it is the only thing that ever has." -- Margaret Mead



                                                                           
             "Rob Andrews"                                                 
             <rob.andrews at gmai                                             
             l.com>                                                     To 
             Sent by:                  "Python Tutor" <tutor at python.org>   
             tutor-bounces at pyt                                          cc 
             hon.org                                                       
                                                                   Subject 
                                       Re: [Tutor] How Do I Make Imports   
             12/27/2007 09:04          Work                                
             AM                                                            
                                                                           
                                                                           
                                                                           
                                                                           
                                                                           




Can you show us an example of the code where you're attempting to
import and the error you get?

-Rob A.

On Dec 27, 2007 7:40 AM,  <james.homme at highmark.com> wrote:
>
> Hi,
> I am just starting to learn about making classes, so I wanted to put some
> code into a module and use it. I know the code works because when I put
it
> in the same file that calls it, it does what it's supposed to do. When I
> move it into its own file and try to use an import statement to bring it
> in, I get errors that say that methods don't exist. I looked at a Windows
> tutorial that instructs me to edit my registry. The tutorial seemed to be
> talking about the version of Python from python.org. I have ActiveState
> Python. I'm OK with editing the registry, but  I'd rather not do it. If I
> have to, is there documentation somewhere that helps me work with
> ActiveState Python to do this. If I don't have to, where can I find
> documentation that helps me make this work?
>
> Thanks lots.
>
> Jim
>
> James D Homme, , Usability Engineering, Highmark Inc.,
> james.homme at highmark.com, 412-544-1810
>
> "Never doubt that a thoughtful group of committed citizens can change the
> world.  Indeed, it is the only thing that ever has." -- Margaret Mead
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
"Quise ahogar mis penas, pero las muy putas flotan"
Sabidur?a popular
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor



From bgailer at alum.rpi.edu  Thu Dec 27 15:55:52 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 27 Dec 2007 09:55:52 -0500
Subject: [Tutor] How Do I Make Imports Work
In-Reply-To: <OFD7FC663C.CFCEEFE7-ON852573BE.004F5794-852573BE.004FB060@highmark.com>
References: <OFD7FC663C.CFCEEFE7-ON852573BE.004F5794-852573BE.004FB060@highmark.com>
Message-ID: <4773BCF8.4010906@alum.rpi.edu>

james.homme at highmark.com wrote:
> Hi,
> Here is the offending code and error.
>
> # elevator_system.py
> # By Jim Homme
> # Simulate the behavior of a group of elevators.
> # Try to import and get error.
> # The module and this file are in the same directory.
> import elevator
> # The elevator module
> # This would be in a separate file.
> # When I remove comments, it works in this file.
>
>
> # class Elevator(object):
> #  """Simulate the behavior of an elevator"""
> #  def show_state(self):
> #    """Show what floor the elevator is on"""
> #    print "I am on floor 1"
> #
>
> e = Elevator()
>   
Objects in an imported module must be qualified with the module name. So 
replace the previous line with:

e = elevator.Elevator()


As an alternative you can 


from elevator import *

which brings the objects into the main namespace and then

e = Elevator()

works but that usage is usually undesirable for several very good reasons.
> e.show_state()
>
> raw_input("\n\nPress the enter key to exit.")
>
> ====================
>
> Error Message
>
> Traceback (most recent call last):
>
>   File "c:\scripts\ELEVAT~1.PY", line 19, in <module>
>
>     e = Elevator()
>
> NameError: name 'Elevator' is not defined
>
> James D Homme, , Usability Engineering, Highmark Inc.,
> james.homme at highmark.com, 412-544-1810
>
> "Never doubt that a thoughtful group of committed citizens can change the
> world.  Indeed, it is the only thing that ever has." -- Margaret Mead
>
>
>
>                                                                            
>              "Rob Andrews"                                                 
>              <rob.andrews at gmai                                             
>              l.com>                                                     To 
>              Sent by:                  "Python Tutor" <tutor at python.org>   
>              tutor-bounces at pyt                                          cc 
>              hon.org                                                       
>                                                                    Subject 
>                                        Re: [Tutor] How Do I Make Imports   
>              12/27/2007 09:04          Work                                
>              AM                                                            
>                                                                            
>                                                                            
>                                                                            
>                                                                            
>                                                                            
>
>
>
>
> Can you show us an example of the code where you're attempting to
> import and the error you get?
>
> -Rob A.
>
> On Dec 27, 2007 7:40 AM,  <james.homme at highmark.com> wrote:
>   
>> Hi,
>> I am just starting to learn about making classes, so I wanted to put some
>> code into a module and use it. I know the code works because when I put
>>     
> it
>   
>> in the same file that calls it, it does what it's supposed to do. When I
>> move it into its own file and try to use an import statement to bring it
>> in, I get errors that say that methods don't exist. I looked at a Windows
>> tutorial that instructs me to edit my registry. The tutorial seemed to be
>> talking about the version of Python from python.org. I have ActiveState
>> Python. I'm OK with editing the registry, but  I'd rather not do it. If I
>> have to, is there documentation somewhere that helps me work with
>> ActiveState Python to do this. If I don't have to, where can I find
>> documentation that helps me make this work?
>>
>> Thanks lots.
>>
>> Jim
>>
>> James D Homme, , Usability Engineering, Highmark Inc.,
>> james.homme at highmark.com, 412-544-1810
>>
>> "Never doubt that a thoughtful group of committed citizens can change the
>> world.  Indeed, it is the only thing that ever has." -- Margaret Mead
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>     
>
>
>
> --
> "Quise ahogar mis penas, pero las muy putas flotan"
> Sabidur?a popular
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From alan.gauld at btinternet.com  Thu Dec 27 15:46:07 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 27 Dec 2007 14:46:07 -0000
Subject: [Tutor] How Do I Make Imports Work
References: <OFAF6EC072.74FC7A39-ON852573BE.004A8F19-852573BE.004B300C@highmark.com>
Message-ID: <fl0drg$tko$1@ger.gmane.org>


<james.homme at highmark.com> wrote

> I am just starting to learn about making classes, so I wanted to put 
> some
> code into a module and use it.

Good idea.

> move it into its own file and try to use an import statement to 
> bring it
> in, I get errors that say that methods don't exist.

Are you remembering to prefix the class/functions with the
module name? Have you instantiated the class correctly?

Can we see the import statement and the error messages please?

BTW Does it work at the >>> prompt?


> tutorial that instructs me to edit my registry.

You should not need to edit the registry for this.
But you may need to save the file somewhere that Python can find it!
And you may need to set your PYTHONPATH environment variable.

> talking about the version of Python from python.org. I have 
> ActiveState
> Python.

Shouldn't make any difference for this.

HTH,

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



From cfuller084 at thinkingplanet.net  Thu Dec 27 17:36:33 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Thu, 27 Dec 2007 10:36:33 -0600
Subject: [Tutor] How Do I Make Imports Work
In-Reply-To: <OFD7FC663C.CFCEEFE7-ON852573BE.004F5794-852573BE.004FB060@highmark.com>
References: <OFD7FC663C.CFCEEFE7-ON852573BE.004F5794-852573BE.004FB060@highmark.com>
Message-ID: <200712271036.33748.cfuller084@thinkingplanet.net>

On Thursday 27 December 2007 08:29, james.homme at highmark.com wrote:
>
> e = Elevator()
> e.show_state()
>
> raw_input("\n\nPress the enter key to exit.")
>

Two observations:

This "module-level" code that does the testing will be run when the module is 
imported.  A more flexible approach would be to place it in a test() function 
and call it whenever you desire.  The test() function could even be a method 
of the class, if it makes sense to do that.  If you had a lot of classes, and 
each needed its own demo/test function, for instance.  If they all worked 
together, maybe one test function for all would suffice.

If you start to collect a lot of modules, you will probably want to organize 
them into directories.  It is a hassle to append stuff to sys.path every time 
you start python, so you may want to consider setting up .pth files.

See the python docs: http://docs.python.org/lib/module-site.html

Cheers

From jmorcombe at westnet.com.au  Fri Dec 28 02:38:05 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Fri, 28 Dec 2007 10:38:05 +0900
Subject: [Tutor] Microsoft Access
Message-ID: <003d01c848f2$4b2b6600$6a00a8c0@ASC000E7B84CF9F>

Are there any simple tutorials on using MS Access from Python?

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/e93c0a25/attachment.htm 

From D3IBZ at hotmail.com  Fri Dec 28 03:12:16 2007
From: D3IBZ at hotmail.com (Darren Williams)
Date: Fri, 28 Dec 2007 02:12:16 -0000
Subject: [Tutor] Microsoft Access
References: <003d01c848f2$4b2b6600$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <BAY138-DAV13C5FA82C76803216CFDAEE9550@phx.gbl>

Typing 'Using MS Access from Python' into Google returned a few results, one in particular - http://www.markcarter.me.uk/computing/python/ado.html

Hope that helps.
  ----- Original Message ----- 
  From: Jim Morcombe 
  To: python tutor mailing list 
  Sent: Friday, December 28, 2007 1:38 AM
  Subject: [Tutor] Microsoft Access


  Are there any simple tutorials on using MS Access from Python?

  Jim



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


  _______________________________________________
  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/20071228/d86c02d9/attachment.htm 

From bgailer at alum.rpi.edu  Fri Dec 28 04:19:41 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 27 Dec 2007 22:19:41 -0500
Subject: [Tutor] Microsoft Access
In-Reply-To: <003d01c848f2$4b2b6600$6a00a8c0@ASC000E7B84CF9F>
References: <003d01c848f2$4b2b6600$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <47746B4D.2060308@alum.rpi.edu>

Jim Morcombe wrote:
> Are there any simple tutorials on using MS Access from Python?

Your question is ambiguous. Do you want to manipulate the data using SQL 
or do you want to open an Access session as a COM server and control it?


From jmorcombe at westnet.com.au  Fri Dec 28 06:08:40 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Fri, 28 Dec 2007 14:08:40 +0900
Subject: [Tutor] Microsoft Access
References: <003d01c848f2$4b2b6600$6a00a8c0@ASC000E7B84CF9F>
	<BAY138-DAV13C5FA82C76803216CFDAEE9550@phx.gbl>
Message-ID: <002001c8490f$b66e2cf0$6a00a8c0@ASC000E7B84CF9F>

This tutorial seems very specific to PythonWin IDE.  I haven't tried it, but it seems to imply that it uses stuff from PythonWin IDE that may not be available in IDLE.  Does PythonWin IDE come with any extras that aren't available in standard Python?

  ----- Original Message ----- 
  From: Darren Williams 
  To: Jim Morcombe ; tutor at python.org 
  Sent: Friday, December 28, 2007 11:12 AM
  Subject: Re: [Tutor] Microsoft Access


  Typing 'Using MS Access from Python' into Google returned a few results, one in particular - http://wwwmarkcarter.me.uk/computing/python/ado.html

  Hope that helps.
    ----- Original Message ----- 
    From: Jim Morcombe 
    To: python tutor mailing list 
    Sent: Friday, December 28, 2007 1:38 AM
    Subject: [Tutor] Microsoft Access


    Are there any simple tutorials on using MS Access from Python?

    Jim



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


    _______________________________________________
    Tutor maillist  -  Tutor at python.org
    http://mail.pythonorg/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/ed32fe20/attachment.htm 

From jmorcombe at westnet.com.au  Fri Dec 28 07:51:06 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Fri, 28 Dec 2007 15:51:06 +0900
Subject: [Tutor] Closing GUI program
Message-ID: <000601c8491e$05902b40$6a00a8c0@ASC000E7B84CF9F>

I have copied the following program.  When I run it, (By pressing F5 from IDLE), it displays the "Hello world" message.

When I close the window, the "Hello world" message disappears, but it seems that the program is still running, because when I close the shell, i get the message "The program is still running.  Do you want to kill it?"

How do I get the program to terminate when the window is closed?

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/9564c8fe/attachment.htm 

From jmorcombe at westnet.com.au  Fri Dec 28 08:32:47 2007
From: jmorcombe at westnet.com.au (Jim Morcombe)
Date: Fri, 28 Dec 2007 16:32:47 +0900
Subject: [Tutor] Closing GUI program
References: <000601c8491e$05902b40$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <002c01c84923$e7b8a560$6a00a8c0@ASC000E7B84CF9F>

Oops!  Here's the program:
---------------------------
from Tkinter import *     

root = Tk()
z = Label(root, text="Hello World!")
z.grid()
root.mainloop()
------------------------------

Jim

  ----- Original Message ----- 
  From: Jim Morcombe 
  To: python tutor mailing list 
  Sent: Friday, December 28, 2007 3:51 PM
  Subject: [Tutor] Closing GUI program


  I have copied the following program.  When I run it, (By pressing F5 from IDLE), it displays the "Hello world" message.

  When I close the window, the "Hello world" message disappears, but it seems that the program is still running, because when I close the shell, i get the message "The program is still running.  Do you want to kill it?"

  How do I get the program to terminate when the window is closed?

  Jim



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


  _______________________________________________
  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/20071228/f6ecf4e7/attachment.htm 

From michaelarpsorensen at stevnstrup.dk  Fri Dec 28 08:44:48 2007
From: michaelarpsorensen at stevnstrup.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=)
Date: Fri, 28 Dec 2007 08:44:48 +0100
Subject: [Tutor] Dynamically named objects
Message-ID: <9b1867560712272344h1b1161c1xb266bc15af83e06f@mail.gmail.com>

Hi there.

I need to instantiate objects on the fly and put the in a list/dict for
later use. I was thinking of this:

objectlist = []
newobjectname = "object1"
classname = "class1" + "()"
objectlist.append(newobjectname = eval(classname) )
objectlist[0].method("hello world")

Can this be done? If not, is there a work around or some design pattern for
this situation?

-- 
Venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH

I am /root and if you see me laughing you better have a backup.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/a277d77d/attachment-0001.htm 

From marc.tompkins at gmail.com  Fri Dec 28 09:15:34 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 28 Dec 2007 00:15:34 -0800
Subject: [Tutor] Dynamically named objects
In-Reply-To: <40af687b0712280013p524529e5ke3a5a78d10953f63@mail.gmail.com>
References: <9b1867560712272344h1b1161c1xb266bc15af83e06f@mail.gmail.com>
	<40af687b0712280013p524529e5ke3a5a78d10953f63@mail.gmail.com>
Message-ID: <40af687b0712280015g33bcefb9q3314d6e310888e73@mail.gmail.com>

Sorry, meant to respond to the list, not just the OP...

---------- Forwarded message ----------
From: Marc Tompkins <marc.tompkins at gmail.com>
Date: Dec 28, 2007 12:13 AM
Subject: Re: [Tutor] Dynamically named objects
To: Michael Bernhard Arp S?rensen <michaelarpsorensen at stevnstrup.dk>


I don't think there's any need for eval - I'll leave the sermon about why
eval is a Bad Thing for someone else - and if your objects are going to
spend most of their "lives" in a list or dictionary, they don't really need
meaningful individual names.  (I mean, instead of naming each one class1,
class2, etc. you can simply refer to them as classDict[1], classDict[2],
etc. or classList[1], etc.)

How's this:
#====================================
class thingy():
    example = "Just testing - "
    def __init__(self, num):
        self.example = self.example + str(num)

thang = {}
for x in range(1,4):
    thang[x] = thingy(x)

for item, value in thang.iteritems():
    print item, value.example
#=====================================

On Dec 27, 2007 11:44 PM, Michael Bernhard Arp S?rensen <
michaelarpsorensen at stevnstrup.dk> wrote:

> Hi there.
>
> I need to instantiate objects on the fly and put the in a list/dict for
> later use. I was thinking of this:
>
> objectlist = []
> newobjectname = "object1"
> classname = "class1" + "()"
> objectlist.append(newobjectname = eval(classname) )
> objectlist[0].method("hello world")
>
> Can this be done? If not, is there a work around or some design pattern
> for this situation?
>
> --
> Venlig hilsen/Kind regards
>
> Michael B. Arp S?rensen
> Programm?r / BOFH
>
> I am /root and if you see me laughing you better have a backup.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
www.fsrtechnologies.com



-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/dae25ac6/attachment.htm 

From marc.tompkins at gmail.com  Fri Dec 28 09:27:25 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 28 Dec 2007 00:27:25 -0800
Subject: [Tutor] Dynamically named objects
In-Reply-To: <9b1867560712272344h1b1161c1xb266bc15af83e06f@mail.gmail.com>
References: <9b1867560712272344h1b1161c1xb266bc15af83e06f@mail.gmail.com>
Message-ID: <40af687b0712280027n6f0cbecdj57499b5c2238ae0c@mail.gmail.com>

Here's the same thing with a list instead of a dictionary:
#===========================================
class thingy():
    example = "Just testing - "
    def __init__(self, num):
        self.example = self.example + str(num)

thang = []
for x in range(1,4):
    thang.append(thingy(x))

for item, value in enumerate(thang):
    print item, value.example
#============================================


On Dec 27, 2007 11:44 PM, Michael Bernhard Arp S?rensen <
michaelarpsorensen at stevnstrup.dk> wrote:

> Hi there.
>
> I need to instantiate objects on the fly and put the in a list/dict for
> later use. I was thinking of this:
>
> objectlist = []
> newobjectname = "object1"
> classname = "class1" + "()"
> objectlist.append(newobjectname = eval(classname) )
> objectlist[0].method("hello world")
>
> Can this be done? If not, is there a work around or some design pattern
> for this situation?
>
> --
> Venlig hilsen/Kind regards
>
> Michael B. Arp S?rensen
> Programm?r / BOFH
>
> I am /root and if you see me laughing you better have a backup.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/0e106a2e/attachment.htm 

From cfuller084 at thinkingplanet.net  Fri Dec 28 09:40:20 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 28 Dec 2007 02:40:20 -0600
Subject: [Tutor] Dynamically named objects
In-Reply-To: <9b1867560712272344h1b1161c1xb266bc15af83e06f@mail.gmail.com>
References: <9b1867560712272344h1b1161c1xb266bc15af83e06f@mail.gmail.com>
Message-ID: <200712280240.20566.cfuller084@thinkingplanet.net>


You might find a dictionary useful. Each element in a dictionary is associated 
with a "key", which can be a string.

objectlist = {}
o = eval("class1" + "()")
objectlist["object1"] = o
o.method("hello world")

Also, try to avoid using eval(), it usually makes troubleshooting and 
maintenance harder and can lead to security problems in some cases. You could 
have a dictionary of classes and look them up on the fly:

classlist = { "classone" : classone, "classtwo" : classtwo }

objectlist = {}
cls = classlist[user_input]
o = cls()
objectlist["object1"] = o
o.method("hello world")

Cheers

From simozack at yahoo.it  Fri Dec 28 11:11:21 2007
From: simozack at yahoo.it (Simone)
Date: Fri, 28 Dec 2007 11:11:21 +0100
Subject: [Tutor] python CLI parser
In-Reply-To: <476C43C7.5020308@alum.rpi.edu>
References: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>
	<476C43C7.5020308@alum.rpi.edu>
Message-ID: <4774CBC9.2070306@yahoo.it>

bob gailer ha scritto:

>> could you have a short review of my CLI package.
> .bz2???  What does that extension mean? (For us Windows folk). Or could 
> you attach a simple zip file?

.bz2 is an archive compressed with the bzip2 compression program. If 
you're on Windows, consider to use 7zip for managing compressed archive 
(www.7zip.org): open source & free (as in freedom) and better, IMHO, 
than WinZip.

Simone
Chiacchiera con i tuoi amici in tempo reale! 
 http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com 

From marc.tompkins at gmail.com  Fri Dec 28 11:51:57 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 28 Dec 2007 02:51:57 -0800
Subject: [Tutor] python CLI parser
In-Reply-To: <4774CBC9.2070306@yahoo.it>
References: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>
	<476C43C7.5020308@alum.rpi.edu> <4774CBC9.2070306@yahoo.it>
Message-ID: <40af687b0712280251n2cb7a1d3ib25b8a8e78649967@mail.gmail.com>

On Dec 28, 2007 2:11 AM, Simone <simozack at yahoo.it> wrote:

> bob gailer ha scritto:
>
> >> could you have a short review of my CLI package.
> > .bz2???  What does that extension mean? (For us Windows folk). Or could
> > you attach a simple zip file?
>
> .bz2 is an archive compressed with the bzip2 compression program. If
> you're on Windows, consider to use 7zip for managing compressed archive
> (www.7zip.org): open source & free (as in freedom) and better, IMHO,
> than WinZip.
>
>
Way, way better!  It can read the following types: arj, bz2, cab, cpio, deb,
gz, iso, lzh, rar, rpm, tar, z, zip, 7z, and 001; it writes 7z, tar, and
zip.
(7z is 7-zip's own format - very tight, very fast compression.  001 is
usually the first part of a multi-part ZIP or RAR file.  ISO is a CD or DVD
image; CAB is a Microsoft cabinet file; DEB and RPM are Linux package files,
and the others are formats we Windows users need to be able to read in order
to become citizens of the world...)

It does self-extracting EXE files "right out of the box" - no extra install,
no "Upgrade to the Professional version to remove this irritating message".
If you're a batch-file maniac like me, it also includes a command-line
interface - again, that's a paid extra with WinZip (or at least it used to
be; I switched to WinRAR years ago and then switched to 7-Zip after a friend
turned me on to it.)  I must admit, the command-line syntax is less
intuitive than WinZip's, but the manual is good.

It's fast and has a spiffy interface and good right-click integration with
Windows Explorer.  It slices!  It dices!  It removes unsightly stains!

Not a paid endorsement - just a happy user.   Sorry to be off-topic, I know
this didn't really belong in the Tutor list...

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/e233ecd1/attachment.htm 

From alan.gauld at btinternet.com  Fri Dec 28 11:14:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 28 Dec 2007 10:14:36 -0000
Subject: [Tutor] Closing GUI program
References: <000601c8491e$05902b40$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <fl2iaf$4kh$1@ger.gmane.org>

"Jim Morcombe" <jmorcombe at westnet.com.au> wrote

> I run it, (By pressing F5 from IDLE), it displays the "Hello world" 
> message.

Don't run GUI programs from within IDLE is the best advice I can give.
It's a lot better than it was and at least they run now but IDLE still 
catches
too many keystrokes and events itself and its a lot safer to test GUI 
programs
by running them outside IDLE. Just double click the file in 
Explorer...

Or to see the errors run it from a DOS prompt.

Alan G. 



From alan.gauld at btinternet.com  Fri Dec 28 11:11:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 28 Dec 2007 10:11:35 -0000
Subject: [Tutor] Microsoft Access
References: <003d01c848f2$4b2b6600$6a00a8c0@ASC000E7B84CF9F><BAY138-DAV13C5FA82C76803216CFDAEE9550@phx.gbl>
	<002001c8490f$b66e2cf0$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <fl2i4q$47f$1@ger.gmane.org>

"Jim Morcombe" <jmorcombe at westnet.com.au> wrote 

> This tutorial seems very specific to PythonWin IDE.  
> I haven't tried it, but it seems to imply that it uses stuff 
> from PythonWin IDE that may not be available in IDLE.  

The IDE is just an IDE - editor and debugger etc.
But the winall package is how you get access to the 
Windows libraries for COM/ADO etc You can download 
winall on top of standard python. You then have the choice 
of IDLE or Pythonwin as an IDE - I prefer Pythonwin.

However if you don;t want to do that you can access Access 
via ODBC using the standard DBAPI for Python using SQL.
That hasthe advantage that you get familiar with DBAPI 
which also works across Oracle, Informix, DB2 etc etc

But if you want to do any kind of complex stuff with 
Windows then the winall package is pretty essential.
And if you get seruious about programming Windows 
from Python the O'Reilly book by Mark Hammond is 
strongly recommended too - it's old now but still the 
best reference on Windows and Python.

HTH,

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


From sewqyne at yahoo.com  Fri Dec 28 12:09:24 2007
From: sewqyne at yahoo.com (Sewqyne Olpo)
Date: Fri, 28 Dec 2007 03:09:24 -0800 (PST)
Subject: [Tutor] Internet Bandwidth Management
Message-ID: <7609.38442.qm@web45910.mail.sp1.yahoo.com>

Hello. I want to restrict internet conncection on windows xp
machine,sometimes to cut off the connection or to reduce the bandwidth
.. But I dont know exactly where to start and what to learn. Could you
give some hints about this?
Thanks in advance.



      ____________________________________________________________________________________
Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  http://tools.search.yahoo.com/newsearch/category.php?category=shopping
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/d9a864b9/attachment.htm 

From cfuller084 at thinkingplanet.net  Fri Dec 28 12:20:44 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 28 Dec 2007 05:20:44 -0600
Subject: [Tutor] python CLI parser
In-Reply-To: <40af687b0712280251n2cb7a1d3ib25b8a8e78649967@mail.gmail.com>
References: <5fa6c12e0712210818h7fe60875x831f15d27a0d5724@mail.gmail.com>
	<4774CBC9.2070306@yahoo.it>
	<40af687b0712280251n2cb7a1d3ib25b8a8e78649967@mail.gmail.com>
Message-ID: <200712280520.44551.cfuller084@thinkingplanet.net>


TUGZip (www.tugzip.com) is another free (as in speech) alternative.  It has a 
distinct interface from 7-zip that some may prefer.

Cheers

From mail at timgolden.me.uk  Fri Dec 28 15:14:02 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 28 Dec 2007 14:14:02 +0000
Subject: [Tutor] Internet Bandwidth Management
In-Reply-To: <7609.38442.qm@web45910.mail.sp1.yahoo.com>
References: <7609.38442.qm@web45910.mail.sp1.yahoo.com>
Message-ID: <477504AA.3070805@timgolden.me.uk>

Sewqyne Olpo wrote:
> Hello. I want to restrict internet conncection on windows xp
> machine,sometimes to cut off the connection or to reduce the bandwidth
> .. But I dont know exactly where to start and what to learn. Could you
> give some hints about this?
> Thanks in advance.

Couple of things: this is really a Windows question first,
although I assume you're (implictly) asking: How do I do
this from within Python? So, if you haven't already, start
searching Windows newsgroups and so on to get some pointers
that way and come back to ask for help on implementing things
in Python.

Secondly, the only way I can think of... although I'm sure
there are others... is to fiddle with the Windows ICF: the
Firewall. I think it can be adjusted via WMI and presumably
by other means as well, so you might try including ICF or
Firewall in your search terms if nothing else shows. I'm
afraid I've never actually tried to do it myself, merely
helped someone out a while back with the WMI mechanics of it.

TJG

From goldwamh at slu.edu  Fri Dec 28 15:38:27 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Fri, 28 Dec 2007 08:38:27 -0600
Subject: [Tutor] Closing GUI program
In-Reply-To: <002c01c84923$e7b8a560$6a00a8c0@ASC000E7B84CF9F>
References: <000601c8491e$05902b40$6a00a8c0@ASC000E7B84CF9F>
	<002c01c84923$e7b8a560$6a00a8c0@ASC000E7B84CF9F>
Message-ID: <18293.2659.855377.842062@euclid.slu.edu>


Hi Jim,

  The problem with your code is that Tk's mainloop continues to run
  even though you have closed the window.  The cleaner way to close
  such a GUI program is to explicitly stop the main loop and the
  Python interpreter at the appropriate time.

  In this particular case, you may provide a callback function that is
  triggered on the event of a window being manually closed by the user.

  Here's a revised version of your program that should work better,
  even within IDLE.  Of course, there is still some system dependency
  among the program, IDLE, and the underlying operating system.

  Some interesting reading is at  http://www.3dartist.com/WP/python/tknotes.htm

With regard,
Michael

-------------------------------------------
from Tkinter import Tk,Label

def onClose():
    root.destroy()   # stops the main loop and interpreter

root = Tk()
root.protocol("WM_DELETE_WINDOW", onClose)  # handle event when window is closed by user
z = Label(root, text="Hello World!")
z.grid()
root.mainloop()
-------------------------------------------

On Friday December 28, 2007, Jim Morcombe wrote: 

>    Oops!  Here's the program:
>    ---------------------------
>    from Tkinter import *     
>    
>    root = Tk()
>    z = Label(root, text="Hello World!")
>    z.grid()
>    root.mainloop()
>    ------------------------------
>    
>    Jim
>    
>      ----- Original Message ----- 
>      From: Jim Morcombe 
>      To: python tutor mailing list 
>      Sent: Friday, December 28, 2007 3:51 PM
>      Subject: [Tutor] Closing GUI program
>    
>    
>      I have copied the following program.  When I run it, (By pressing F5 from IDLE), it displays the "Hello world" message.
>    
>      When I close the window, the "Hello world" message disappears, but it seems that the program is still running, because when I close the shell, i get the message "The program is still running.  Do you want to kill it?"
>    
>      How do I get the program to terminate when the window is closed?
>    
>      Jim


From timmichelsen at gmx-topmail.de  Fri Dec 28 16:31:35 2007
From: timmichelsen at gmx-topmail.de (Tim Michelsen)
Date: Fri, 28 Dec 2007 16:31:35 +0100
Subject: [Tutor] send file/mail to imap
Message-ID: <fl34so$nge$1@ger.gmane.org>

Hello,
I have a mbox file locally on my notebook.

I would like to send this file to my IMAP account using python.

Does anyone know a module or tutorial which does this?

I tried
* IMAPClient 0.3 - http://pypi.python.org/pypi/IMAPClient/0.3
but it doesn't contain a send function.

Thanks in advance for any hints,
Timmie


From mail at timgolden.me.uk  Fri Dec 28 16:51:28 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 28 Dec 2007 15:51:28 +0000
Subject: [Tutor] send file/mail to imap
In-Reply-To: <fl34so$nge$1@ger.gmane.org>
References: <fl34so$nge$1@ger.gmane.org>
Message-ID: <47751B80.90503@timgolden.me.uk>

Tim Michelsen wrote:
> I have a mbox file locally on my notebook.
> 
> I would like to send this file to my IMAP account using python.

Ummm. There seem to be two possible sources of confusion here.

Number one is that you don't normally "send" things via IMAP,
you use the IMAP protocol to *read* messages from a server-based
mail store of some sort.

Number two is that it's not clear whether the "mbox file" is
merely coincidentally a mbox file (ie it might as well be a
text file or a Word doc) or is -- as seems most likely -- a
real mailbox which you want to make available to normal email
clients via your IMAP server.

So... reading way too much between the lines, I deduce that you
want to have the mails in your mbox file available to your
mail clients via your IMAP server. Am I right?

If so, you don't want to use an IMAP client, you want some
other kind of file transfer mechanism, such as FTP or an scp
command to get the file into the appropriate place on your
mail server where the IMAP server will see it. You might
then have to subscribe to it from your clients; depends on
your setup.

TJG

From cfuller084 at thinkingplanet.net  Fri Dec 28 17:05:40 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 28 Dec 2007 10:05:40 -0600
Subject: [Tutor] send file/mail to imap
In-Reply-To: <fl34so$nge$1@ger.gmane.org>
References: <fl34so$nge$1@ger.gmane.org>
Message-ID: <200712281005.40432.cfuller084@thinkingplanet.net>

On Friday 28 December 2007 09:31, Tim Michelsen wrote:
> Hello,
> I have a mbox file locally on my notebook.
>
> I would like to send this file to my IMAP account using python.
>
> Does anyone know a module or tutorial which does this?
>
> I tried
> * IMAPClient 0.3 - http://pypi.python.org/pypi/IMAPClient/0.3
> but it doesn't contain a send function.
>
> Thanks in advance for any hints,
> Timmie
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Batteries included!

http://docs.python.org/lib/module-imaplib.html

Cheers

From doug.shawhan at gmail.com  Fri Dec 28 17:22:51 2007
From: doug.shawhan at gmail.com (doug shawhan)
Date: Fri, 28 Dec 2007 11:22:51 -0500
Subject: [Tutor] Careful Dictionary Building
Message-ID: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>

I'm building a dictionary from a list with ~ 1M records.

Each record in the list is itself a list.
Each record in the list has a line number, (index 0) which I wish to use as
a dictionary key.

The problem: It is possible for two different records in the list to share
this line number. If they do, I want to append the record to the value in
the dictionary.

The obvious (lazy) method of searching for doubled lines requires building
and parsing a key list for every record. There must be a better way!

dict = {}
for record in list
    if record[0] in dict.keys():
        dict[ record[0] ].append( record )
    else:
        dict[ record[0] ] = [record]

Once you get ~ 80,000 records it starts slowing down pretty badly (I would
too ...).

Here's hoping there is a really fast, pythonic way of doing this!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/c44bfc92/attachment.htm 

From doug.shawhan at gmail.com  Fri Dec 28 17:29:49 2007
From: doug.shawhan at gmail.com (doug shawhan)
Date: Fri, 28 Dec 2007 11:29:49 -0500
Subject: [Tutor] Careful Dictionary Building
In-Reply-To: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>
References: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>
Message-ID: <5e1ceb8a0712280829n699cd08cgef1c6561f86756bc@mail.gmail.com>

*sigh* Ignore folks. I had forgotten about .has_key().



On Dec 28, 2007 11:22 AM, doug shawhan <doug.shawhan at gmail.com> wrote:

> I'm building a dictionary from a list with ~ 1M records.
>
> Each record in the list is itself a list.
> Each record in the list has a line number, (index 0) which I wish to use
> as a dictionary key.
>
> The problem: It is possible for two different records in the list to share
> this line number. If they do, I want to append the record to the value in
> the dictionary.
>
> The obvious (lazy) method of searching for doubled lines requires building
> and parsing a key list for every record. There must be a better way!
>
> dict = {}
> for record in list
>     if record[0] in dict.keys ():
>         dict[ record[0] ].append( record )
>     else:
>         dict[ record[0] ] = [record]
>
> Once you get ~ 80,000 records it starts slowing down pretty badly (I would
> too ...).
>
> Here's hoping there is a really fast, pythonic way of doing this!
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/ad2b439e/attachment-0001.htm 

From brunson at brunson.com  Fri Dec 28 17:21:45 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 28 Dec 2007 09:21:45 -0700
Subject: [Tutor] send file/mail to imap
In-Reply-To: <47751B80.90503@timgolden.me.uk>
References: <fl34so$nge$1@ger.gmane.org> <47751B80.90503@timgolden.me.uk>
Message-ID: <47752299.9030008@brunson.com>


Tim's pretty spot on in his ruminations below, I just wanted to add a 
few comments.  Read inline.

Tim Golden wrote:
> Tim Michelsen wrote:
>   
>> I have a mbox file locally on my notebook.
>>
>> I would like to send this file to my IMAP account using python.
>>     
>
> Ummm. There seem to be two possible sources of confusion here.
>
> Number one is that you don't normally "send" things via IMAP,
> you use the IMAP protocol to *read* messages from a server-based
> mail store of some sort.
>
> Number two is that it's not clear whether the "mbox file" is
> merely coincidentally a mbox file (ie it might as well be a
> text file or a Word doc) or is -- as seems most likely -- a
> real mailbox which you want to make available to normal email
> clients via your IMAP server.
>
> So... reading way too much between the lines, I deduce that you
> want to have the mails in your mbox file available to your
> mail clients via your IMAP server. Am I right?
>   

In order to use IMAP, the key word would not be to "send" the messages, 
as Tim points out, which IMAP does not do, but do "copy" the messages 
from one IMAP repository to another.  However, (reading between the 
lines) in order to do that you would need both repositories (mbox and 
your IMAP server) available via the IMAP protocol and I doubt you have 
IMAP access to the local mbox file.

> If so, you don't want to use an IMAP client, you want some
> other kind of file transfer mechanism, such as FTP or an scp
> command to get the file into the appropriate place on your
> mail server where the IMAP server will see it. You might
> then have to subscribe to it from your clients; depends on
> your setup.
>   

This would definitely be the correct approach if your IMAP server uses 
an mbox store and you have the ability to directly manipulate those 
stores outside of the IMAP interface, i.e. root privs on the mail 
server.  However, knowing that all but the most rudimentary IMAP servers 
do *not* use mbox and that there's a good possibility (based on your 
initial question) that you do *not* have direct access to the mail 
backend, I think your best solution would be to resend the emails via 
SMTP to your mail server where they would be delivered as if they had 
been sent there initially.

This can definitely be done via smtplib in Python by opening the mbox 
file and iterating over the messages, but you may want to look at the 
fetchmail utility and see if that has the capabilities (on your local 
platform) required to access the mbox file directly.  It's a mighty 
capable utility and may be able to take care of this in a single shot.

Hope that helps,
e.

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


From ian505 at gmail.com  Fri Dec 28 17:36:37 2007
From: ian505 at gmail.com (Ian Egland)
Date: Fri, 28 Dec 2007 11:36:37 -0500
Subject: [Tutor] How to stop a script.
In-Reply-To: <fd42efd50712280832i3d258f46x3d2bb1627a91b69@mail.gmail.com>
References: <fd42efd50712280832i3d258f46x3d2bb1627a91b69@mail.gmail.com>
Message-ID: <fd42efd50712280836q6fa5c3e1pdcaadd1bb725deec@mail.gmail.com>

Hi everyone... I litterally just started python and did the following 'hello
world' related tutorial.

http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro
<http://hkn.eecs.berkeley.edu/%7Edyoo/python/idle_intro>

Being the kind of person who like to experiment, I tried changing the
following script from:

print "Hello World!"
print "Here are the ten numbers from 0 to 9, just in case you can't count."
for i in range(10):
    print i,

print "I'm done!"

to:

print "Hello World!"
print "Here are the ten numbers from 0 to 9, just in case you can't count."
for i in range(10000000):
    print i,

print "I'm done!


Now I am stuck staring at IDLE as it prints out all 10million numbers.....
Is there a way other than closing the shell to stop a script midway through
execution?

-Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/e9a66bff/attachment.htm 

From brunson at brunson.com  Fri Dec 28 17:43:02 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 28 Dec 2007 09:43:02 -0700
Subject: [Tutor] Careful Dictionary Building
In-Reply-To: <5e1ceb8a0712280829n699cd08cgef1c6561f86756bc@mail.gmail.com>
References: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>
	<5e1ceb8a0712280829n699cd08cgef1c6561f86756bc@mail.gmail.com>
Message-ID: <47752796.1050407@brunson.com>

doug shawhan wrote:
> *sigh* Ignore folks. I had forgotten about .has_key().

Actually, you don't even need that, simply write:

if record[0] in dict:
   # Do your thing.

But don't use "dict" as a variable name, it's a builtin function name.

>
>
>
> On Dec 28, 2007 11:22 AM, doug shawhan <doug.shawhan at gmail.com 
> <mailto:doug.shawhan at gmail.com>> wrote:
>
>     I'm building a dictionary from a list with ~ 1M records.
>
>     Each record in the list is itself a list.
>     Each record in the list has a line number, (index 0) which I wish
>     to use as a dictionary key.
>
>     The problem: It is possible for two different records in the list
>     to share this line number. If they do, I want to append the record
>     to the value in the dictionary.
>
>     The obvious (lazy) method of searching for doubled lines requires
>     building and parsing a key list for every record. There must be a
>     better way!
>
>     dict = {}
>     for record in list
>         if record[0] in dict.keys ():
>             dict[ record[0] ].append( record )
>         else:
>             dict[ record[0] ] = [record]
>
>     Once you get ~ 80,000 records it starts slowing down pretty badly
>     (I would too ...).
>
>     Here's hoping there is a really fast, pythonic way of doing this!
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From cfuller084 at thinkingplanet.net  Fri Dec 28 18:05:00 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 28 Dec 2007 11:05:00 -0600
Subject: [Tutor] Careful Dictionary Building
In-Reply-To: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>
References: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>
Message-ID: <200712281105.00784.cfuller084@thinkingplanet.net>

first thing.. you are duplicating a lot of effort inside your loops. getting 
rid of that will speed things up:

dict = {}
for record in list:
    rid = record[0]
??? if rid in dict:
??????? dict[ rid ].append( record )
??? else:
??????? dict[ rid ] = [record]

The other thing I see isn't a speed problem. You are overwriting two python 
built-in types when you use variables named "list" and "dict". You probably 
want to avoid doing this, because someday yuou want to use the built-ins, and 
you code wil exhibit goofy errors when you try.

The only thing I can suggest that might speed it up more is to use a set type 
instead of a list, if the ordering doesn't matter to you. I've seen that 
change result in 20-30 percent speedups, but YMMV. If you can't start with a 
set, you can create a new one by passing the list to the set constructor. 
This may or may not help you speedwise, but try it out.

You could play around with psyco, but I don't know if it would help much in 
this case.

Chris

From mlangford.cs03 at gtalumni.org  Fri Dec 28 18:49:00 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Fri, 28 Dec 2007 12:49:00 -0500
Subject: [Tutor] Careful Dictionary Building
In-Reply-To: <5e1ceb8a0712280829n699cd08cgef1c6561f86756bc@mail.gmail.com>
References: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>
	<5e1ceb8a0712280829n699cd08cgef1c6561f86756bc@mail.gmail.com>
Message-ID: <82b4f5810712280949l68905d49h9233c43188482d04@mail.gmail.com>

This functionality already exists in the ever so useful defaultdict object.
You pass a factory method to the constructor of defaultdict for an object,
and it returns a new object when there is no key:

from collections import defaultdict
mydict = defaultdict(list)
for record in mylist:
        mydict[ record[0] ].append( record )

defaultdict is usually good enough for datasets I've used it for.

         --Michael



On 12/28/07, doug shawhan <doug.shawhan at gmail.com> wrote:
>
> *sigh* Ignore folks. I had forgotten about .has_key().
>
>
>
> On Dec 28, 2007 11:22 AM, doug shawhan <doug.shawhan at gmail.com> wrote:
>
> > I'm building a dictionary from a list with ~ 1M records.
> >
> > Each record in the list is itself a list.
> > Each record in the list has a line number, (index 0) which I wish to use
> > as a dictionary key.
> >
> > The problem: It is possible for two different records in the list to
> > share this line number. If they do, I want to append the record to the value
> > in the dictionary.
> >
> > The obvious (lazy) method of searching for doubled lines requires
> > building and parsing a key list for every record. There must be a better
> > way!
> >
> > dict = {}
> > for record in list
> >     if record[0] in dict.keys ():
> >         dict[ record[0] ].append( record )
> >     else:
> >         dict[ record[0] ] = [record]
> >
> > Once you get ~ 80,000 records it starts slowing down pretty badly (I
> > would too ...).
> >
> > Here's hoping there is a really fast, pythonic way of doing this!
> >
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/1bc904aa/attachment.htm 

From doug.shawhan at gmail.com  Fri Dec 28 19:14:38 2007
From: doug.shawhan at gmail.com (doug shawhan)
Date: Fri, 28 Dec 2007 13:14:38 -0500
Subject: [Tutor] Tutor] Careful Dictionary Building
In-Reply-To: <8249c4ac0712280923k663cd9f5uea1c59cacde1a362@mail.gmail.com>
References: <8249c4ac0712280923k663cd9f5uea1c59cacde1a362@mail.gmail.com>
Message-ID: <5e1ceb8a0712281014l7818ba63udd6347ab87381ab5@mail.gmail.com>

Lots of very good answers to a pretty stupid question! *blush*

I guess there is more than one way to do it!

Uh ... guys? Did I say something wrong...?

<sounds of a thorough beating with a haddock>

On Dec 28, 2007 12:23 PM, Tony *** <****@gmail.com> wrote:

> Hello Doug,
>
> You can also use exceptions instead of the if /else. It has more of a
> pythonic syntax to it, but I'm not sure about performance.
>
> try:
>    dict[ record[0] .append( record ) ]
> except:KeyError
>
>     dict[ record[0] ] = [record]
>
>
> To help performance a bit, don't call dict.keys() on every iteration,
> since you're invoking a function.
>
> dict = {}
> allKeys =dict.Keys
> for record in list
>   if record[0] in allKeys:
>       dict[ record[0] .append( record ) ]
>   else:
>       dict[ record[0] ] = [record]
>       allKeys = dict.Keys()                    # this function is
> only invoked some of the time, not on every iteration
>
>
> See how much this helps your performance. It  may not be much, but a
> little can help
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/ca803ce4/attachment.htm 

From ian505 at gmail.com  Fri Dec 28 20:17:52 2007
From: ian505 at gmail.com (Ian Egland)
Date: Fri, 28 Dec 2007 14:17:52 -0500
Subject: [Tutor] How to stop a script.
In-Reply-To: <40af687b0712281016s425557o9cb8bd7233c65a62@mail.gmail.com>
References: <fd42efd50712280832i3d258f46x3d2bb1627a91b69@mail.gmail.com>
	<fd42efd50712280836q6fa5c3e1pdcaadd1bb725deec@mail.gmail.com>
	<40af687b0712281016s425557o9cb8bd7233c65a62@mail.gmail.com>
Message-ID: <fd42efd50712281117s277486e8v7edfafeaead07cb7@mail.gmail.com>

Yea I think that I will wait till I get sea legs for the first time, hehe.

On Dec 28, 2007 1:16 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:

> As far as I know, not unless you either 1) use threading and put the
> killable process in a separate thread or 2) stop and check for input once in
> a while, which will make things much much slower.   If you're anything like
> me, threading is something you'll want to put off for a month or so while
> you get your Python sea legs...
>
> On Dec 28, 2007 8:36 AM, Ian Egland <ian505 at gmail.com> wrote:
>
> > Hi everyone... I litterally just started python and did the following
> > 'hello world' related tutorial.
> >
> > http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro
> > <http://hkn.eecs.berkeley.edu/%7Edyoo/python/idle_intro>
> >
> > Being the kind of person who like to experiment, I tried changing the
> > following script from:
> >
> > print "Hello World!"
> > print "Here are the ten numbers from 0 to 9, just in case you can't
> > count."
> > for i in range(10):
> >     print i,
> >
> > print "I'm done!"
> >
> > to:
> >
> > print "Hello World!"
> > print "Here are the ten numbers from 0 to 9, just in case you can't
> > count."
> > for i in range(10000000):
> >     print i,
> >
> > print "I'm done!
> >
> >
> > Now I am stuck staring at IDLE as it prints out all 10million
> > numbers.....
> > Is there a way other than closing the shell to stop a script midway
> > through execution?
> >
> > -Ian
> >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>
> --
> www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/80796860/attachment-0001.htm 

From kent37 at tds.net  Fri Dec 28 20:28:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 28 Dec 2007 14:28:06 -0500
Subject: [Tutor] Tutor] Careful Dictionary Building
In-Reply-To: <5e1ceb8a0712281014l7818ba63udd6347ab87381ab5@mail.gmail.com>
References: <8249c4ac0712280923k663cd9f5uea1c59cacde1a362@mail.gmail.com>
	<5e1ceb8a0712281014l7818ba63udd6347ab87381ab5@mail.gmail.com>
Message-ID: <47754E46.3060009@tds.net>

doug shawhan wrote:

>     To help performance a bit, don't call dict.keys() on every iteration,
>     since you're invoking a function.
> 
>     dict = {}
>     allKeys =dict.Keys

Should be dict.keys()

>     for record in list
>       if record[0] in allKeys:
>           dict[ record[0] .append( record ) ]

Should be
   dict[record[0]].append(record)

>       else:
>           dict[ record[0] ] = [record]
>           allKeys = dict.Keys()                    # this function is
>     only invoked some of the time, not on every iteration

So you only create the list of keys when it changes; that may speed up 
the loop, depending on how many duplicates there are. But there are two 
big problems with the original program - it creates a new list of keys 
each time through the loop, and it searches for a key in the list 
instead of looking it up directly in the dict. Your change may cut down 
on the number of times the key list is created but it will not improve 
the search time at all.

In other words, you are making modest improvements to a broken 
algorithm; a better fix is to use a better algorithm.

Kent

From keridee at jayco.net  Fri Dec 28 23:42:43 2007
From: keridee at jayco.net (Tiger12506)
Date: Fri, 28 Dec 2007 17:42:43 -0500
Subject: [Tutor] How to stop a script.
References: <fd42efd50712280832i3d258f46x3d2bb1627a91b69@mail.gmail.com><fd42efd50712280836q6fa5c3e1pdcaadd1bb725deec@mail.gmail.com><40af687b0712281016s425557o9cb8bd7233c65a62@mail.gmail.com>
	<fd42efd50712281117s277486e8v7edfafeaead07cb7@mail.gmail.com>
Message-ID: <003e01c849a2$f9d82200$8efde004@jslaptop>

Ctrl+c will issue a KeyboardInterrupt which breaks out of programs such as 
the one you described. (The only situation it doesn't is when the program 
catches that exception. You won't see that 'til you get your sea legs ;-) 


From ian505 at gmail.com  Fri Dec 28 23:51:52 2007
From: ian505 at gmail.com (Ian Egland)
Date: Fri, 28 Dec 2007 17:51:52 -0500
Subject: [Tutor] Fwd:  How to stop a script.
In-Reply-To: <003e01c849a2$f9d82200$8efde004@jslaptop>
References: <fd42efd50712280832i3d258f46x3d2bb1627a91b69@mail.gmail.com>
	<fd42efd50712280836q6fa5c3e1pdcaadd1bb725deec@mail.gmail.com>
	<40af687b0712281016s425557o9cb8bd7233c65a62@mail.gmail.com>
	<fd42efd50712281117s277486e8v7edfafeaead07cb7@mail.gmail.com>
	<003e01c849a2$f9d82200$8efde004@jslaptop>
Message-ID: <fd42efd50712281451i4773c1a7y29c48af01dd26524@mail.gmail.com>

Thanks, I will keep that in mind the next time I  "experiment". :-P

-Ian

---------- Forwarded message ----------
From: Tiger12506 <keridee at jayco.net>
Date: Dec 28, 2007 5:42 PM
Subject: Re: [Tutor] How to stop a script.
To: tutor at python.org


Ctrl+c will issue a KeyboardInterrupt which breaks out of programs such as
the one you described. (The only situation it doesn't is when the program
catches that exception. You won't see that 'til you get your sea legs ;-)

_______________________________________________
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/20071228/97295fe9/attachment.htm 

From michaelarpsorensen at stevnstrup.dk  Sat Dec 29 16:58:39 2007
From: michaelarpsorensen at stevnstrup.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=)
Date: Sat, 29 Dec 2007 16:58:39 +0100
Subject: [Tutor] Learning about callbaks
Message-ID: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>

Hi there.

I want to learn about callbacks because we use it at work in our software.

I there a short "hello world"-like version of a callback example?

-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071229/66d96ca0/attachment.htm 

From keridee at jayco.net  Sat Dec 29 17:48:10 2007
From: keridee at jayco.net (Tiger12506)
Date: Sat, 29 Dec 2007 11:48:10 -0500
Subject: [Tutor] Learning about callbaks
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
Message-ID: <002501c84a3a$b2375b30$3dfce004@jslaptop>

Callbacks are where you send python (or a library) a function which it can 
call(back). They are usually used to make things a little more generic. 
Here's a (trying to make it simple) example.

######## example.py ###########

# These first three are callback functions (nothing special
# is needed to make them a callback function)
def printtoscreen(s):
    print s

def printdifferently(s):
    s = s.upper()
    print s

def printtofile(s):
    fobj = file("output.txt","a")
    fobj.write(s)
    fobj.close()

# this is the generic function that uses callbacks
def doPrint(s, callbackfunc):
    callbackfunc(s)

# and then we can use it however we wish
# because doPrint never has to change
# no matter how, or to what we are printing.
doPrint("HelloWorld!", printtofile)
doPrint("Hello World!", printtoscreen)
doPrint("ascii", printdifferently)
##############################


----- Original Message ----- 
From: "Michael Bernhard Arp S?rensen" <michaelarpsorensen at stevnstrup.dk>
To: <tutor at python.org>
Sent: Saturday, December 29, 2007 10:58 AM
Subject: [Tutor] Learning about callbaks


Hi there.

I want to learn about callbacks because we use it at work in our software.

I there a short "hello world"-like version of a callback example?

-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.



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


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


From alan.gauld at btinternet.com  Sat Dec 29 18:39:56 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 29 Dec 2007 17:39:56 -0000
Subject: [Tutor] Learning about callbaks
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
Message-ID: <fl60pg$sg1$1@ger.gmane.org>


"Michael Bernhard Arp S?rensen" <michaelarpsorensen at stevnstrup.dk> 
wrote

> I want to learn about callbacks because we use it at work in our 
> software.

Can you be more specific about what you want to know. Callbacks are
used in many different ways from event handling methods in a GUI
to network programming to simulating synchronous protocols over
an asynchronous connection.

> I there a short "hello world"-like version of a callback example?

See almost any GUI tutorial.
The recent thread "Closing GUI program" had the following example
from Michael Goldwasser

#-------------------------------------------
from Tkinter import Tk,Label

def onClose():
    root.destroy()   # stops the main loop and interpreter

root = Tk()
root.protocol("WM_DELETE_WINDOW", onClose)  # handle event when window 
is closed by user
z = Label(root, text="Hello World!")
z.grid()
root.mainloop()
#-------------------------------------------


In this example the onClose() event handler is a callback function.

The folowing pseusdo code shows how the principle can be used for
asynchronous network programming:

waiting = {}     # list of objects awaiting responses
id = 0

def sendToServer(msg, callback)
       msgSent = prepareMessage(msg)
       id = server.send(msgSent)
       waiting[id] = (msg, callback)

def func1()
     msg = prepareData()
     sendToServer(msg, func1_cont)

def func1_cont(original, result)
     x,y,z = result.getValues()
     processData(x,y,z,original.p,original.q)

while server.listen()
      msg = server.recv()
      id = msg.getID()
      oldMessage = waiting[id][0]
      callback =  waiting[id][1]
      callback(oldmessage, msg)
      del(waiting[id])

In this example we can think of the main application calling func.
func1 needs to send a message to a server and process the response
but the server has an asynchronous protocol so we split the function
into func1 and func1_cont at the point of calling the server. Then
when the server send us the response we pull the stored state out
of the dictionary and combine it with the server data to complete
the func1 processing via the func1_cont callback.

In practice we'd probably store the date/time with the transaction
data so that we can check for timeouts etc in a separate thread...

The important thing with all callbacks is that you match up the
data expected by the callback with the data actually available
at the point of calling it. In this case we take the architectural
decision to pass callback functions the old and new data structures.
We could alternatively have passed the transaction id and let the
callback retrieve (and delete) the data from the waiting list.

I hope that all makes sense.

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



From michaelarpsorensen at stevnstrup.dk  Sat Dec 29 19:23:18 2007
From: michaelarpsorensen at stevnstrup.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=)
Date: Sat, 29 Dec 2007 19:23:18 +0100
Subject: [Tutor] Learning about callbaks
In-Reply-To: <fl60pg$sg1$1@ger.gmane.org>
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
	<fl60pg$sg1$1@ger.gmane.org>
Message-ID: <9b1867560712291023m6cec4feap2a2325f51055c901@mail.gmail.com>

Greetings, my master.

I'm writing a game based on curses.

I have my own screen object and several child objects to handle sub windows
with e.g. menues, board/map/views and log outputs. All user input is done
with screen.getch and later sent to the dynamic menu for selecting menu
points.

My imidiate problem is when I select "Quit" from the menu, I need to send
the string back to the caller/parent class for evaluation.

Later I will need to design all the menues and the related methods, other
sub windows in different threads for individual updates. But first I need a
working UI.

Off topic: I must say that I'm amazed by this tutor thing. To really have my
"own" tutor in this new programming language I'm learning, is kinda blowing
my mind. I hope I can repay the python community some day when I'm smart
enough. :-)

Thanks in advance

/karneevor

On Dec 29, 2007 6:39 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

>
> "Michael Bernhard Arp S?rensen" <michaelarpsorensen at stevnstrup.dk>
> wrote
>
> > I want to learn about callbacks because we use it at work in our
> > software.
>
> Can you be more specific about what you want to know. Callbacks are
> used in many different ways from event handling methods in a GUI
> to network programming to simulating synchronous protocols over
> an asynchronous connection.
>
> > I there a short "hello world"-like version of a callback example?
>
> See almost any GUI tutorial.
> The recent thread "Closing GUI program" had the following example
> from Michael Goldwasser
>
> #-------------------------------------------
> from Tkinter import Tk,Label
>
> def onClose():
>    root.destroy()   # stops the main loop and interpreter
>
> root = Tk()
> root.protocol("WM_DELETE_WINDOW", onClose)  # handle event when window
> is closed by user
> z = Label(root, text="Hello World!")
> z.grid()
> root.mainloop()
> #-------------------------------------------
>
>
> In this example the onClose() event handler is a callback function.
>
> The folowing pseusdo code shows how the principle can be used for
> asynchronous network programming:
>
> waiting = {}     # list of objects awaiting responses
> id = 0
>
> def sendToServer(msg, callback)
>       msgSent = prepareMessage(msg)
>       id = server.send(msgSent)
>       waiting[id] = (msg, callback)
>
> def func1()
>     msg = prepareData()
>     sendToServer(msg, func1_cont)
>
> def func1_cont(original, result)
>     x,y,z = result.getValues()
>     processData(x,y,z,original.p,original.q)
>
> while server.listen()
>      msg = server.recv()
>      id = msg.getID()
>      oldMessage = waiting[id][0]
>      callback =  waiting[id][1]
>      callback(oldmessage, msg)
>      del(waiting[id])
>
> In this example we can think of the main application calling func.
> func1 needs to send a message to a server and process the response
> but the server has an asynchronous protocol so we split the function
> into func1 and func1_cont at the point of calling the server. Then
> when the server send us the response we pull the stored state out
> of the dictionary and combine it with the server data to complete
> the func1 processing via the func1_cont callback.
>
> In practice we'd probably store the date/time with the transaction
> data so that we can check for timeouts etc in a separate thread...
>
> The important thing with all callbacks is that you match up the
> data expected by the callback with the data actually available
> at the point of calling it. In this case we take the architectural
> decision to pass callback functions the old and new data structures.
> We could alternatively have passed the transaction id and let the
> callback retrieve (and delete) the data from the waiting list.
>
> I hope that all makes sense.
>
> --
> 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
>



-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071229/91ae5d51/attachment.htm 

From dkuhlman at rexx.com  Sat Dec 29 19:58:26 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 29 Dec 2007 10:58:26 -0800
Subject: [Tutor] Learning about callbaks
In-Reply-To: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
Message-ID: <20071229185826.GA30751@cutter.rexx.com>

On Sat, Dec 29, 2007 at 04:58:39PM +0100, Michael Bernhard Arp S?rensen wrote:
> Hi there.
> 
> I want to learn about callbacks because we use it at work in our software.
> 
> I there a short "hello world"-like version of a callback example?
> 

In Python, any object that can be *called* can be considered a
call-back.  The Pythonic way of describing these objects is to say
that they are "callable".  You can detect whether an object is
callable by using "dir(obj)", then looking for an attribute named
"__call__".

Objects defined with "def" (functions and methods) and "lambda"
provide that automatically.  And, if you implement a class
containing a method name "__call__", then instances of that class
will be callable (and can be used as call-backs) also.

Python's consistent use of first-class objects makes using
callables/call-backs so simple that it is almost hard to
explain.  Just stuff that callable (function, method, lambda, or
instance with a "__call__" method) into a data structure or pass it
to a function, then when you are ready to use it, apply the
function call "operator" (parentheses).

Here is a trivial example:

    def f1(x):
        print 'f1: %s' % x

    def f2(x):
        print 'f2: %s' % x

    def use_them(funcs):
        for func in funcs:
            func('abcd')

    def test():
        funcs = [f1, f2]
        use_them(funcs)

    test()

- Dave



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

From reed at reedobrien.com  Sat Dec 29 21:04:05 2007
From: reed at reedobrien.com (Reed O'Brien)
Date: Sat, 29 Dec 2007 15:04:05 -0500
Subject: [Tutor] Careful Dictionary Building
In-Reply-To: <5e1ceb8a0712280829n699cd08cgef1c6561f86756bc@mail.gmail.com>
References: <5e1ceb8a0712280822p13363136u568c6e2109f6f540@mail.gmail.com>
	<5e1ceb8a0712280829n699cd08cgef1c6561f86756bc@mail.gmail.com>
Message-ID: <C293E0F1-4078-4AC2-8A3B-A33FD12CD84D@reedobrien.com>

On Dec 28, 2007, at 11:29 AM, doug shawhan wrote:

> *sigh* Ignore folks. I had forgotten about .has_key().

.has_key() is deprecated in 2.6 and goes away in 3.0 IIRC

You should use

record in D

or

D.get(record)


>
> On Dec 28, 2007 11:22 AM, doug shawhan <doug.shawhan at gmail.com> wrote:
> I'm building a dictionary from a list with ~ 1M records.
>
> Each record in the list is itself a list.
> Each record in the list has a line number, (index 0) which I wish  
> to use as a dictionary key.
>
> The problem: It is possible for two different records in the list  
> to share this line number. If they do, I want to append the record  
> to the value in the dictionary.
>
> The obvious (lazy) method of searching for doubled lines requires  
> building and parsing a key list for every record. There must be a  
> better way!
>
> dict = {}
> for record in list
>     if record[0] in dict.keys ():
>         dict[ record[0] ].append( record )
>     else:
>         dict[ record[0] ] = [record]
>
> Once you get ~ 80,000 records it starts slowing down pretty badly  
> (I would too ...).
>
> Here's hoping there is a really fast, pythonic way of doing this!
>
> _______________________________________________
> 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/20071229/a90b3c9f/attachment-0001.htm 

From ptmcg at austin.rr.com  Sat Dec 29 22:15:27 2007
From: ptmcg at austin.rr.com (Paul McGuire)
Date: Sat, 29 Dec 2007 15:15:27 -0600
Subject: [Tutor] Careful Dictionary Building
In-Reply-To: <mailman.12451.1198958688.13604.tutor@python.org>
References: <mailman.12451.1198958688.13604.tutor@python.org>
Message-ID: <003301c84a5f$efad4e00$7a00a8c0@AWA2>

1. Don't name your dict 'dict' or your list 'list', as this then masks the
builtin dict and list types.
2. Your application is a textbook case for defaultdict:
    
from collections import defaultdict

recordDict = defaultdict(list)
for record in recordList:
    recordDict[record[0]].append(record)

Voila!  No key checking, no keeping of separate key lists (wrong for many
other reasons, too), just let defaultdict do the work.  If the key does not
exist, then defaultdict will use the factory method specified in its
constructor (in this case, list) to initialize a new entry, and then the new
record is appended to the empty list.  If the key does exist, then you
retreive the list that's been built so far, and then the new record gets
appended.

-- Paul


From alan.gauld at btinternet.com  Sun Dec 30 10:17:42 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 30 Dec 2007 09:17:42 -0000
Subject: [Tutor] Learning about callbaks
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com><fl60pg$sg1$1@ger.gmane.org>
	<9b1867560712291023m6cec4feap2a2325f51055c901@mail.gmail.com>
Message-ID: <fl7nnq$m6o$1@ger.gmane.org>

"Michael Bernhard Arp S?rensen" <michaelarpsorensen at stevnstrup.dk> 
wrote

> Greetings, my master.

Nah, there are no masters on the tutor list, we are all learning 
together,
just at different stages. If you really want the masters go to
comp.lang.python! :-)

> I'm writing a game based on curses.

OK, That gives us a much better context from which to work.

> My imidiate problem is when I select "Quit" from the menu, I need to
> send the string back to the caller/parent class for evaluation.

For a good quick tutorial on programming menus in curses try
David Metz' article from his excellent Charming Python series
- a resouerce every Python programmer should read IMHO...

http://www.ibm.com/developerworks/linux/library/l-python6.html

> Off topic: I must say that I'm amazed by this tutor thing.

Yes, the Python tutor list is one of the best features of Python.

> I hope I can repay the python community some day when
> I'm smart enough. :-)

Just keep reading and when you one day see a question you
can answer jump in! Participation is the life blood of Open
Source software at every level.

Enjoy,

Alan G.



From tiagosaboga at terra.com.br  Sun Dec 30 14:48:53 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Sun, 30 Dec 2007 11:48:53 -0200
Subject: [Tutor] Learning about callbaks
In-Reply-To: <fl7nnq$m6o$1@ger.gmane.org>
References: <9b1867560712291023m6cec4feap2a2325f51055c901@mail.gmail.com>
	<fl7nnq$m6o$1@ger.gmane.org>
Message-ID: <20071230134853.GA19594@localdomain>

On Sun, Dec 30, 2007 at 09:17:42AM -0000, Alan Gauld wrote:
> Yes, the Python tutor list is one of the best features of Python.

This expresses exactly the way I feel about python. Everytime I have
to work in another language, I keep asking myself: but where is the
tutor mailing list for this language?

Tiago.

From sabya.pal at gmail.com  Mon Dec 31 06:10:11 2007
From: sabya.pal at gmail.com (Sabyasachi Pal)
Date: Mon, 31 Dec 2007 10:40:11 +0530
Subject: [Tutor] Installing problem in matplotlib
Message-ID: <cd1b883a0712302110uc19d97eqabf59be66c1649dc@mail.gmail.com>

HI,

While installing matplot lib, I am facing errors given below after
trying "python setup.py build". I made it sure that freetype (>=
2.1.7), libpng and zlib are installed along with there devel versions.
Can any one help?

 running build
running build_py
copying lib/matplotlib/mpl-data/matplotlibrc ->
build/lib.linux-i686-2.5/matplot lib/mpl-data
running build_ext
building 'matplotlib.backends._tkagg' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall
-Wp,-D_FORTIFY_SOU RCE=2 -fexceptions -fstack-protector
--param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic
-fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fPIC -I/usr/inc lude
-I/usr/include -I/usr/local/include -I/usr/include -I. -Isrc -Iswig
-Iagg23 /include -I. -I/usr/local/include -I/usr/include -I.
-I/usr/include/freetype2 -I /usr/include/freetype2
-I/usr/local/include/freetype2 -I/usr/include/freetype2 - I./freetype2
-Isrc/freetype2 -Iswig/freetype2 -Iagg23/include/freetype2 -I./free
type2 -I/usr/local/include/freetype2 -I/usr/include/freetype2
-I./freetype2 -I/u sr/include/python2.5 -c src/_tkagg.cpp -o
build/temp.linux-i686-2.5/src/_tkagg.o
src/_tkagg.cpp:28:18: error: tk.h: No such file or directory
src/_tkagg.cpp:36: error: ISO C++ forbids declaration of 'Tcl_Interp'
with no ty pe
src/_tkagg.cpp:36: error: expected ';' before '*' token
src/_tkagg.cpp:40: error: 'ClientData' was not declared in this scope
src/_tkagg.cpp:40: error: 'Tcl_Interp' was not declared in this scope
src/_tkagg.cpp:40: error: 'interp' was not declared in this scope
src/_tkagg.cpp:41: error: expected primary-expression before 'int'
src/_tkagg.cpp:41: error: expected primary-expression before 'char'
src/_tkagg.cpp:41: error: initializer expression list treated as
compound expres sion
src/_tkagg.cpp:42: error: expected ',' or ';' before '{' token
./CXX/Extensions.hxx: In constructor
'Py::PythonExtension<T>::PythonExtension() [with T = BufferRegion]':
src/_backend_agg.h:61:   instantiated from here
./CXX/Extensions.hxx:477: warning: right-hand operand of comma has no effect
./CXX/Extensions.hxx: In constructor
'Py::PythonExtension<T>::PythonExtension() [with T = LazyValue]':
src/_transforms.h:27:   instantiated from here
./CXX/Extensions.hxx:477: warning: right-hand operand of comma has no effect
./CXX/Extensions.hxx: In constructor
'Py::PythonExtension<T>::PythonExtension() [with T = Func]':
src/_transforms.h:379:   instantiated from here
./CXX/Extensions.hxx:477: warning: right-hand operand of comma has no effect
./CXX/Extensions.hxx: In constructor
'Py::PythonExtension<T>::PythonExtension() [with T = FuncXY]':
src/_transforms.h:466:   instantiated from here
./CXX/Extensions.hxx:477: warning: right-hand operand of comma has no effect
./CXX/Extensions.hxx: In constructor
'Py::PythonExtension<T>::PythonExtension() [with T = Transformation]':
src/_transforms.h:538:   instantiated from here
./CXX/Extensions.hxx:477: warning: right-hand operand of comma has no effect
src/_tkagg.cpp: At global scope:
src/_tkagg.cpp:40: warning: 'PyAggImagePhoto' defined but not used
error: command 'gcc' failed with exit status 1

With regards
Sabyasachi

From alan.gauld at btinternet.com  Mon Dec 31 09:30:42 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 31 Dec 2007 08:30:42 -0000
Subject: [Tutor] Installing problem in matplotlib
References: <cd1b883a0712302110uc19d97eqabf59be66c1649dc@mail.gmail.com>
Message-ID: <fla9bm$j18$1@ger.gmane.org>


"Sabyasachi Pal" <sabya.pal at gmail.com> wrote

> While installing matplot lib, I am facing errors given below after
> trying "python setup.py build". I made it sure that freetype (>=
> 2.1.7), libpng and zlib are installed along with there devel 
> versions.
> Can any one help?

Not an expert in matplotlib but...

> gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall
> src/_tkagg.cpp:28:18: error: tk.h: No such file or directory
> src/_tkagg.cpp:36: error: ISO C++ forbids declaration of 
> 'Tcl_Interp'

This is saying it can't find tk.h which implies you don't have the
devel version of Tcl/Tk installed.

Since tk.h contains all the tk function/type definitions most of the
other errors looik like they are related to this missing header file 
too.

HTH.

Alan G 



From agoldgod at gmail.com  Mon Dec 31 13:19:58 2007
From: agoldgod at gmail.com (goldgod a)
Date: Mon, 31 Dec 2007 17:49:58 +0530
Subject: [Tutor] how to sort the data inside the file.
Message-ID: <105c9ccc0712310419r78143ce3h6d896c37bb043c7e@mail.gmail.com>

hello all,
            Please find the attached file. I want to sort the content
of this file based on the "bytes" in descending order. How can i do
it, any pointers to it.

-- 
Thanks & Regards,
goldgod
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test
Type: application/octet-stream
Size: 13257 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20071231/e60260cd/attachment.obj 

From cfuller084 at thinkingplanet.net  Mon Dec 31 14:00:16 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Mon, 31 Dec 2007 07:00:16 -0600
Subject: [Tutor] Installing problem in matplotlib
In-Reply-To: <cd1b883a0712302110uc19d97eqabf59be66c1649dc@mail.gmail.com>
References: <cd1b883a0712302110uc19d97eqabf59be66c1649dc@mail.gmail.com>
Message-ID: <200712310700.17138.cfuller084@thinkingplanet.net>


Is there a reason you are building from scratch?  There are binaries for 
win32, and most linux distributions.

You will need the development packages for libpng, zlib, and freetype, and 
others, depending on the GUI backends you want to use.  These can be 
configured in the setup.cfg file.  See 
http://matplotlib.sourceforge.net/installing.html.

If you are doing something like creating images for a web server, you may not 
need any GUI backends at all.  This is not an unusual use-case!

If you don't know which backend you'd like to use, select Tk, GTK, and wx.  
This will cover the examples and give you a feel for the different toolkits.  
Tk is a nice one for beginners, although the others are generally faster, 
better looking, and more capable, although the just-released new version of 
Tk addresses most of these.  Que flamewar.

I use GTK myself, but I still have a fondness for the simplicity and elegance 
of Tk, and still use it for quick and simple tasks.

Cheers

From kent37 at tds.net  Mon Dec 31 14:31:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 31 Dec 2007 08:31:47 -0500
Subject: [Tutor] how to sort the data inside the file.
In-Reply-To: <105c9ccc0712310419r78143ce3h6d896c37bb043c7e@mail.gmail.com>
References: <105c9ccc0712310419r78143ce3h6d896c37bb043c7e@mail.gmail.com>
Message-ID: <4778EF43.9030605@tds.net>

goldgod a wrote:
> hello all,
>             Please find the attached file. I want to sort the content
> of this file based on the "bytes" in descending order. How can i do
> it, any pointers to it.

There are several things to do here:
- read the file
- split into records
- extract the byte count
- sort
- write the file in sorted order

Which parts are you having trouble with? What have you tried?

File reading and writing are covered in any Python tutorial. For the 
sort, I would make a list of
( byte count, record )
and sort that using the list.sort() method.

Kent

From cfuller084 at thinkingplanet.net  Mon Dec 31 17:36:30 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Mon, 31 Dec 2007 10:36:30 -0600
Subject: [Tutor] how to sort the data inside the file.
Message-ID: <200712311036.30303.cfuller084@thinkingplanet.net>

On Monday 31 December 2007 06:19, goldgod a wrote:
> hello all,
> ? ? ? ? ? ? Please find the attached file. I want to sort the content
> of this file based on the "bytes" in descending order. How can i do
> it, any pointers to it.

This is a classic case for the use of regular expressions. ?A powerful tool, 
but can be tricky.  I create a RE for a record, and than use the findall() 
function to get all of them in a list.  I'll walk you through it.

A not of caution: once you get the hang of REs, using them will leave you 
feeling giddy!

Note: ?I load the whole file into memory and parse it in one piece. ?If your 
log is up in the megabytes, it might make more sense to read it in line by 
line.

All of this is well documented in the Python Library Reference.


The code:

import re

fd = open('test', 'r')
s = fd.read()
fd.close()

# seperate into records
lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)

# iterate through the records, and convert the text of the size to an integer
for fields in lin:
   if   fields[3] == ' M':
      mul = 1000000
      #mul = 1024000
      #mul = 1048576

   elif fields[3] == ' k':
      mul = 1000
      #mul = 1024

   else:
      mul = 1

   lout.append( (fields[0], fields[1], int(fields[2])*mul) )

# now sort
lout.sort(lambda a,b: cmp(a[2], b[2]))


Most of processing is happeneing in the single line
lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)

Here is the regular expression
'\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes'

From left to right:
\s* ?The \s designates whitespace, the asterisk matches zero or multiple 
instances.

([^\s]+) ?The parentheses designate a "group", which can be referenced later, 
and represents the hyphen delimited IP address. ?It also works in the 
familiar order-of-operations manner. ?We'll see this in the last piece, ?The 
square brackets designate a list of valid characters. ?The caret inside is an 
inversion: match anything that isn't in the set. ?\s designates whitespace, 
so this matches one or more characters of not-whitespace stuff.

\s+ ?The plus matches one or multiple instances of whitespace.

([^\s]+) ?The second referenced group, which is the domain name in your file.

\s+ ?matches the whitespace between fields

(\d+) ?the third referenced ("matched") group, which is one or more decimal 
digits.

( [kM])? ?Now the tricky bit. ?The [kM] matches any character in the set, so 
either "k" or "M". ?The space inside the group includes the space preceeding 
the "k" or "M" and the ? applies to the whole group, and matches zero or one 
instance, which allows records that have only "bytes" to be matched. ?These 
will have None returned for that group, and " k" or " M" if these were 
present.

bytes  This is pretty obvious.  Nothing funny going on here.

I hope that made sense.

The other tricky bit is the sort. ?In python, lists can be sorted in place, if 
you pass a function that determines the relative precedence of two elements. ?
The cmp() built-in is a shorthand that makes this easy. ?What this line does 
is sorts the list according to the value of the third element. ?Reverse the a 
and b to get a descending sort.


An interesting note: ?I mismatched some parentheses at first, and I ended up 
multiplying the string that converted to int rather than the int. ?
Python will happily convert a million digit int for you, but damn it takes a 
long time!

Cheers

From antoniosalgado at gmail.com  Mon Dec 31 18:12:34 2007
From: antoniosalgado at gmail.com (Antonio Salgado)
Date: Mon, 31 Dec 2007 12:12:34 -0500
Subject: [Tutor] Mobile Python
Message-ID: <d4a3dc80712310912t20ceccd3m94b6b260c161dc92@mail.gmail.com>

Hello to everyone and wishing you all the best and succes  in this new
year!!
Well i'm wondering if someone can point me out or help on this, I want to
write apps for mobile devices, but for the regular nokia (like the 5300),
but i haven't find documentation or anything. Hope someone can help me.
My best wishes and greeting from Mexico!!

-- 
Antonio Salgado Leiner.
New Media, Blogger & Podcaster.
syntax error in KITCHEN.H : COFFEE not found
http://osound101.btpodshow.com/
http://blogmodelolight.com
http://blogcoronamusicfest.com
http://blogsocioaguila.com
http://modeblog-light.blogspot.com
http://rockampeonatotelcel.blogspot.com
http://osound101.blogspot.com
http://chocoaventura.blogspot.com
http://mascherry.com
http://blogmobalis.com
http://blogpromocionestelcel.com
http://blogreventour.com
http://blogvictoria.com
http://fritsi.com/DrOso
http://droso.jaiku.com/
http://twitter.com/droso


"mensaje escrito sin acentos para compatibilidad de formatos"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071231/6062dd6b/attachment.htm 

From kent37 at tds.net  Mon Dec 31 18:18:14 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 31 Dec 2007 12:18:14 -0500
Subject: [Tutor] how to sort the data inside the file.
In-Reply-To: <200712311036.30303.cfuller084@thinkingplanet.net>
References: <200712311036.30303.cfuller084@thinkingplanet.net>
Message-ID: <47792456.4050006@tds.net>

Chris Fuller wrote:

> This is a classic case for the use of regular expressions.  A powerful tool, 
> but can be tricky.  I create a RE for a record, and than use the findall() 
> function to get all of them in a list.  I'll walk you through it.

> # seperate into records
> lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)

This is just splitting on whitespace, you could just use s.split().

> # now sort
> lout.sort(lambda a,b: cmp(a[2], b[2]))

> The other tricky bit is the sort.  In python, lists can be sorted in place, if 
> you pass a function that determines the relative precedence of two elements.  

Recent versions of Python have a better (faster, easier to understand) 
way to do this using the key parameter to sort. The above could be 
written as

lout.sort(key=lambda a: a[2])

or, better:
import operator
lout.sort(key=operator.itemgetter(2))

Kent

From cfuller084 at thinkingplanet.net  Mon Dec 31 20:45:21 2007
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Mon, 31 Dec 2007 13:45:21 -0600
Subject: [Tutor] how to sort the data inside the file.
In-Reply-To: <200712311036.30303.cfuller084@thinkingplanet.net>
References: <200712311036.30303.cfuller084@thinkingplanet.net>
Message-ID: <200712311345.21810.cfuller084@thinkingplanet.net>

On Monday 31 December 2007 10:36, Chris Fuller wrote:
> lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)

This is incorrect.  The first version of the script I wrote split the file 
into records by calling split('bytes').  I erroneously assumed I would obtain 
the desired results by sinmply adding "bytes" to the RE.  The original RE 
could have been written such that this would have worked, (and would have 
been a little "cleaner") but it wasn't.  The space should be obligatory, and 
not included with the [kM] group.

I tried some of Kent's suggestions, and compared the run times.  Nested 
split()'s are faster than REs!  Python isn't as slow as you'd think :)

   # seperate into records (drop some trailing whitespace)
   lin = [i.split() for i in s.split('bytes')[:-1]]

   for fields in lin:
      try:
         if   fields[3] == 'M':
            mul = 1000000

         elif fields[3] == 'k':
            mul = 1000

      except IndexError:
         mul = 1

      lout.append( (fields[0], fields[1], int(fields[2])*mul) )

Cheers