Re: [Tutor] Simple RPN calculator

2004-12-06 Thread Terry Carroll
On Mon, 6 Dec 2004, Chad Crabtree wrote:

> Bob Gailer wrote:
> 
> > For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as
> input 
> > and prints -0.0481481 8 lines of Python. That indeed is less
> than 
> > 100. Took about 7 minutes to code and test. 
> 
> I'm quite interested in seeing the sourcecode for that.

Me, too.  I'm always interested in cool little Python examples.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] AttributeError: instance has no __call__ method

2004-12-15 Thread Terry Carroll
On Wed, 15 Dec 2004, Marc Gartler wrote:

> Hi everybody,
> 
> Prior to this chunk of code 'glass' has been chosen from a list of 
> colors via user input, and I now want to have that choice connect to 
> one of several possible classes:
> 
> def glass_type(glasstype):
>   if glasstype == 'Red':
>   myglass = RedGlassCost()
>   elif glasstype == 'Blue':
>   myglass = BlueGlassCost()
>   elif glasstype == 'Yellow':
>   myglass = YellowGlassCost()
>   return myglass
> 
> glasschoice = glass_type(glass)

At this point, glasschoice is set to glass_type(glass), which in turn is 
something like RedGlassCost().

> AttributeError: RedGlassCost instance has no __call__ method

Right; it sounds like you're using RedGlassCost as a function, but it 
wasn't defined as a function.  Can you show us how RedGlassCost is 
defined?


> I've tried various approaches and keep getting different errors.  But 
> this one seems closest to my goal, as I know it is at least passing 
> 'glass' into the function:

My mother always told me to apologize after passing glass.



___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Reading the CDROM in Linux

2010-11-05 Thread Terry Carroll
I have a program that traverses the directory of a CDROM using os.walk. 
I do most of my work on Windows, but some on (Ubuntu) Linux, and I'd like 
this to work in both environments.


On Windows, I do something along the lines of this:

  startpoint="D:/"
  for (root, dirs, files) in os.walk(startpoint):
 (stuff)

What would I use for startpoint in Linux?  I've tried "/dev/sr0" and 
"/dev/sr0/"; neither work.  (If I recall correctly, the for-loop just 
drops through; I'm not at my Linux box right now to confirm.)


A number of other mount points (like /dev/cdrom, I think) are links to 
/dev/sr0; and don't work either.


It *does* work to start at "/media/VOLUMENAME", where VOLUMENAME is the 
volume ID of the disc; but my program will not know that.  I need to be 
able to do this without knowing the volume name.


Any ideas?

(I have a nagging suspicion the answer will be that it's not possible to 
do this in exactly teh same way, and that I'll need to somehow query what 
volume is mounted on /dev/sr0, and then use the /media/volumename 
approach)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Reading the CDROM in Linux

2010-11-05 Thread Terry Carroll

Alan Gauld wrote:


I don't use Ubuntu so don;t know the standard anmswer
there but it will depend on where the CD is mounterd.

I usually mount cdroms on /dev/cdrom


That's what I figured; I now realize I didn't say so in my email, but it's 
mounted at /dev/sr0, which is where I came up with that mount point.



 t...@vraspberry:~$ df
  . . .

 /dev/sr0   614350614350 0 100% /media/MP_04_074


MP_04_074 is the volume name.

But in python:


import os
for (r, d, f) in os.walk("/dev/sr0"): print r, d, f

...

for (r, d, f) in os.walk("/dev/sr0/"): print r, d, f

...

for (r, d, f) in os.walk("/dev/cdrom/"): print r, d, f

...

for (r, d, f) in os.walk("/dev/cdrom"): print r, d, f

...

for (r, d, f) in os.walk("/dev/cdrom0"): print r, d, f

...

for (r, d, f) in os.walk("/dev/cdrom0/"): print r, d, f

...


None of those work; but:



for (r, d, f) in os.walk("/media/MP_04_074"): print r, d, f

...
/media/MP_04_074 ['directory1'] []
(etc.)


What I can't figure out is how to do this if my program does not know the 
volume name.  I won't know the colume name in advance, and in fact, I'll 
be processing one CDROM, replacing it and processing another, etc.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reading the CDROM in Linux

2010-11-05 Thread Terry Carroll

On Sat, 6 Nov 2010, Steven D'Aprano wrote:

Anyway, more modern Linux systems automatically mount CDs and DVDs. By 
convention, /mnt/... is used for manually mounts, and /media/... for 
automatic mounts of media.


I am seeing my volume in /media ; however, I won't know the volume name 
when my program runs.  I can't use whatever shows up in /media, because 
there could be more than one drive.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reading the CDROM in Linux

2010-11-05 Thread Terry Carroll

On Sat, 6 Nov 2010, Steven D'Aprano wrote:


Terry Carroll wrote:
I have a program that traverses the directory of a CDROM using os.walk. I 
do most of my work on Windows, but some on (Ubuntu) Linux, and I'd like 
this to work in both environments.


On Windows, I do something along the lines of this:

  startpoint="D:/"


What if the user has two CD drives? What if they have a second hard disk 
mounted on D:/, and a network drive on E:/, and use F:/ or A:/ or Z:/ for the 
CD drive?



D:/ doesn't enter into it.  That's on Windows, I'm asking about Linux.  I 
used "D:/" to show a single example of what works on Windows to explain 
what I am looking for on Linux.


In practice, the drive specification will be coming from a config file. 
It would be D:? on some systems, E:/ on others or maybe both.


But my question is not about Windows, which I already have covered.  My 
question is, to put it succinctly:


How can one use os.walk to walk a directory structure of a CDROM on LInux 
when the volume name is not known?


On Unix and Linux systems, there are two conventions for mounting external 
media. One is that if you, the user, mount something by hand using the 
"mount" command, it gets placed in /mnt (old-school Unix sys admins had


keyboards without vowels *wink*). Often people would use subdirectories under 
/mnt:


/mnt/cdrom
/mnt/floppy

are the two most common ones.


No such luck:

t...@vraspberry:~$ ls -pal /mnt
total 8
drwxr-xr-x  2 root root 4096 2010-04-23 03:23 ./
drwxr-xr-x 23 root root 4096 2010-10-04 10:42 ../

t...@vraspberry:~$ ls -pal /mnt/cdrom
ls: cannot access /mnt/cdrom: No such file or directory
t...@vraspberry:~$ ls -pal /mnt/floppy
ls: cannot access /mnt/floppy: No such file or directory


The other convention is that modern window/desktop managers like KDE and 
Gnome will automatically mount devices by name under /media.


Yes, I mentioned this, but it requires knowing the volume name.

If you only have one CD drive, and no other devices mounted, you can 
just look at /media and walk over that without caring what the CD drive 
is called. In other words, just use /media as the starting point, and 
let os.walk discover the name of the CD under it.


But that has the same problem I already mentioned in the prior note: what 
if there's more than one device?  The same thing you pointed out above 
about D:/




Well that was easy. You need to query the external tool volname, which
should be present on just about any Linux system.

Use the subprocess module to call "volname /dev/cdrom".


Aha, this looks like it will work; I was starting to think along these 
lines; I was thinking of reading the output of df, but this is cleaner.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reading the CDROM in Linux

2010-11-05 Thread Terry Carroll

On Fri, 5 Nov 2010, Terry Carroll wrote:

Aha, this looks like it will work; I was starting to think along these lines; 
I was thinking of reading the output of df, but this is cleaner.


Just to close this out, here's what's working for me.  It will need to be 
prettied up, and the "/media/" parameterized, but it's my proof of concept 
that lets me know how to solve my problem:


#
import subprocess, os
def getvolid(mountpoint):
p = subprocess.Popen(["volname", mountpoint],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(response, errmsg) = p.communicate()
volid=response.rstrip()
errmsg = errmsg.rstrip()
if len(response)==0:
volid=None
return (volid, errmsg)

# Test it
things_to_try = ["/dev/sr0",# VBOXADDITIONS_3.2.6_63112
 "/dev/cdrom1", # symlink to sr0
 "/dev/sr1",# MP_04_074
 "/dev/cdrom",  # symlink to sr1
 "/dev/sr2"]# no such mount point, return an error
for thing in things_to_try:
volid, error = getvolid(thing)
print "mount point=%s; volid=%s; errormsg=%s" % (thing, volid, error)

# Try the os.walk:
(volid, errmsg) = getvolid("/dev/sr0")
for (r, d, f) in os.walk("/media/"+volid):
print (r, d, f)

#

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interactive visualization in python

2010-11-07 Thread Terry Carroll

On Sun, 7 Nov 2010, Alan Gauld wrote:


Most GUI toolkits have a tree widget like the Wiondows Explorer tree view.
The Tkintrer version is included in the Tix module which extends the basic
Tkinter widgets.

I'm pretty sure wxPython will have one too.


I haven't used it, but wxPython's tree widget is wx.TreeCtrl

doc:

http://wxpython.org/docs/api/wx.TreeCtrl-class.html

example:

http://wiki.wxpython.org/AnotherTutorial#wx.TreeCtrl
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Too different 2.6 vs 2.7?

2010-11-08 Thread Terry Carroll

On Mon, 8 Nov 2010, Jorge Biquez wrote:


Are there really BIG differences between version 2.6 and 2.7?


I'm in a similar boat.  I use Ubuntu 10.04 aw well as Windows XP, Vista 
and 7.  I keep to similar levels just to avoid confusion and at present 
run Python 2.6 on all systems.


If I had an urgent enough need, I'd go to ActivePython 2.7 on the Windows 
boxes, but so far, no need other than to have the latest.


The only feature I'm pining for at all is the new argparse; but it depends 
on your needs.


Under my ubuntu configuration I can not install version 2.7, searching the 
why, but the version 2.6 is maintained and installed by the ubuntu software 
center.


It's possible to install 2.7 on Ubuntu, but I'm not piqued enough to do 
so.  If you're interested, a couple posts on Ubuntu Forums describe it:


http://.ubuntuforums.org/showthread.php?t=1524491
http://ubuntuforums.org/showthread.php?t=1582739

As a newby , trying to learn all the features of all the libraries. Will I 
miss TOO much if I stay under version 2.6? Or it will be better to stay under 
2.7 (in that case under Windows XP)


For myself, I think I'll be fine in 2.6.  I usually upgrade when I see a 
particular feature I want.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Stupid bug

2010-11-10 Thread Terry Carroll
This isn't a question, I'm just offering it as a cautionary tale and an 
opportunity to laugh at my own stupidity.


I have a small function to calculate the MD5 checksum for a file.   It's 
nothing fancy:


###
import hashlib
def md5(filename, bufsize=65536):
"""
Compute md5 hash of the named file
bufsize is 64K by default
"""
m = hashlib.md5()
with open(filename,"rb") as fd:
content = fd.read(bufsize)
while content != "":
m.update(content)
content = fd.read(bufsize)
return m.hexdigest()
###

I've discovered a need to calculate the checksum on the first 10K or so 
bytes of the file (faster when processing a whole CDROM or DVDROM full of 
large files; and also allows me to find when one file is a truncated copy 
of another).


This seemed like an easy enough variation, and I came up with something 
like this:


###
def md5_partial(filename, bufsize=65536, numbytes=10240):
"""
Compute md5 hash of the first numbytes (10K by default) of named file
bufsize is 64K by default
"""
m = hashlib.md5()
with open(filename,"rb") as fd:
bytes_left = numbytes
bytes_to_read = min(bytes_left, bufsize)
content = fd.read(bytes_to_read)
bytes_left = bytes_left - bytes_to_read
while content != "" and bytes_left >0:
m.update(content)
bytes_to_read=min(bytes_left, bufsize)
content = fd.read(bytes_to_read)
bytes_left = bytes_left - bytes_to_read
return m.hexdigest()
###

Okay, not elegant, and violates DRY a little bit, but what the heck.

I set up a small file (a few hundred bytes) and confirmed that md5 and 
md5_partial both returned the same value (where the number of bytes I was 
sampling exceeded the size of the file).  Great, working as desired.


But then when I tried a larger file, I was still getting the same checksum 
for both.  It was clearly processing the entire file.


I started messing with it; putting in counters and print statements, 
using the Gettysburg Address as sample daya and iterating over 
20 bytes at a time, printing out each one, making sure it stopped 
appropriately.  Still no luck.


I spent 90 minutes over two sessions when I finally found my error.

My invocation of the first checksum was:

###
checksumvalue = my.hashing.md5("filename.txt")
# (Not an error: I keep my own modules in Lib/site-packages/my/ )
print checksumvalue
#
# [several lines of code that among other things, define my new
# function being tested]
#
checksumvalue2 = md5_partial("filename.txt", numbytes=200
print checksumvalue

Turns out my function was working correctly all along; but with my typo, I 
was printing out the value from the first checksum each time.  Doh!


Well, no harm done, other than wasted time, and I did turn up a silly but 
harmless off-by-one error in the process.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Data Directory under site-packages

2010-11-10 Thread Terry Carroll

On Wed, 10 Nov 2010, Greg Lindstrom wrote:


I'm writing my first module that I intend to put under our company's
"site-packages" directory for everyone to use in their programs.  The
problem I'm having is that I want to place files in a data directory under
the module directory (under site-packages) and I don't know how to set the
path so I pick up the files.  If I use open('./data/myfile') I get the path
of the file importing the module (which could be just about anywhere).  I've
tried various combinations using os.path.abspath() and os.path.dirname() but
have the same problem.  Is there a way I can use files in the subdirectory
(I really do not want dozens more files in the main directory)?


I'm not sure I follow.

You want to put data, i.e., non-python code, in the import path?  That 
sounds unusual to me.


You can find the filename from which a module is imported with the 
module's __file__ attribute; and then os.path.dirname() can get you the 
directory.  So if you wanted to address a subdirectory named "data" in the 
same directory from which you imported a given module, or a file 
"myfile.txt" in that subdirectory, that's possible.


Using the sqlite module as an example on my system:


import sqlite3
sqlite3.__file__

'C:\\Python26\\lib\\sqlite3\\__init__.pyc'

import os
os.path.dirname(sqlite3.__file__)

'C:\\Python26\\lib\\sqlite3'

os.path.join(os.path.dirname(sqlite3.__file__), "data")

'C:\\Python26\\lib\\sqlite3\\data'

os.path.join(os.path.dirname(sqlite3.__file__), "data", "myfile.txt")

'C:\\Python26\\lib\\sqlite3\\data\\myfile.txt'


Is this the kind of thing you're thinking of?

Again, it's highly unusual to put non-code data in the import path; I've 
never heard of this being done before, and it makes me shiver in 
revulsion.  I'm not sure I can articulate exactly what bad effects it will 
have, apart from the inherent messiness of it, but I don't like it.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] program hangs in while loop using wx.yield

2010-11-15 Thread Terry Carroll

On Sun, 14 Nov 2010, Alex Hall wrote:


Is there a basic tutorial for this sort of thing?


Chapter 3 ("Working in an event-driven environment") of the book "wxPython 
in Action" is a pretty good tutorial on event-driven GUI programming in 
wxPython.  The book in general is pretty good; I no longer buy many 
computer books, but this one was worth it.


If you don't want to buy it, if you're in the U.S., you can go to 
http://www.worldcat.org/oclc/67122432 and plug in your zip code to see if 
a library near you[1] has it.


[1] or a library that has inter-library loan arrangements with a library 
near you.  I'm currently reading "Essential SQLAlchemy," courtesy of the 
San Diego State University library.  My local library (San Jose Public 
Library) borrowed it from SDSU and then lent it to me.  It's kind of cool 
that one library will send a book 400 miles to another, just because I'm 
too cheap to buy a copy and asked for it.


Apologies to anyone at SDSU who's learning SQLAlchemy and wondering why 
they can't find this book in their library.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] wxPython, Tkinter (was: program hangs in while loop using wx.yield

2010-11-16 Thread Terry Carroll

On Tue, 16 Nov 2010, Patty wrote:

Hi Terry - I am an alumni of UCSC (University of California, Santa Cruz) 
and live really close so I can request books throughout the UC system 
just like you describe and there is no limit - or maybe an extremely 
high limit - to the number of books I can check out from McHenry 
Library.  It is so worth paying alumni dues!  There is no way they would 
transport books to the public library to make it easier for people 
though - not with the way the city and the university feel about each 
other :}


You might be surprised.  I would't have expected to get a book from San 
Diego State University sent to the San Jose Public Library, but it did. 
I just entered teh request, and a few hours later, I had anote saying it 
was on the way.  The system finds the copy and obtains it.


It's not on a one-to-one basis, i.e., as if SJPL had an arrangement with 
SDSU; it's more of the libraries deciding to patricipate in the pool.


If I just can't figure out how to do this with Tkinter and the Python Imaging 
Library, is 'wxPython' the additional software I would want to install and 
try with?


wxPython is an alternative to Tkinter.  The advantage of Tkinter is that 
it comes as part of standard Python.  You know that it will be installed 
on any reasonably current Python installation.  If you write a program 
using Tkinter and send it to me, you can be sure that I can run it as long 
as I have Python installed (at least as far as the GUI is concerned; other 
things such as PIL might still be an issue).


wxPython is an API over the cross-platform wxWidgets GUI.  I think it 
provides a cleaner and more native look compared to Tkinter. For what my 
opinion is work (and that's not much -- I'm pretty inexperienced at GUI 
stuff), I find it at least as easy to use as Tkinter, but I recall a 
learning curve when I started.


I don't use Tkinter any more, preferring wxPython, but opinions will vary.

Here's a comparison of the two; it's hosted on a wxPython site, so it's 
undoubtedly slanted toward wxPython:

http://wiki.wxpython.org/Choosing%20wxPython%20over%20Tkinter

Another couple:
http://www.llaisdy.com/static/tech/python/calc.html
http://ojs.pythonpapers.org/index.php/tpp/article/viewArticle/61

However, if you would like an example of using Tkinter with PIL, I would 
be happy to provide you with a very rough program I wrote several years 
ago for my own use (when I still used Tkinter).  It loads an image that 
was taken with a digital camera; reads the date the photo was taken from 
the image's EXIF data; adds a timestamp to the photo, and saves it.


It's very rough; I have the habit of writing something only to the point 
where it's good enough for me, and then stop development on it.  But you 
might find it helpful of a straightforward program that uses both.  It's 
from about 2006 or so, and I am by no means a GUI programming expert and 
was even less so then, so my techniques may be suspect; but I'd be happy 
to send it to you for what it's worth.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Optparse question: if only certain values are acceptable

2009-05-08 Thread Terry Carroll
I'm tryng to use optparse for the first time.

The toy summary is that I want to have the following command format:

  prognam -f FORMAT

Where FORMAT, if specified, must be one of "X", "Y", or "Z".

In otherwords, if the user enters:

 progname -f X

It runs, producing its output in format X.  Similar if "Y" or "Z" is
specified instead of "X".

But if the user specifies

 progname -f A

I want it to spit up because A is not a recognized format.

I don't see anything in the docs that directly addresses this.  Is this 
something that I should use the callback parameter for?

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


Re: [Tutor] Optparse question: if only certain values are acceptable

2009-05-08 Thread Terry Carroll
On Sat, 9 May 2009, Sander Sweers wrote:

> Is the below what you are looking for?

It's exactly what I was looking for.  Thanks very much.

Now I'm going to have to re-read the docs and see why I couldn't pick that 
up from them. 


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


Re: [Tutor] am I missing another simpler structure?

2004-12-17 Thread Terry Carroll
On Thu, 16 Dec 2004, Alan Gauld wrote:

> In most debiggers ...

So *that's* the trick to writing compact code!


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sample Tkinter data entry screen?

2004-12-24 Thread Terry Carroll
I haven't played with Tkinter in months, and always find it a frustrating 
experience (GUI stuff is non-intuitive to me).

Taking the lazy way out, can anyone point me to a simple sample app that
just puts up a data entry screen with a small (4 or 5) number of simple
text-entry fields and lets me pull in variables from those fields?


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


Re: [Tutor] Sample Tkinter data entry screen?

2004-12-25 Thread Terry Carroll
Thanks, Harm.

On Sat, 25 Dec 2004, Harm Kirchhoff wrote:

> What really helped me get going were the Tk inter chapters in
> 'Programming Python' by Mark Lutz.

I'll take a closer look at it.  I don't find this book very helpful, 
because it assumes you've been following all the previous parts of the 
book, so, for example, when you open to the Tk section, if you haven't 
been following all the "packer" stuff in the previous chapters, it's hard 
to tell what's got to do with Tk and what's got to do with the other 
stuff.

> Hope the following helps:

[snip]

Thanks, I'll give this a try and use it as a base.  I really appreciate 
it.

Merry Christmas!

Terry


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


Re: [Tutor] Sample Tkinter data entry screen?

2004-12-25 Thread Terry Carroll
On Sat, 25 Dec 2004, Alan Gauld wrote:

> The case study in my tutor shows a text entry and set of radio buttons
> and a Text field for outbut, along with some buttons. Is that enough?

I'll have a look at it (printing a copy now); I expect it will be very 
helpful.

Thanks, Alan.

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


[Tutor] Tkinter packing confusion

2004-12-27 Thread Terry Carroll
First, thanks for the responses on my questions on using Tkinter for data 
entry from last week. Alan's and Harm's responses were very helpful.

I'm now playing with a tiny application that does nothing except allow the 
user to enter a variable for processing.  It provides a default value, and 
three buttons: if the user hits CANCEL, the app terminates; if he hits OK, 
it prints out the entered variable; if he hts RESET, the data entered is 
reset to the default it had to start.

The program logic works, but I'm totally lost on the pakcer layout 
manager.  What I want to see is a window with something like this (bear 
with my ascii art):

  URL: [ http://www.somewhere.com/default ]

  ++   +---+  ++   
  | Cancel |   | Reset |  | OK |
  ++   +---+  ++

What I'm getting is:

   URL:
++
| Cancel |
++   [ http://www.somewhere.co ]
  +---+++
  | Reset || OK +
  +---+++


I'm sure my error lies in the packing, but I don't get it.

I'm probably thinking abou it wrong, but my logic is this:

I create a master frame, with two sub-frames, fBaseURL for the URL label
and entry, and fButtons for the three buttons.

In the fBaseURL frame, I pack the label widget to the top, and then the
entry widget right (i.e., the entry widget to the right of the label
widget).  Then I pack in the fBaseURL frame.

In the fButtons frame, I pack in the "Cancel" button as the top of 
fButtons; then "Reset" to its right, and "OK" to its right.  Then I pack 
in the fButtons frame.

Finally, I pack the parent frame.

Well, I'm lost.  I'm trying dozens of variations, but just don't get it.  
Can someone explain to me how to pack in more simple terms?

Here's my code:

import Tkinter as tk

class DEApp:
def __init__(self):

top=tk.Tk()

self.DefaultBaseURL = "http://www.somewhere.com/default/";
self.tvDefaultBaseURL=tk.StringVar()
self.tvDefaultBaseURL.set(self.DefaultBaseURL)

self.F=tk.Frame(top)

fBaseURL=tk.Frame(self.F)
lBaseURL=tk.Label(self.F, text="URL:")
eBaseURL=tk.Entry(textvariable=self.tvDefaultBaseURL)
lBaseURL.pack(side="top")
eBaseURL.pack(side="right")
fBaseURL.pack(side="top")

fButtons=tk.Frame(self.F)
bCancel=tk.Button(fButtons, text="Cancel", command=self.evCancel)
bReset=tk.Button(fButtons, text="Reset", command=self.evReset)
bOK=tk.Button(fButtons, text="OK", command=self.evOK)
bCancel.pack(side="top")
bReset.pack(side="right")
bOK.pack(side="right")
fButtons.pack(side="left")

self.F.pack(side="top")

def evCancel(self):
print "Cancel hit"
self.F.quit()
return

def evReset(self):
print "Reset hit"
self.tvDefaultBaseURL.set(self.DefaultBaseURL)
return

def evOK(self):
print "OK hit"
print "BaseURL is now", self.tvDefaultBaseURL.get()
self.F.quit()
return

app = DEApp()
app.F.mainloop()






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


Re: [Tutor] Tkinter packing confusion

2004-12-27 Thread Terry Carroll
On Mon, 27 Dec 2004, Terry Carroll wrote:

> The program logic works, but I'm totally lost on the pakcer layout 
> manager.  

Never mind; I'm an idiot.

> self.F=tk.Frame(top)
> 
> fBaseURL=tk.Frame(self.F)
> lBaseURL=tk.Label(self.F, text="URL:")
> eBaseURL=tk.Entry(textvariable=self.tvDefaultBaseURL)

This is my problem.  I created the fBaseURL Frame, but never used it.  The 
last two lines should read:

> lBaseURL=tk.Label(fBaseURL, text="URL:")
> eBaseURL=tk.Entry(fBaseURL, textvariable=self.tvDefaultBaseURL)

No wonder it not only didn't pack the way I expected, but that no
variation in the pack() calls would fix it.  I was putting the widgets
directly into the master frame.


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


Re: [Tutor] file-like object

2005-01-14 Thread Terry Carroll
On Fri, 14 Jan 2005, Chad Crabtree wrote:

> class _macroString(object):
> def __init__(self,s):
> self.macro=s
> self.list=self.macro.split("\n")
> for n,v in enumerate(self.list):
> self.list[n]=v+'\n'


Is this for loop a safe technique, where the list you're enumerating over
in the for statement is the same as the one being updated in the loop
body?  I always avoid things like that.


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


Re: [Tutor] file-like object

2005-01-14 Thread Terry Carroll
On Fri, 14 Jan 2005, Terry Carroll wrote:

> Is this for loop a safe technique, where the list you're enumerating over
> in the for statement is the same as the one being updated in the loop
> body?  

Rather than cluttering the list by making three replies, I'd just like to
thank Danny, Alan and Jeff each for their answers to this.  Clears it
right up for me.


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


[Tutor] Intro for interfacing with Microsoft Access?

2005-01-14 Thread Terry Carroll
Does anyone know of any online resource that explains how to interface to 
Microsoft Access via Python, where the intended audience is someone who 
knows Python, but not the Microsoft innards?

I've found http://starship.python.net/crew/bwilk/access.html (which 
doesn't work for me, and presumably is out of date) and 
http://www.ecp.cc/pyado.html (which mostly works well enough, but assumes 
you know Microsoft's Data Access Objects (DAO), and points to the 
overwhelming Microsoft ADO API Reference.

I don't want to do anything too fancy, just read data from my database, 
make a few calculations and print some summaries obtained from it.  I know 
Python, but not Access (it's my company's DB, not mine) or DAO. 

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


Re: [Tutor] Intro for interfacing with Microsoft Access?

2005-01-14 Thread Terry Carroll
On Fri, 14 Jan 2005, Kent Johnson wrote:

> A couple of minutes of googling for 'python odbc' finds the ODBC driver
> that comes with win32all. It seems to have a fairly simple interface.
> The download from this page has an example:  
> http://py.vaults.ca/apyllo2.py/D906422565

Thanks, Kent.  I'm not familiar with OBDC, but I'll look into it.


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


[Tutor] Should this be a list comprehension or something?

2005-01-25 Thread Terry Carroll
The following Python code works correctly; but I can't help but wonder if 
my for loop is better implemented as something else: a list comprehension 
or something else more Pythonic.

My goal here is not efficiency of the code, but efficiency in my Python 
thinking; so I'll be thinking, for example, "ah, this should be a list 
comprehension" instead of a knee-jerk reaction to use a for loop.

Comments?

The point of the code is to take a sequence of objects, each object 
representing an amount of water with a given mass and temperature, and to 
return another object that represents all the water ideally combined.  The 
formulae for the combined mass and temp are respectively:

 combined mass = M1 + M2 + M3  (duh)
 combined temp = ((M1*T1) + (M2*T2) + (M3*T3)) / (M1 + M2 + M3)

Here's my code:

class Water:
def __init__(self, WaterMass, WaterTemperature):
self.mass = WaterMass
self.temperature = WaterTemperature
def __repr__(self):
return ("%.2f, %.2f" % (self.mass, self.temperature))

def CombineWater(WaterList):
totalmass=0
numerator = 0; denominator = 0
for WaterObject in WaterList:
totalmass += WaterObject.mass
numerator += WaterObject.mass * WaterObject.temperature
return Water(totalmass, numerator/totalmass)


Example use:


w1 = Water(50,0)
w2 = Water(50,100)
w3 = Water(25,50)

print CombineWater((w1,w2,w3))


prints, as expected: 125.00, 50.00



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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
On Fri, 28 Jan 2005, Alan Gauld wrote:

> > Oh wait, I know: let's all start writing code in MS Word .doc
> format!
> > Arial for functions, Times New Roman for classes. Who's with me?
> ;-)
> 
> So you've been looking at Eiffel then?
> :-)

I don't get this joke, but it sounds like the basis for it 
would be interesting.  Can you explain?

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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
Sorry for not responding earlier to thank all the people who weighed in on 
my question.  I'm glad to find that my first take on it was sufficiently 
pythonic.

Alan, I'd never seen the criterion befor that list comprehensions should 
be used to generate other lists.  That's helpful, and I'll keep it in 
mind.

Thanks to Max and Tony for their comments and tests on efficiency.  
Although I was primarily interested in finding out if I was thinking in 
the right way, this was helpful.

Karl, I hadn't thought about overloading, although I knew about the 
possibility.  That's really cool, and quite clear.

Sean, I wasn't even aware of reduce() before.  Thanks, I'll look into 
that.




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


[Tutor] Naming conventions (was: Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
On Wed, 26 Jan 2005, Sean Perry wrote:

> And now, for the pedant in me. I would recommend against naming
> functions with initial capital letters. In many languages, this implies
> a new type (like your Water class). so CombineWater should be combineWater.

I hate hate hate hate hate camelcase and will never use it.  In my book,
if the name has *any* capitals in it, the first letter is capitalized,
too.  Anything else is unaesthetic.  

To me, when I have names that are composed of multiple words (say, "rice
quantity"), I have two approaches: distinguishing the words by case 
(RiceQuantity) or separating by underscores (rice_quantity).

I never confuse classes/instances and methods, because I use noun phrases
for classes and instances (HeatedWater, VerifiedInput) and verb phrases
for the methods (CombineWater, CookRice).  I suppose I could get
confusion, for example, when the combination either a noun phrase or 
verb phrase (SoundOut: is that a name describing the Sound that's being 
put Out, or is it a method that's is tentatively Sounding Out somthing?) 
but so far that hasn't been an issue for me.

Of course in my case, I write code only for myself, so I have the luxury 
of not worrying about what Joe in the next cubicle is doing, and what Jane 
will do when she's trying to read Bob's and my code together.  So I have 
the luxury of turning my nose up at camelCase.

I should add that, the one time I made changes to someone else's Python
code for release (a minor patch to nntplib.py), I used the same case
conventions already in place in the module.

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


Re: [Tutor] Naming conventions

2005-01-28 Thread Terry Carroll
On Fri, 28 Jan 2005, Kent Johnson wrote:

> Separating with underscores is quite common in the Python community,
> actually it is the preferred spelling for library modules. So maybe you
> should adopt that, just to reduce the confusion when your code does have
> an encounter with the outside world :-)

I'm a lawyer by trade; my work is *supposed* to confuse the outside world!

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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
On Fri, 28 Jan 2005, Alan Gauld wrote:

> Its not so much a criterion that they *should* be used that way,
> its just that its what they do. A list comprehension creates a list!
> Thats why they are called *list* comprehensions. :-)

See, I'd always figured that the reason it was called a list 
comprehension was because the list comprehension operated on a list, 
and the operation was comprehension.

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


Re: [Tutor] Dividing 1 by another number ?

2005-01-30 Thread Terry Carroll
On Sun, 30 Jan 2005, Brandon wrote:

> I'm trying to write a program they may involve needing to divide 1 by
> another number. In the program below when I use 4 for the diameter of
> the bore, and 1 for the diameter of the rod, and 60 for the PSI, the
> force should be 706.8 . However the program keeps giving me 0 for
> "rodarea". 

In addition to the real division issue that's already been pointed out 
(simplest fix is to divide by 4.0 instead of 4 to avoid this), you've got 
another problem:

> area = (bore**2/4)*PI
> rodarea = (rod**2/4)*PI

Both of your formulas above are the same.  So, where bore = rod, as in 
your example where they're both equal to 1, area and rodarea are both 
going to evaluate to the same value:

>>> bore = 1
>>> rod = 1
>>> PI = 3.14
>>> area = (bore**2/4.0)*PI
>>> rodarea = (rod**2/4.0)*PI
>>> area
0.78503
>>> rodarea
0.78503

Now, look at your nest line:

> force = (area-rodarea)*psi

since area is equal to rodarea when bore is equal to rod, area-rodarea 
will always = 0, and force will equal 0, too, not 706.8 as you're 
expecting.

This isn't just a matter of when you use 1, it's true whenever you use 
equal values for rod and bore.


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


Re: [Tutor] Presentation

2005-01-31 Thread Terry Carroll
On Tue, 1 Feb 2005, Paul Hartley wrote:

> When I was a member of the Forth Interest Group in the USA we learned
> that Forth was used on the buggy that went to mars, that it started life
> controlling huge radio telescopes which only had 4k (yes 4k) of memory
> for both language and application.
> 
> Anything like the above concerning python would be useful.

I just did a google on "Pyton success stories," and found this page, which 
you may find useful.

http://www.pythonology.com/success 

See also the two O'Reilley links on that page.

Since you mentioned use in space exploration, always a sexy example, I 
search for "Nasa Python" also turned up these:

 NASA Ames Processing in Python: 
http://home.badc.rl.ac.uk/astephens/software/nappy/

 Space shuttle engineers use Python to streamline mission design:
http://builder.com.com/5100-6401-1045764.html

... and others.

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


Re: [Tutor] Presentation

2005-02-01 Thread Terry Carroll
On Wed, 2 Feb 2005, Paul Hartley wrote:

> Not only is the language amazing but the community is fantastic!!

The community is one of the things I particularly like about Python.  I
always hated asking a question in the Perl newsgroups; although you
usually got an answer, you were almost certain to be told you're stupid
for not already knowing it.

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


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-02 Thread Terry Carroll
I got nothing on your Perl rant, but in response to the subject line...

http://www.snopes.com/legal/arizona.htm

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


RE: [Tutor] executing SAS and passing parameters

2005-02-08 Thread Terry Carroll

Ah, SAS.  I used that a lot in the early '80s for general programming.  I 
felt a lot about SAS then as I do about Python now.

Enough of that.  Can you show your python code that invokes SAS; and can 
you also show what you type at a command line that makes SAS run the 
way you want?

Given the command line, it should be pretty straightforward to move the 
command line invocation into Python.

On Tue, 8 Feb 2005, Williams, Thomas wrote:

> I'll do my best to answer these questions for you.
> 
> I am able to start the SAS executable from python, but not the specific SAS
> program in question.  When this executable is executed, the typical SAS
> environment is displayed (SAS editor Window, SAS libraries, and the output
> and log windows).  I want to have a specific SAS program executing with the
> assigned parameters that will be read into a SAS macro.  
> 
> This SAS program was originally called from an AML (Arc Macro Language),
> again, with the parameters passed to it.
> 
> OS: WindowsNT
> 
> Let me know if you need further information.
> 
> Thanks again,
> Tom
> 
> 
> -Original Message-
> From: Alan Gauld [mailto:[EMAIL PROTECTED] 
> Sent: Tuesday, February 08, 2005 1:57 PM
> To: Williams, Thomas; tutor@python.org
> Subject: Re: [Tutor] executing SAS and passing parameters
> 
> > I am trying to use python to run a SAS program by passing the needed
> > parameters.  I am able to start SAS, but unable to start the correct
> SAS
> > program with its parameters.
> 
> Not being familiar with SAS or its parameters we'll need more clues...
> 
> > Any assistance you could provide will be appreciated.
> 
> Can you show us what you used to start SAS?
> Can you tell us exactly what happened? - any errors etc?
> Can you show us how you'd do it outside of Python?
> Can you tell us which OS you are using?
> 
> With that info we should be able to make a stab at it.
> 
> Alan G.
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

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


Re: [Tutor] executing SAS and passing parameters

2005-02-09 Thread Terry Carroll
I'd echo what Alan said.  It sounds more like you're having trouble 
finding out what the command line to SAS should look like, rather than 
invoking it with Python.

(I'm going to quote some of your message out-of-order to better facilitate 
my approach to this.  I will, I trust, not misrepresent the context.)

On Wed, 9 Feb 2005, Williams, Thomas wrote:

> However, the program in question is c:\work\run_ratios.sas, with 2
> parameters: incov, and outcov.  This program was initially invoked from an
> aml program.  The code that invoked SAS from this aml is:
> 
>   &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~
> %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~
> %.ARCLOC%\sas_code\ratios\new_ratio.sas
> 
> %.SASLOC%: the SAS executable file ('C:\Program Files\SAS
> Institute\SAS\V8\SAS.exe')
> %sas_parm%: the list of parameters to be passed onto SAS
> %.file%: the name of the log file that is generated during the execution of
> the SAS program.
> %.ARCLOC%: directory of the SAS program (c:\work)

First, something's not jibing here: you say the program to run is 
c:\work\run_ratios.sas , but none of the variables under AML appear to 
have "run_ratios" in it. (Not that I know what AML is).

My expectation is that this code:

>   &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~
> %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~
> %.ARCLOC%\sas_code\ratios\new_ratio.sas

Expands to an invocation of this:

"""
C:\Program Files\SAS Institute\SAS\V8\SAS.exe -SYSPARM incov outcov 
-log c:\work\ratios\log\[logfilename].log
-SYSIN  c:\work\sas_code\ratios\new_ratio.sas
"""

(where [logfilename] is actually replaced with the name of your logfile.)

As I said, no reference to "c:\work\run_ratios.sas" in this; so confirm 
this.

My suggestion is that you open up an MSDOS window, and try variations on 
this until you find one that works.  Once you find one that works, you 
know your command; and that's going to be 95% of the battle.

In your Python code:


>   os.execl('C:\Program Files\SAS Institute\SAS\V8\SAS.exe')

First, as Alan points out, try os.system() instead.  I would also very 
much encourage a piece of advice he gave that might have slipped through, 
which is: build a string, first, and pass that string to os.system().  
That way, you can do some debugging by making sure your string represents 
the command you cane up with earlier.

I'd also recommend using forward slashes rather than backslashes,  which 
saves you some escape heartache.  Forward slashes should still work.

You can also do something along the same lines your AML took, if 
you like:


SAS_location = "C:/Program Files/SAS Institute/SAS/V8/SAS.exe"
sas_parm = "incov outcov"
ARC_location = "c:/work/"
logfile = "ratios/mylog.log"
SAS_SYSIN = "sas_code/ratios/new_ratio.sas"

command_line = "%s -SYSPARM %s -log %s%s -SYSIN %s%s" % (SAS_location, sas_parm,
 ARC_location, logfile, ARC_location, SAS_SYSIN)

print command_line
# above line verifies the command matches what you determined from the 
# earlier testing from the MS-DOS command line

os.system(command_line)
# invoke SAS




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


Re: ****SPAM(11.2)**** [Tutor] Larger program organization

2005-02-16 Thread Terry Carroll
On Fri, 11 Feb 2005, Bob Gailer wrote:

> Whenever you find yourself writing an if statement ask whether this
> would be better handled by subclasses. Whenever you find yourself about
> to write a global statement, consider making the variables properties of
> a class.

Bob -- 

Brian already asked for an explanation of your first statement, and I 
found the ensuing discussion very instructive.

Can you explain the second?  As an aesthetic point, I hate globals, and 
I'd love a discussion with some examples of using class variables as a way 
of avoiding this.

Terry

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


Re: [Tutor] Active Python

2005-02-17 Thread Terry Carroll
On Wed, 16 Feb 2005, Robert Campbell wrote:

> I am not a programmer, but have decided to learn Python.  I am wondering
> if anyone has used the Activestate ActivePython and what are the
> advantages/disadvantages of using it rather than the standard Python
> tools.

If you're on Windows, I recommend it.

It is the full Python, plus some Windows extensions.

The only downside I've encountered is that, as of 2.4, it no longer 
includes the Help files in their original HTML format.  Instead, there's 
just one big help file in Windows Help format.

I prefer the HTML, because I can then run searches against it from 
outside the help system.  I've gotten around this by also installing the 
help files from www.python.org; that gives me everything but the 
Win32-specific stuff.

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


Re: [Tutor] Active Python

2005-02-18 Thread Terry Carroll
On Thu, 17 Feb 2005, Jeff Shannon wrote:

> On Thu, 17 Feb 2005 15:54:43 -0800 (PST), Terry Carroll <[EMAIL PROTECTED]> 
> wrote:
> > 
> > I prefer the HTML, because I can then run searches against it from
> > outside the help system.  
> 
> Interesting -- I prefer the CHM (Windows helpfile), because it's
> internally indexed.  I feel that the internal search is more
> convenient than external searches would be.  But I suppose that
> there's room for reasonable people to disagree, here. :)

Sure, and I'd expect I'm in the minority.

I use Agent Ransack for searching files on my system.  I do a search for,
for example, a filename of html$ containing the word "socket"  and can get
a pretty good look at what I'm looking for.

I'll bet that the CHM file can do that at least as well, but since 
I use Agent Ransack for all my document searches (Python-related or 
otherwise), it's most convenient for me use one consistent mechanism.

I'll tell you, if Google desktop had a way of limiting searches to 
specific directories, I'd be in heaven.

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


Re: [Tutor] Active Python

2005-02-18 Thread Terry Carroll
On Fri, 18 Feb 2005, Bill Mill wrote:

> How do you live without cygwin? 

I don't.  I have it installed, too.

But Agent Ransack is more convenient.  If it wasn't free, I'd pay for it.  
It's primarily to search by filename, but the grep-like capability is a 
nice plus.


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


Re: [Tutor] How can i use both float and int?

2005-02-22 Thread Terry Carroll
On Tue, 22 Feb 2005, . , wrote:

> like...
> 
> number1 = raw_input(float int("Number1: ")
> 
> But, I think error will occur...

You have some syntax issues here.

What you want, I think, is to use raw_input to get input, and then convert 
that to float.  try this:

number1 = float(raw_input("Number1: "))


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


Re: [Tutor] How to use threads ?

2005-03-02 Thread Terry Carroll
On Tue, 1 Mar 2005, Mark Kels wrote:

> Can anyone give me a very simple example on thread programming ?

I don't think a simple example is possible, given that threads are 
inherently for slightly more complex processing than you ordinarily do.

That being said, here's an example.

This is a made-up process.  It shows both queuing and an arbitrary number 
of threads.

First, the imports:

###
import random, os, time, sys
import threading, Queue
###

No, I'll define a class for the "work" to be performed.  Basically, each 
work unit just specifies how much time the system is supposed to wait, in 
second; pretend that it's doing some amount of work that takes some 
number of seconds to be performed:

###
class workunit(object):
"""
Sample object to be put on a queue similating work to be done.
variables:
  counter: a serial number just for identification purposes.
  waittime: the time in second it uses up.
  Done: a flag used for a special-purpose end-of-queue sentinel,
 in which case waittime is ignored.
"""
counter = 1
def __init__(self, waittime=0, Done=False):
self.counter = workunit.counter
self.waittime = waittime
self.Done = Done
workunit.counter += 1
###

This will be called in one of two ways:

 w = workunit(waittime=20) # to indicate wait for 20 seconds; or
 w = workunit(Done=True) # to add a "dummy" work unit to the queue so 
 # everyone know the queue is empty and finished.


Okay, imagine a queue (or just a list) full of work units like the above.  
Here's a plain old sequential NON-THREAD way of processing this:

###
def ProcessQueue(work_queue):
"""
Method to process an element from the queue 
 (Non-Threaded implementation).
All it does is loop, doing the following:
  pull an element from the queue (break out if it's a "Done" marker)
  print a starting message;
  wait for the specified amount of time;
  print an ending message
"""
while True:
queue_entry = work_queue.get()
if queue_entry.Done:
break
print "%s starting on workunit %d, %d secs" % \
   (time.asctime(), queue_entry.counter, queue_entry.waittime)
time.sleep(queue_entry.waittime)
print "%s ending for workunit %d" % \
   (time.asctime(), queue_entry.counter)


Okay, understand that, first  See what it's doing?  It's just 
popping things off the work_queue, printing a message, waiting for 
the indicated amount of time in the work unit, and printing another 
message; then starting over.

Now, let's try the same approach with threads.  Firrst, the class 
declaration:

#
class ThreadProcessQueue(threading.Thread):
"""
This is a Threaded equivalent to ProcessQueue().
"""
#

Now, here's the ThreadProcessQueue.__init__:

#
def __init__(self, threadname, work_queue, **kwds):
self.tname = threadname
self.work_queue = work_queue
threading.Thread.__init__(self, **kwds)
print "%s Thread %s started" % (time.asctime(), self.tname) 
#

The parameters here are an arbitrary name for the thread, and the queue it 
will process.  All __init__ does is print a message that the thread 
started.

Here's the guts of it, the ThreadProcessQueue.__run__ method.  NOte how 
similar it is to the non-Threaded version:

#
def run(self):
while True:
queue_entry = work_queue.get()
if queue_entry.Done:
break
print "%s Thread %s starting on workunit %d, %d secs" % \
   (time.asctime(), self.tname, queue_entry.counter, 
queue_entry.waittime)
time.sleep(queue_entry.waittime)
print "%s Thread %s ending for workunit %d" % \
   (time.asctime(), self.tname, queue_entry.counter)

print "%s %s thead ending." % (time.asctime(), self.tname)
self.work_queue.put(queue_entry)
#

The only real difference is that the messages produced include an 
identifier so you can see which thread is generating which message; and 
also there's that self.work_queue.put(queue_entry) at the end. I'll 
discuss that at the end of this message.

Now, here's the main program that uses these.  First some setup:


print "MAIN: %s starting..." % (time.asctime())
work_queue = Queue.Queue()
NumWorkUnits=8
NumThreads=3
WaitTimes = [3,6,9,12,1,5,5,1]
lenWaitTimes = len(WaitTimes)
# WaitTimes is just a list of some arbitrary times representing work
# A particular WorkUnit will wait for one of these times.
ThreadList=[]
###

Queue is s specialized type of FIFO list, 

Re: [Tutor] How to use threads ?

2005-03-02 Thread Terry Carroll
On Wed, 2 Mar 2005, Mark Kels wrote:

> The only problem is that when I try to do it my thread doesnt closes.
> When does a thread closes ?

You got me.  That's what I meant when I wrote "calls to t.isAlive()
returned True long after the thread referred to had finished up and put
out its final [shutdown] message."

I don't know what it would take to have a t.isAlive() call ever come back 
as False.  I may experiment a bit.  That tutorial and program was put 
together on the fly late last night, and I didn't have the opportunity to 
look into that issue.

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


Re: [Tutor] HELP: subclass of int

2005-03-08 Thread Terry Carroll
On Tue, 8 Mar 2005, Shidai Liu wrote:

> I'll sum up a question as following:
> 
> def int5():
> '''return 5'''
> return 5
> 
> class my_int(int):
> def __init__(self):
> self.id = int5()
> int.__init__(self, self.id)  # FIXME: this line doesn't work
> 
> the above code act like this:
> >>> I = my_int()
> >>> I
> 0
> 
> I want it to be like this:
> >>> I = my_int()
> >>> I
> 5

You'll want to use the __new__ method, see 
http://www.python.org/2.2.3/descrintro.html#__new__

Example:

>>> def int5():
... '''return 5'''
... return 5
...
>>> class my_int(int):
...def __new__(self):
...   return int.__new__(self, int5())
...
>>> i = my_int()
>>> i
5
>>>

As someone else pointed out, you probably ought to call int.__init__ as 
well.

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


Re: [Tutor] Acessing files in Windows 2000

2005-03-08 Thread Terry Carroll
On Tue, 8 Mar 2005, Dave S wrote:

> IOError: [Errno 2] No such file or directory: 'c:\\my documents\\memo.txt'

My two thoughts.

1) is there actually a directory named "my documents" at the root?  I 
don't know about Win2000, but for Win XP, the "my documents" directory is 
actually 

 C:\Documents and Settings\username\My Documents

2) The embedded space may be the issue, although I doubt that's it.


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


Re: [Tutor] XML to Python

2005-05-06 Thread Terry Carroll
On Thu, 5 May 2005, Smith, Jeff wrote:

> I'm able to use the built in XML parser to effect "normal" XML parsing
> usage but frequently, I'm not doing anything to complicated and would
> simply like to translate the XML file into a more "Pythonic" structure.  
> What's the best way to do this?  Something from the standard libraries
> would be preferable.

I've made a mental note to try Amara next time I attack an XML problem.  

The description of Amara's Bindery sounds like it tries to take that
"'Pythonic' structure" approach you refer to:

   Amara XML Toolkit [is] a collection of Pythonic tools for XML data
   binding.  Not just tools that happen to be written in Python, but tools
   built from the ground up to use Python idioms and take advantage of the
   many advantages of Python over other programming languages

   Bindery: a data binding tool (fancy way of saying it's a very Pythonic 
   XML API)
   
http://uche.ogbuji.net/uche.ogbuji.net/tech/4Suite/amara/

Mind you, I haven't tried Amara yet, but it looks worth looking into.

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


Re: [Tutor] need a example of translate or maketrans

2005-05-09 Thread Terry Carroll
On Mon, 9 May 2005, Servando Garcia wrote:

>   As you can guess I am working on the riddles. I have looked in vain 
> for a simple example and or a explanation of the string function 
> "translate" or even "maketrans"
>Can someone please send me a working example,please.

Here's a quick example, in which every (lower-case) vowel in a string is
replaced by its vowel position; e.g, 'a' gets replaced by '1', 'e' by
'2', etc., and all consonants (including 'y', for this example) and other
characters are left alone:

>>> from string import maketrans
>>> intab="aeiou"
>>> outtab="12345"
>>> trantab=maketrans(intab, outtab)
>>> instring = "Life of Brian"
>>> outstring = instring.translate(trantab)
>>> outstring
'L3f2 4f Br31n'
>>>




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


[Tutor] Any easy way to invoke the default browser on a specified URL?

2005-05-09 Thread Terry Carroll
Is there any way, from within Python, to cause the default browser 
(Firefox, in my case) to be invoked with a specific URL?

I'd like to do something like (totally made-up name and syntax):

OpenBrowser("http://www.google.com/";)

and have a new browser window opened up pointing to Google.

(Okay, the truth is, this is intended as a handy way of checking answers 
on the Python Challenge, but what the heck.)

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


Re: [Tutor] Any easy way to invoke the default browser on a specified URL?

2005-05-09 Thread Terry Carroll
On Mon, 9 May 2005, Kent Johnson wrote:

>   >>> import webbrowser
>   >>> webbrowser.open("http://www.google.com/";)

Beautiful; just what I needed.  Thanks.

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


Re: [Tutor] map() and lambda to change class instance attribute

2005-05-11 Thread Terry Carroll
It's not often I get a chance to correct Danny, but

On Wed, 11 May 2005, Danny Yoo wrote:

>  map(lambda x: x^2, [1, 2, 3])
> 
>  [x^2 for x in [1, 2, 3]]
> then we're really saying something like this:
> 
>  [1, 2, 3]
>   |  |  |
>   |  |  |  map()
>   |  |  |
>   V  V  V
>  [1, 4, 9]

You probably don't want to invoke a bitwise exclusive-or here!

I think Danny meant:

  map(lambda x: x**2, [1, 2, 3])
  [x**2 for x in [1, 2, 3]]



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


[Tutor] Perl to Python phrasebook

2005-05-13 Thread Terry Carroll
A "Perl-to-Python phrasebook," showing a number of common tasks in Perl, 
and how to do the equivalent in Python, is at 
.

I'll bet a lot of readers know about it already, but I just stumbled on it
and thought that some readers might also find it useful.

Terry

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


[Tutor] How to verify all things are equal to one another

2005-05-14 Thread Terry Carroll

Suppose I have several variables, e.g.: a, b, c, d, e, f, g.

I would like to be able to see if they're all the same, I don't care what
the value is, as long as they're equal.  If they're all equal to 0, or to
"spam", or to ["cleese", "idle", "gilliam"], as long as they're the same.

Is there a more pythonic way of doing this other than, 

if (a == b &
a == c &
a == d &
a == e &
a == f &
a == g):
do stuff

For example, is there any kind of function:

if allsame(a, b, c, d, e, f, g):
   do stuff

I can roll my own, but I was just wondering if something already existed 
like this.

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


Re: [Tutor] How to verify all things are equal to one another

2005-05-16 Thread Terry Carroll
Thanks to all who responded on this.  The commonly suggested:

> if a == b == c == d == e == f == g:
>   do stuff

Is just what I needed.  It never occurred to me that Python supported a 
construct like that.  I would have though this would have evaulated a la:

  if ((a == b) == c) == d) == e) == f) == g):


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


Re: [Tutor] Objects in List

2005-05-16 Thread Terry Carroll
On Mon, 16 May 2005, Viljoen, Danie wrote:

> My Code:
> 
> class MyObject:
>   """A simple VO class"""
>   def setName(self, newName):
>   self.name=newName
>   
>   def getName(self):
>   return self.name
> 
> def main():
>   list=[]
>   #created object in container
>   for i in range(10):
>   myObject = MyObject()   
>   name = 'name:' + str(i)
>   myObject.setName(name)
>   list.append(myObject)
>   
> #manipulate object in list
>   for p in enumerate(range(10)):
>   myObject=p
>   print myObject.getName()

I think what you're looking to do in this second loop is go through the 
list (of instances of MyObject) and print each instance's name.  But your 
for loop doesn't reference list.

(note: "list" is a defined word in Python, so it's best to use something 
else.  I'll use "ObjectList" below, with conforming changes made to the 
earlier loop creating it, of course)

#manipulate object in list
for p in ObjectList:
myObject=p
print myObject.getName()

Prints:

name:0
name:1
name:2
name:3
name:4
name:5
name:6
name:7
name:8
name:9



> C:\development\python__>python list.py
> Traceback (most recent call last):
>   File "list.py", line 25, in ?
> main()
>   File "list.py", line 21, in main
> print myObject.getName()
> AttributeError: 'tuple' object has no attribute 'getName'

Yeah, here's the breakdown of why this is occurring:

> #manipulate object in list
>   for p in enumerate(range(10)):

This is going to essentially generate feed the for loop with a series of
tuples, with the values (0,0), (1,1)  ... (9,9)  [see Danny's message] .  
Each iteration of teh for loop will use one tuple as the value for p.

>   myObject=p

Now, you've set the label mObject to point to a tuple, e.g., (0,0).

>   print myObject.getName()

Now, you've asked to execute a method named getName in the tuple (0,0).  
A tuple doesn't have that method, so the call failes:

> AttributeError: 'tuple' object has no attribute 'getName'

By the way, normally, you wouldn't use getters and setters in Python in 
the way they dominate in Java.  Instead, you'd just use an 
appropriately named attribute.  It makes for simpler code later.  Here'a a 
more pythonic approach:

class MyObject:
"""A simple VO class"""

def main():
ObjectList=[]
#created object in container
for i in range(10):
myObject = MyObject()
myObject.name = 'name:' + str(i)
ObjectList.append(myObject)

#manipulate object in list
for p in ObjectList:
print p.name

if __name__ == '__main__':
main()



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


Re: [Tutor] Linux variable to Python

2005-05-17 Thread Terry Carroll
On Fri, 13 May 2005, Alberto Troiano wrote:

> To explain for those who doesn't know:
> The first line creates a variable named "fec" with the value cam(a Linux 
> function returning year month day hour minute second).jpg
> The second show the value of "fec"
> The third moves hola.txt to the directory grabacion and puts the "fec" value 
> as the new name for the file

I do something similar in a pure python program:


# get to temporary directory
(_year, _mon, _day, _hour, _min, _sec, _none, _none, _none)=time.localtime()
temp_dir = "D%4d-%02d-%02d-%02d%02d%02d" % (_year, _mon, _day, _hour, _min, 
_sec)
os.mkdir(temp_dir)
os.chdir(temp_dir)

This creates a directory in the form D-MM-DD-HHMMSS (for example, at 
6:10:08 PM on May 12, 2005, the directory is named D2005-05-12-181008), 
and then makes it the current directory.

You could probably do the same with minimal tweaking.

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


[Tutor] using -i flag with '''if __name__ == "__main__":'''

2005-05-17 Thread Terry Carroll

I've often found it convenient to run a Python program I'm developing with 
the -i flag. I find it convenient to use as a post-mortem as it hits bugs, 
or to explore data structures.

I've recently started using the construct 

  if __name__ == "__main__":
 main()

And found I can't do the -i thing effectively any more.  What's a good 
equivalent approach?

To use a trivial example, if I have the following program (t2.py):

i = 0
k = 4/i
print i, k

I can do this:

C:\>python -i t2.py
Traceback (most recent call last):
  File "t2.py", line 2, in ?
k = 4/i
ZeroDivisionError: integer division or modulo by zero
>>> i
0
>>>

But if the program is like this:

def main():
   i = 0
   k = 4/i
   print i, k

if __name__ == "__main__":
   main()

That won't work:

C:\>python -i t1.py
Traceback (most recent call last):
  File "t1.py", line 7, in ?
main()
  File "t1.py", line 3, in main
k = 4/i
ZeroDivisionError: integer division or modulo by zero
>>> i
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'i' is not defined
>>>


I understand *why* it won't work; I'm just looking for a nice 
easy way to do the same sort of thing I used to do before I 
started using '''if __name__ == "__main__":'''

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


Re: [Tutor] using -i flag with '''if __name__ == "__main__":'''

2005-05-17 Thread Terry Carroll
On Wed, 18 May 2005 [EMAIL PROTECTED] wrote:

> If main is a class, you could change to 'm = main()'; that would at
> least give you access to the class attributes.

Interesting approach; I'm refering to where main() is a method, the usual 
python idiom.


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


Re: [Tutor] hettingertools?

2005-05-17 Thread Terry Carroll
On Tue, 17 May 2005, D. Hartley wrote:

> This was a hint from a python challenge, but I can't find anything
> about it online: Anyone know?

Raymond Hettinger is a frequent contributor to Python.  I don't know if 
that is part of it.

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


Re: [Tutor] hettingertools?

2005-05-17 Thread Terry Carroll
On Tue, 17 May 2005, Terry Carroll wrote:

> On Tue, 17 May 2005, D. Hartley wrote:
> 
> > This was a hint from a python challenge, but I can't find anything
> > about it online: Anyone know?
> 
> Raymond Hettinger is a frequent contributor to Python.  I don't know if 
> that is part of it.

And actually, I think he was behind itertools, come to think of it.

You're obviously further along the challenges than I am.  I'm on #9 now.  
My defense is that I'm not a programmer by occupation, so I do these in my
Copious Spare Time in the evenings.

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


Re: [Tutor] How to convert hex representation of char? (Challenge part 8)

2005-05-18 Thread Terry Carroll
On Wed, 18 May 2005, Pieter Lust wrote:

> onepart and anotherpart contain many hex representations of nonprintable 
> characters, like '\x14'. But I can't manage to convert those to the 
> actual nonprintable characters. Any hints on how to do this?

The string including the \x14 escape should be usable as is.

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


Re: [Tutor] using -i flag with '''if __name__ == "__main__":'''

2005-05-19 Thread Terry Carroll
On Wed, 18 May 2005 [EMAIL PROTECTED] wrote:

> Another possibility is to look at this recipe:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287

On Tue, 17 May 2005, Kent Johnson wrote:

> I think this approach to debugging won't scale well and you are just
> seeing the tip of the iceberg [and more helpful stuff, snipped.]

Thanks to you both.  I think I may need to step up my "development
environment" beyond emacs and a command line.


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


[Tutor] Finding which list entry is being used, in a for loop (was: using -i flag with '''if __name__ == "__main__":'''

2005-05-19 Thread Terry Carroll
On Tue, 17 May 2005, Kent Johnson wrote:

> I often find that the information in the traceback and exception are
> enough to figure out the problem; if not, a few print statements can
> help. You will get better at this with experience. 

Here's an example where traceback and print statements doesn't help, and
it's really nice to have access to the variables...

Suppose I have a long list of lists (by "long," I mean, too long to
display on one screen and visually examine easily), and am iterating over
the inner lists.  (Forget whether there might be more 
efficient ways;
this is just for illustration.)

In most languages, you'd take this unpythonic approach:

for i in range(0,len(mylist)):
   for j in range(0, len(mylist[i])):
   # stuff dependent on mylist[i][j]

I could put in "print i,j, mylist[i][j]" statements in here, and pretty 
easily zero in on the exceptional data.

But a pythonic approach, and the one I find easiest, is:

for innerlist in mylist:
   for item in innerlist:
   # stuff dependent on item

Now, I can only put in "print item", and finding that in the nested list 
is like a needle in a haystack.  That's what I like about the -i 
option... I can use Python expressions to iterate through the list 
lookingfor stuff.

Is there any way, in the second construct, to have the traceback (or 
equivalent info) include where in "innerlist" "item" came from, and where 
in "mylist" "innerlist" came from?

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


Re: [Tutor] using -i flag with '''if __name__ == "__main__":'''

2005-05-19 Thread Terry Carroll
On Thu, 19 May 2005, Max Noel wrote:

> On May 19, 2005, at 23:05, Terry Carroll wrote:
> 
> > Thanks to you both.  I think I may need to step up my "development
> > environment" beyond emacs and a command line.
> 
>  Actually, if you're having problems with debugging your problem,  
> what you should step up is your approach to debugging/testing.

That's a fair point.

However, most of the programming I'm doing right now is the Python 
Challenge!  Not really programs I'm going to keep around and maintain.

But I think my lesson here is to have two programming modes: one where 
I'm writing programs known to be throwaways (like these Python Challenge 
ones), where I don't do unit-testing and also don't use that "__name__ == 
"__main__" construct (what's the point of that in a throwaway, anyway?); 
and one where I'm writing a keeper, where I build tests.

Thanks!

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


[Tutor] Any Python interface to USPTO web site?

2005-05-27 Thread Terry Carroll
I have the need to run periodic searches on the US Patent and Trademark 
Office website, www.uspto.gov.  Before I reinvent the wheel, I thought I'd 
check to see if anyone knew of such a beast.

For instance, It's like to be able to pass an argument like one of these:

  an/"dis corporation"
  in/newmar-julie

to http://patft.uspto.gov/netahtml/search-adv.htm and get a list of all 
the patents owned by Dis Corporation, or invented by the 1960s Catwoman 
actress; or pass a patent number like 4,150,505 to 
http://patft.uspto.gov/netahtml/srchnum.htm to bring up a particular 
patent.

Then I want to be able to parse out the patent metadata, e.g. inventor 
names, dates filed and issued, etc.

Has this already been done?

The closest my google searches have turned up is 
http://hacks.oreilly.com/pub/h/1724 , but that turns out to be Perl rather 
than Python, and not quite dead-on anyway.


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


Re: [Tutor] Help: wget-- how does it work?

2005-05-27 Thread Terry Carroll
On Fri, 27 May 2005, Aaron Elbaz wrote:

> First, I found the progress bar class from aspn
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639
> 
> This could be used to simulate wgets progress bar. What I'm trying to
> figure out now is how one would stat a file as it was being downloaded
> so that I can feed information to the progress bar, and what the most
> optimal way to do this is?

I use this for an app I have that reads the 27-meg Unihan.txt file; but I 
think I cheat and hardcode the 27-meg no.


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


Re: [Tutor] increment operator

2005-05-28 Thread Terry Carroll
On Fri, 27 May 2005, Lee Cullens wrote:

> I find the following invaluable - maybe you will also.
> 
> http://rgruet.free.fr/PQR24/PQR2.4.html

That's a great resource. Thanks.

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


Re: [Tutor] reading comments

2005-05-28 Thread Terry Carroll
On Sat, 28 May 2005, Servando Garcia wrote:

>   How do I read the comments attached to a zipfile or for
> any file .?

Someone's on riddle 6!  :-)

z = zipfile.ZipFile(zipfilename, mode='r')
zi = z.getinfo(zfilename)
print zi.comment


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


Re: [Tutor] Help: wget-- how does it work?

2005-05-28 Thread Terry Carroll
On Fri, 27 May 2005, Terry Carroll wrote:

> I use this for an app I have that reads the 27-meg Unihan.txt file; but I 
> think I cheat and hardcode the 27-meg no.

I just checked, and, yep, that's exactly what I do.

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


[Tutor] Using Python to keep peace in the house (a little success story)

2005-05-29 Thread Terry Carroll
My wife and I have a disagreement over the use of our digital camera.  She 
likes to have the date printed on the image.  I hate that, I like the 
image to be pristine.

Our camera has the option to put the date on the image, but we can't agree 
on whether to enable it.

Well, Python to the rescue.  Since I learned about Python Imaging Library
doing a couple of the Python Challenges, I decided to find whether I could
add the date to the image after the fact.  It turned out to be pretty
easy.  I had a proof-of-concept done in about 10 minutes, and a finished
project a couple hours later.  I now have a routine called "Imprint" that
adds any arbitrary text to a JPG file; and one called "GetFileDate" that
gets the date of the file (using the EXIF info stored with the image, if
it exists).

Now I can write a little program to loop through all the undated images
(which keep me happy) and make copies with the date, (to keep her happy).

Here's my solution, in case anyone is interested:


==
import Image, ImageDraw, ImageFont

def GetFileDate(file):
"""
Returns the date associated with a file.
For JPEG files, it will use the EXIF data, if available
"""
try:
import EXIF
# EXIF.py from http://home.cfl.rr.com/genecash/digital_camera.html
f = open(file, "rb")
tags = EXIF.process_file(f)
f.close()
return str(tags['Image DateTime'])
except (KeyError, ImportError):
# EXIF not installed or no EXIF date available
import os.path, time
return time.ctime(os.path.getmtime(file))

def ReduceOpacity(im, opacity):
"""
Returns an image with reduced opacity.
Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
"""

import ImageEnhance
assert opacity >= 0 and opacity <= 1
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)
return im

def Imprint(im, inputtext, font=None, color=None, opacity=.6, margin=(30,30)):
"""
imprints a PIL image with the indicated text in lower-right corner
"""
if im.mode != "RGBA":
im = im.convert("RGBA")
textlayer = Image.new("RGBA", im.size, (0,0,0,0))
textdraw = ImageDraw.Draw(textlayer)
textsize = textdraw.textsize(inputtext, font=font)
textpos = [im.size[i]-textsize[i]-margin[i] for i in [0,1]]
textdraw.text(textpos, inputtext, font=font, fill=color)
if opacity != 1:
textlayer = ReduceOpacity(textlayer,opacity)
return Image.composite(textlayer, im, textlayer)

def test():
font=ImageFont.truetype("Arial.ttf", 40)
imagefile = "DSCN0214.JPG"
datetext = GetFileDate(imagefile)
print datetext
im = Image.open(imagefile)
im0 = Imprint(im, datetext, font=font, opacity=0.5, color=(255,255,255))
im0.save("DSCN0214-dated.jpg", "JPEG")

if __name__ == "__main__":
test()

   
==


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


Re: [Tutor] List processing

2005-06-01 Thread Terry Carroll
On 1 Jun 2005 [EMAIL PROTECTED] wrote:

> eYAL001C1 Spar81  3419451845192   1   
> 
> So basically its a table, separated with tabs. What I need to do is make
> a new file where all the entries in the table are those where the values
> in columns 1 and 5 were present as a pair more than once in the original
> file.

This is half-baked, but I toss it out in case anyone can build on it.

Create a dictionary, keyed on column 1.  Read a line and split it into 
the columns.  For each line, create a dictionary entry that is a 
dictionary keyed by column 5, whose entry is a list of lists, the inner 
list of which contains columns 2, 3, 4 and 6.  When a dupe is found, add 
an additional inner list.

So, upon processing this line, you have a dictionary D:

{'eYAL001C1': {'4518': [['Spar', '3419', '4519', '2', '1']]}}

As you process each new line, one of three things is true:

 1) Col 1 is used as a key, but col5 is not used as an inner key;
 2) Col 1 is used as a key, and col5 is used as an inner key
 3) Col 1 is not used as a key

So, for each new line:

 if col1 in d.keys():
if col5 in d[col1].keys()
  d[col1][col5].append([col2, col3, col4, col6])
else
  d[col1][col5] = [[col2, col3, col4, col6]]
 else:
  d[col1]={col5:[[col2, col3, col4, col6]


The end result is that you'll have all your data from the file in the form 
of a dictionary indexed by column 1.  Each entry in the top-level 
dictionary is a second-level dictionary indexed by column 2.  Each entry 
in that second-level dictionary is a list of lists, and each list in that 
list of lists is columns 2, 3, 4 and 6.

if the list of lists has a length of 1, then the col1/col5 combo only 
appears once in the input file.  But if it has a length > 1, it occurred 
more than once, and satisfies you condition of "columns 1 and 5 were 
present as a pair more than once"

So to get at these:

 for key1 in d:
   for key2 in d[key1]:
if len(d[key1][key2]) > 1:
  for l in d[key1][key2]:
print key1, l[0], l[1], l[2], key2, l[3]

I haven't tested this approach (or syntax) but I think the approach is 
basically sound.

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


Re: [Tutor] quick PIL question

2005-06-02 Thread Terry Carroll
On Thu, 2 Jun 2005, D. Hartley wrote:

> What does it mean if my image mode is "P"? In the documentation, it
> says "typical values are '1', 'L', 'RGB', 'CMYK.'" (it's a gif, if
> that's important)

That's really weird.  It does say that (in the description of im.mode, 
where you'd expect it).  But other parts of the doc refer to a "P" mode; 
see the descriptions of im.convert; im.putpalette; and the BMP format 
description.

Seems to be some sort of "palette" format.

Hey!  Look under "Concepts":

The mode of an image defines the type and depth of a pixel in the 
image. The current release supports the following standard modes:

 . . .

- P (8-bit pixels, mapped to any other mode using a colour palette)

 . . . 

Palette

The palette mode ("P") uses a colour palette to define the actual
colour for each pixel.



Not sure what that means, exactly, but it looks like im.palette will get 
the palette of a a P-mode image, and im.putpalette will change it.

I'm not sure how to interpret the palette once you have it, though.  The
description of the ImagePalette class is not too helpful.

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


Re: [Tutor] quick PIL question

2005-06-02 Thread Terry Carroll
On Thu, 2 Jun 2005, Max Noel wrote:

 [explanation snipped]

>  Makes sense?

Yes.  Thanks very much.

I think the problem is the the PIL documentation (reasonably) assumes that 
the reader already understands all the structures used in the imaging it 
supports; it just explains how PIL gives access to those structures.

Perfectly usable for those of us who have worked with images before, and 
now just want to use Python to do so; less usable for those of us who use 
Python, and now want to extend our knowledge to cover images.

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


Re: [Tutor] Detecting my own IP address?

2005-06-05 Thread Terry Carroll
The Python Cookbook (1st ed) suggests this, in recipe 10.4 ("Finding Your 
Own Name and Address):

>>> import socket
>>> myname = socket.getfqdn(socket.gethostname())
>>> myaddr = socket.gethostbyname(myname)
>>> myaddr
'192.168.1.120'




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


[Tutor] Trying Ruby...

2005-06-06 Thread Terry Carroll
This message is not as off-topic as it at first appears.

I'm a user of Activestate's ActivePython under Windows/XP.  I want to give
Ruby a spin, just for the heck of it.  I vaguely recall a post a few
months ago, I don't know if it was in this forum, where someone had a
problem in Python, and it turns out it was because a Ruby install messed
with some setting, perhaps in the Windows registry.

I can be more vague upon request.

Anyway, I'd like to install Ruby, but want to make very sure I don't 
impair my Python environment.  Is there anything anyone can point to to 
ensure this?

Any suggestions on the safest Ruby to install would also be appreciated.

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


Re: [Tutor] More image manipulation

2005-06-07 Thread Terry Carroll
On Tue, 7 Jun 2005, D. Hartley wrote:

> def findlist():
> newlist = []
> for i in range(480):
> line = fromlist[:640]
> del fromlist[:640]
> x = line.index(195)
> y = x + 5
> z = line[x:y]
> del line[x:y]
> for i in z:
> newlist.append(i)
> for i in line:
> newlist.append(i)
> return newlist

where does the variable named "fromlist" come from?  It's not passed into 
the method as a parameter.

> B). If I run the steps in makenewpic one by one in the interpreter, it
> doesnt give me any "x not in list" error, it lets me do the result =
> newim.putdata(a) just fine.  But then when I type result.show() it
> tells me 'NoneType' object has no attribute 'show'.  At first I
> thought it was because when I was creating the blank newim, I was
> using mode "RGB" and adding a list of "P" pixel values to it. But I
> fixed it so that my newim is also mode "P" and it still tells me that
> type(result) = None.

You have:

> result = newim.putdata(a)
> return result

>From the PIL docs, putdata does not appear to return an image.  The docs
for putdata say:

  putdata

  im.putdata(data)
  im.putdata(data, scale, offset)

Usually, when a PIL method returns an image, the docs say "=> image" 
after the method signature.  My guess is that putdata returns None, which 
would be consistent with the error message "'NoneType' object has no 
attribute 'show'."

You'll probably want:

 newim.putdata(a)
 return newim

Instead.


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


Re: [Tutor] repr()

2005-06-07 Thread Terry Carroll
On Tue, 7 Jun 2005, Bernard Lebel wrote:

> repr( myFunc )
> ''
> 
> 
> 
> s = repr( myFunc() )
> print s
> 
> 'None'

In the first example, your repr invocation is:

  repr(myFunc)

i.e., you're asking for the repr of the function myFunc.

In the second example, your repr invocation is:

  repr(myFunc())

i.e., you're calling the function myFunc and asking for the repr of the 
*result*

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


Re: [Tutor] More image manipulation

2005-06-07 Thread Terry Carroll
On Tue, 7 Jun 2005, Terry Carroll wrote:

> On Tue, 7 Jun 2005, D. Hartley wrote:
> 
> > def findlist():
> > newlist = []
> > for i in range(480):
> > line = fromlist[:640]
> > del fromlist[:640]
> > x = line.index(195)
> > y = x + 5
> > z = line[x:y]
> > del line[x:y]
> > for i in z:
> > newlist.append(i)
> > for i in line:
> > newlist.append(i)
> > return newlist
> 
> where does the variable named "fromlist" come from?  It's not passed into 
> the method as a parameter.

I'm thinking more and more that this is the issue.  

Take a look at this, and see if it gives you the flavor.  Only the third 
approach actually gives you what (I think) you want, rather than reusing 
the same list over and over.

def testit1():
   print fromlist1[0]
   del fromlist1[0]
   return
fromlist1 = ['a', 'b', 'c', 'd']
print "testit1: Denise problem"
testit1()
testit1()
testit1()

def testit2(flist):
   print flist[0]
   del flist[0]
   return
fromlist2 = ['a', 'b', 'c', 'd']
print "testit2: Python Gotcha #6"
# http://www.ferg.org/projects/python_gotchas.html
testit2(fromlist2)
testit2(fromlist2)
testit2(fromlist2)

def testit3(flist):
   mylist = flist[:] 
   # copy the list rather than mutating it for next time
   print mylist[0]
   del mylist[0]
   return
fromlist3 = ['a', 'b', 'c', 'd']
print "testit3: the right way"
testit3(fromlist3)
testit3(fromlist3)
testit3(fromlist3)



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


Re: [Tutor] More image manipulation (fwd)

2005-06-07 Thread Terry Carroll

On Tue, 7 Jun 2005, D. Hartley wrote:

> OK. I tried them out and I do see the diffence. (btw, testit1 gave me
> the following error:
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> testit1()
>   File "", line 3, in testit1
> del fromlist[0]
> IndexError: list assignment index out of range
> 
> ... was that something you intended? that didnt happen with my
> original problem).

Interesting; I get this:

testit1: Denise problem
a
b
c
testit2: Python Gotcha #6
a
b
c
testit3: the right way
a
a
a

> Anyway I def notice the diff between 2 and 3, but see here's the thing:
> 
> I think I *do* want it like #2, becaues I want it to keep returning
> the same list (i.e., move on and use line 2 (b), and then line 3 (c),
> and so on), rather than keep iterating over the same first line (a)
> over and over again.

Okay, gotcha.  

Here's my take on this sort of thing: I like to look at a method as a
black box, defined by the method signature and its call.  My basic rule is
that I don't every like a method to alter any data except what it passes
back.  

So... My approach, which I think is a little more clean and isolatable, is
to pass anything that the function needs to operate in as a parameter;  
then, if I want to alter that list, I create a new copy and pass that
back.  I have a deep distrust of globals.

So instead of this:

  def snip_first:
delete alist[0]   # find alist via scoping rules
return

and calling it like this:

 
  alist = ['a', 'b', 'c']
  snip_first()

I'd prefer to set it up like thi:

  def snip_first(input_list):
output_list = alist[:]
delete output_list[0]
return output_list

  alist = ['a', 'b', 'c']
  alist=snip_first(alist)

(Both of these are untested, I'm just winging it here.)


> I want to take the first line in the picture,
> rearrange the pixels, and pop that line into the new list that I can
> then (eventually) create a new image from. I *thought* my list was
> populated (it's 307200 pixels long, after all), but it wont work when
> i try to putdata it onto a new blank image.

I don't know about you, but if it were me, without that encapsulation, I'd 
have a tough time figuring out what's getting modified when.

> > > where does the variable named "fromlist" come from?  It's not passed into
> > > the method as a parameter.
> 
> No, I had it defined right before the function. it pulls it in just
> fine. 

Yes, but global scoping often messes me up, so I always use a local scope.  
If it's not parameter-passed into or created in a method, I don't use it
in the method.

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


Re: [Tutor] Newsreader list name?

2005-06-10 Thread Terry Carroll

> > I'm on OS X 10.4.1 and downloaded Hogwasher to try.  Using my ISPs
> > news server I found the two lists I mentioned,  but I can't get
> > anything nntp://news.gmane.org alone or in combination with a group

Try news://news.gmane.org , if your reader requires specifying the 
protocol.


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


Re: [Tutor] Web browser

2005-06-11 Thread Terry Carroll
On Sat, 11 Jun 2005, Ismael Garrido wrote:

> I've been looking around for a web browser either written in python, or 
> with python bindings.

MozPython?  http://www.thomas-schilz.de/MozPython/README.html

> What I need to do is load a web-page, enter a password-protected site 
> and follow certain links, it needs to have frames and follow the refresh 
> meta. I'm running winxp, python 2.4

Why not write a scraper, using something like Beautiful Soup?


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


Re: [Tutor] Python Books

2005-06-12 Thread Terry Carroll
On Sun, 12 Jun 2005, Kristiano Ang wrote:

>  So, I'm prepared to invest in a Python book of some sort that will
> help me master the language. Does anyone have any recommendations? Or
> perhaps tutorials? I have limited programming experience (a little
> dabbling in C++).

For a how-to-learn Python book, it's hard to beat "Learning Python"

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


Re: [Tutor] Trying Ruby...

2005-06-14 Thread Terry Carroll
My original question:

> I vaguely recall a post a few months ago, I don't know if it was in this
> forum, where someone had a problem in Python, and it turns out it was
> because a Ruby install messed with some setting, perhaps in the Windows
> registry Anyway, I'd like to install Ruby, but want to make very
> sure I don't impair my Python environment.

On Tue, 7 Jun 2005, Premshree Pillai wrote:

> I have Python and Ruby -- not ActiveState -- installed on an XP box. No
> issues.

On Tue, 7 Jun 2005, Christian Wyglendowski wrote:

> If I remember correctly, it had to do with Tk getting messed up.  But
> that's all I recall :-)

Sorry for the late acknowledgement.  My computer fried not long 
after I posted the message, and I haven't been reading much email 
since.  Thanks to you both.

I found the problem I recalled; Ruby sets some environment variables 
assuming that it's the only user of Tk, and hoses the Python usage:

 
https://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=824756
 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=922914&group_id=5470

or http://makeashorterlink.com/?G4DC1624B and 
http://makeashorterlink.com/?T1EC2124B

I'll just be careful when I install Ruby and take corrective action if 
needed.

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


Re: [Tutor] Why does invalid syntax pop up?

2005-07-07 Thread Terry Carroll
On Thu, 7 Jul 2005, Nathan Pinno wrote:

>   Why does invalid syntax popup?




>   def lookup_login_command(site,filename):
>   print "Lookup a login info card"
>   site = raw_input("Site: ")
>   if sitelist.has_key(site):
>   print "The ID is: ",sitelist[site][0]
>   print "The password is: ",sitelist[site][1]
>   else:
>   print site," was not found."

Bad indentation.  Try this instead:


def lookup_login_command(site,filename):
print "Lookup a login info card"
site = raw_input("Site: ")
if sitelist.has_key(site):
print "The ID is: ",sitelist[site][0]
print "The password is: ",sitelist[site][1]
else:
print site," was not found."

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


Re: [Tutor] New entry in the Tutor list - Question: Python and dbf files

2005-07-08 Thread Terry Carroll
On Fri, 8 Jul 2005, Alessandro Brollo wrote:

> 1. Does a Python dbf reader/writer module exist
> somewhere?

A google on "python dbf" led me to a few promising leads:

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715
 http://www.fiby.at/dbfpy/
 http://www.garshol.priv.no/download/software/python/   (see "dbfreader")


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


Re: [Tutor] cPickle.load()

2005-07-16 Thread Terry Carroll
On Sat, 16 Jul 2005, David Jimenez wrote:

> [EOFError on pickle]

First, something that may not be a problem, but let's get it out of the 
way, anyway:

> pickle_file=open("pickles1.dat","w")
>. . .
> pickle_file=open("pickles1.dat","rb")

I notice that your write open does not specify binary mode, but your read 
open does.  If you're on an OS where binary mode matters (e.g., Windows), 
you should use it in both places, or the file you write out will probably 
be corrupted.


But here's your real problem (I'm adding line numbers in brackets for 
reference):


> for i in pickle_file:#1
> i=cPickle.load(pickle_file)  #2
> print i  #3
> pickle_file.close()  #4

On line #1, you're telling it to iterate over the pickel file.  That is, 
line #1 says, read a line from pickle_file, and assign it to i.

Then, in line #2, bearing in mind you've already taken the first line out 
of the file, you're doing a pickle load, starting part-way into the file.

I suspect that, because it's a binary file, your line #1 is putting the 
whole file contents into i, and nothing's left in the file to process.  
When you do the load, you hit EOF, hence the error.

It should be a big red flag to you that you're modifying variable i both 
in line #1 and line #2.  That never leads anywhere good.

What I would suggest is that you endlessly loop over a load call, and wrap 
it in a try/except combination to exit on EOF.  Here's an equivalent to 
the above four lines, that takes that approach:


=
try: 
while True:
i=cPickle.load(pickle_file)
print i
except EOFError:
pass

pickle_file.close()
=


Hope this helps.


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


Re: [Tutor] What's the invalid syntax? Code supplied

2005-08-04 Thread Terry Carroll
On Thu, 4 Aug 2005, Bob Gailer wrote:

> At 06:51 PM 8/3/2005, Nathan Pinno wrote:
> >That's part of my signature. It describes who I am.
> 
> I would like to know who you are, but the signature does not convey enough 
> information. My guess is that you are on the crew of a MacDonald's 
> restaurant in Camrose, Alberta (thanks to Google) but what is "Woffee"?

See, I figured he worked at the accounting firm of Crew Camrose McDonalds.  
:-)

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


Re: [Tutor] What's the invalid syntax? Code supplied

2005-08-05 Thread Terry Carroll
On Fri, 5 Aug 2005, Nathan Pinno wrote:

> What's the invalid syntax? Here is the code:

Nathan,

My method when encountering a syntax error like this is to look at the 
part of my code that's generating the syntax error, and see what structure 
or function it's using.  Then find a program segment that does the 
same thing in a working program or tutorial.  Now that I've 
written a good number of working programs, I can usually find 
working examples in my own programs, but if not, I hit a python 
book.

I think you'll find this more efficient than simply posting the error 
message and code to the Tutor list and asking for help; save the Tutor 
list for the really challenging problems.  You'll find you learn a lot 
more by taking a good whack at it yourself, first.

In your case you've already indicated the error is in this code:


> hand = {
> '0' : ["Ace"]
> '1' : ["Two"]
> '2' : ["Three"]
> '3' : ["Four"]
> '4' : ["Five"]
> '5' : ["Six"]
> '6' : ["Seven"]
> '7' : ["Eight"]
> '8' : ["Nine"]
> '9' : ["Ten"]
> '10' : ["Jack"]
> '11' : ["Queen"]
> '12' : ["King"]
> }

You're trying to initialize a dictionary.  So go find some examples of 
initializing a dictionary that work, compare them to your code, and see if 
you can see what's different about your code.

Good luck!

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


Re: [Tutor] IP Address from Python module?

2005-08-05 Thread Terry Carroll
On Fri, 5 Aug 2005, Joseph Quigley wrote:

> Is it possible to get my internet and/or network IP address from Python?

import socket
ipaddr = socket.gethostbyname(socket.gethostname())


Some users report this gives a meaningless '127.0.0.1' (i.e., localhost), 
though.  But try it and see.  It works for me.


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


[Tutor] Averaging a list of lists with a listcomp?

2007-04-25 Thread Terry Carroll
I have a list (of arbitrary length) of lists, each sublist having a fixed
number N of items, all integers.

I would like to produce a list of N items, each item of which is an 
integer which is the average of the elements in the same position of each 
of the sublists of the original list.

I realize the wording above is all hash, so here's the example:

Say the original list is: [[10, 20, 30], [50, 20, 90], [30, 20, 30]]

I want the new list to be: [30, 20, 50]

Because the average of the first elements 10, 50, 30 is 30; second 
elements 20, 20, 20 is 20; and third elements 30, 90, 30 is 50.

Since I'm taking a list and producing another list, I figured this would 
be a good candidate for a list comprehension; but I don't see a good 
approach. 

My attempt is below, but I can see the list comp approach is pretty yucky.  
As you can see, I've got a working solution, but in an effort to think 
more pythonically about list comprehensions, I'd like to see what a good 
list comprehension approach is.

(note: I know there's an integer division issue here; ignore that, I just 
picked easy numbers to keep the example clean.)

My approach:

###
orig = [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
average = [30, 20, 50]

# iterative approach
L1 = [0, 0, 0]
for item in orig:
for i in range(0,3):
L1[i] += item[i]
L1 = [x/len(orig) for x in L1]
print L1

#list comp approach
L2 = [
sum([x[0] for x in orig])/len(orig),
sum([x[1] for x in orig])/len(orig),
sum([x[2] for x in orig])/len(orig)
]
#ew, yuck, hard-coded list indices!
print L2

assert L1 == L2 == average
###


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


Re: [Tutor] Averaging a list of lists with a listcomp?

2007-04-26 Thread Terry Carroll
On Thu, 26 Apr 2007, John Fouhy wrote:

> So, here is your one-line solution:
> 
> >>> [sum(x)/len(x) for x in zip(*orig)]
> [30, 20, 50]

Beautiful.  Thanks.

I wasn't looking for a one-liner, exactly, but just something that was 
more straightforward and pythonic than what I was doing.  But I find that 
that's often what one-liners are, as long as they aren't one-liners for 
one-linerness's sake!

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


Re: [Tutor] How to test for a remainder from division

2007-05-15 Thread Terry Carroll
On Tue, 15 May 2007, Kent Johnson wrote:

> Matt Smith wrote:
> > 
> > Thanks for the help. For future reference how do I go look at the
> > implementation of a particular function (the ones coded in Python, I
> > don't know C)?
> 
> Look in the lib directory that was installed with Python. The location 
> varies. On Windows look for C:\Python2.x\Lib. My Mac has it at
> /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5
> 
> In the python interpreter, try
>  >>> import sys
>  >>> sys.path
> 
> The lib directory will be listed as one element of sys.path.

Will the following approach always work?  It's what I start with.

>>> import calendar
>>> print calendar.__file__
C:\Python25\lib\calendar.py


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


Re: [Tutor] Starting with wxPython

2007-06-01 Thread Terry Carroll
On Tue, 22 May 2007, Alan Gauld wrote:

> "Alan Gilfoy" <[EMAIL PROTECTED]> wrote
> 
> > soon, and I plan to use wxPython to do so. What, do you think, is 
> > the best tutorial out there for wxPython?
> 
> I'm working through the new wxPython book and highly recommend
> it. 

I second that.  I've used Tkinter for a few years, mostly because the docs 
on it are good.  I looked at wxPython, but there was no good vehicle for 
learning it, and I gave up.

When the wxPython book came out, I borrowed a copy from the Library (hint: 
even if your library doesn't have it, it can probably get it for you via 
Inter-Library Loan) and read it.  I liked it enough to go and buy my own 
copy as a reference after returning it.

I'm now planning on my next GUI app to be wxPython-based.

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


Re: [Tutor] Launch external application?

2007-06-04 Thread Terry Carroll
On Fri, 1 Jun 2007, Brad Tompkins wrote:

> Is there an easy way to make a python script that will launch an external
> application for me ?  I'm using Windows XP and I'm trying to create a little
> front end that will launch the VLC media player for me.

In addition to Grant's approach, if your filetype (say "mpg") is already 
associated with VLC, you can use this:

os.startfile('filename.mpg')
 

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


Re: [Tutor] Finding all locations of a sequence

2007-06-14 Thread Terry Carroll
On Thu, 14 Jun 2007, Lauren wrote:

> Subseq  AU can bind to UA (which is normal) and UG (not so
> normal) and I want to know where UA, and UG are in the large
> RNA sequence, and the locations to show up as one...thing.

How about something like this?



def seqsearch(seq, targets):
   """
   return a list of match objects, each of which identifies where any of
   the targets are found in the string seq
seq: string to be searched
targets: list or tuple of alternate targets to be searched

   note: re.findall is not used, because it wont catch overlaps
   """
   
   import re
   resultlist=[]
   pos=0
   regext_text = "|".join(targets)
   regex = re.compile(regext_text)
   while True:
  result = regex.search(seq, pos)
  if result is None:
 break
  resultlist.append(result)
  pos = result.start()+1
   return resultlist

targets = ["UA", "UG"]
sequence="UUCAAUUUGATACCAUAGCUUCCGUGCGATACCAAGCGU"
#++   ++
# 0 1 2 3 4 5
# 012345678901234567890123456789012345678901234567890
# note: matches at 15 & 28
matches = seqsearch(sequence, targets)
for m in matches:
   print "match %s found at location %s" % (sequence[m.start():m.end()],
m.start()) 


This prints, as expected:

match UA found at location 15
match UG found at location 28

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


[Tutor] Getting at sqlite schema info from within Python?

2007-06-25 Thread Terry Carroll

Is there any way of getting to the schema of an sqlite database from 
within Python? In particular, a list of tables in the DB.

>From the sqlite command line, I can use the sqlite 

 .tables

command to get a list of tables in the database; and then the 

 PRAGMA TABLE_INFO(tablename)

to get the information on the various fields in the table.

>From within Python, though, I can't find a way to get the table names.  
If I know the table names, the PRAGMA approach works to get at the field
info; but I can't figure out how to find the table names first.

Trying to use the sqlite .tables command via Python gives me:

>>> c.execute(".tables;")
Traceback (most recent call last):
  File "", line 1, in 
sqlite3.OperationalError: near ".": syntax error

...which makes some sense; it isn't SQL.

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


Re: [Tutor] Getting at sqlite schema info from within Python?

2007-06-25 Thread Terry Carroll
On Tue, 26 Jun 2007, John Fouhy wrote:

> On 26/06/07, Terry Carroll <[EMAIL PROTECTED]> wrote:
> >
> > Is there any way of getting to the schema of an sqlite database from
> > within Python? In particular, a list of tables in the DB.
> 
> Try 'select * from sqlite_master'.

You rock.  Thanks.

And, now that I know that trick, googling on sqlite_master leads me to 
http://www.sqlite.org/faq.html#q7 which explains the format.

Honest, I really did spend quite some time reading the sqlite docs and
trying things; somehow I missed the FAQ.

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


Re: [Tutor] UTF-8 filenames encountered in os.walk

2007-07-03 Thread Terry Carroll
On Tue, 3 Jul 2007, William O'Higgins Witteman wrote:

> Has anyone found a silver bullet for ensuring that all the filenames
> encountered by os.walk are treated as UTF-8?  Thanks.

What happens if you specify the starting directory as a Unicode string, 
rather than an ascii string, e.g., if you're walking the current 
directory:
 
 for thing in os.walk(u'.'):

instead of:

 for thing in os.walk('.'): 

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


Re: [Tutor] UTF-8 title() string method

2007-07-03 Thread Terry Carroll
On Tue, 3 Jul 2007, Jon Crump wrote:

> but where there are diacritics involved, title() gives me:
>
> AngoulMe, Angoumois.
>
> Can anyone give the clueless a clue on how to manage such unicode strings 
> more effectively?

I think setting the locale is the trick:

>>> s1 = open("text.txt").readline()
>>> print s1
ANGOUL.ME, Angoumois.
>>> print s1.title()
Angoul.Me, Angoumois.
>>> import locale
>>> locale.setlocale(locale.LC_ALL,('french'))
'French_France.1252'
>>> print s1.title()
Angoul.me, Angoumois.



(sorry about the '.' for the characters that my term program won't accept)

You might have to hunt around and experiment for the right locale that 
will work in all your cases.


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


Re: [Tutor] Calculating Deflection angles

2007-07-04 Thread Terry Carroll
On Wed, 4 Jul 2007, nitin chandra wrote:

> Hello Every One,
> 
> I create a list of coordinates of 2 lines.
> X11,Y11 & X12,Y12 as starting and ending of one line.
> X21,Y21 & X22, Y22 as starting and ending of the 2nd line.
> 
> Now is there any way to calculate the deflection angle between the two
> lines? Will any modules be required other than Python 2.3 (on Linux)?

I'm looking at my old book "A Programmer's Geometry" now.

If you first put the equations for each line in the AX+BY+C=0 form, i.e.,

 Line 1:  A1*X + B1*Y + C1 = 0
 Line 2:  A2*X + B2*Y + C2 = 0

Then the angle between them is found by:

theta = acos(
 (A1*A2 + B1*B2) 
   /
   sqrt((A1**2+B1**2)*(A2**2+B2**2))
   )

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


  1   2   3   4   5   >