[Tutor] data type conversion for print statement

2007-09-25 Thread Tim
Hello,
I have a print statement where I use concatenation of variables with "+" to
avoid extra whitespaces. The variables are mixed (float/int).

How can I convert them all to strings to have a clean print statement?

example
print str(var1)+"and this "+str(var2)+"needs to check "+str(var3)

how can I convert var1, var2, var3 all at once?

This would avoid errors because of mixed data types.

BTW, why does a statment like
print var1, var2
automatically add spaces between the variables?

Thanks in advance for your help.

Timmie

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


[Tutor] function for removing all white spaces from a string

2007-10-01 Thread Tim
Hello,
after reading the responses to athread in 2004 [1] I am wondering why there is
no easy function in python to remove all white spaces from a string.

Like:

" i am very fine "
to
"iamveryfine"

In IDL there's just one simple function which does this: STRCOMPRESS [2].

Is there really not yet such a function in Python?

If not I created it:

a = " i am very fine "


def strcompress(mystring):
... mystring_compressed = ''.join(mystring.split())
... return mystring_compressed

 strcompress(a)
'iamveryfine'

Thanks for your input,
Timmie

[1] Re: how to strip whitespaces from a string.
http://article.gmane.org/gmane.comp.python.tutor/18622

[2] STRCOMPRESS http://idlastro.gsfc.nasa.gov/idl_html_help/STRCOMPRESS.html

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


Re: [Tutor] Introspecting class and method names

2005-12-14 Thread tim
* Kent Johnson <[EMAIL PROTECTED]> [051214 16:00]:
> Tim Johnson wrote:
> > I was pleasantly surprised to notice in a previous thread that python
> > can automagically retrieve a class name thru __class__.__name__
> > 1)Can someone point me to further documentation on this topic?
> 
> __name__ and __module__ at least are documented here:
> http://docs.python.org/ref/types.html#l2h-118
> 
> You can also try dir(type) to see attributes of type 'type', the base class 
> of all 
> new-style classes, or dir(A) for any class A to see attributes of the class. 
> Many of the 
> special attributes (__xxx__) are referenced in the index to the Python 
> Reference Manual.
> http://docs.python.org/ref/genindex.html
> 
> > 2)Is it possible for the name of a class method to be 
> >   programmatically retrieved from within the scope of the method?
> >   If so, how? and pointers to docs would be welcome also.
> 
> You can look at the stack frame to find out what method you are in. See for 
> example
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062
 
  Thanks! This is really nice! I'm too old to write things like
  www! - so I won't - but I am impressed.
  quick, handy function here:
def Here():
""" Return file, name and line number of calling function"""
return 'File: %s Function: %s Line Number: %s' % \
   (sys._getframe(1).f_code.co_filename,
sys._getframe(1).f_code.co_name,
    sys._getframe(1).f_lineno)

Must tie a string around my finger with "sys._getframe" on it.
I'm sure it has many other goodies.
cheers
==
Tim Johnson <[EMAIL PROTECTED]>
  http://www.alaska-internet-solutions.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accuracy of time.sleep()

2004-12-04 Thread Tim Peters
[Dave S <[EMAIL PROTECTED]>]
> OK I may be pushing it,  ;-)

Yup .

> I need a script to sleep from any point to 8:05AM when in needs to
> re-start.
> 
> So I calculate the number of seconds with the following 
> 
> def secs_till_805():
># Returns the number of seconds till 8:05AM
> 
>secs_5min=5*60
>secs_24hr=24*60*60
>secs_8hr=(8*60*60)+secs_5min
>secs_8hr_24hr=secs_24hr-secs_8hr
> 
>hours=int(strftime('%H'))
>mins=int(strftime('%M'))
>secs=int(strftime('%S'))

Ouch.  Never try to pick apart the current time by computing it more
than once.  For example, if the time at the start of that block is
just a fraction of a second before 9AM, it's quite possible you'll end
up with hours==8 and mins==secs==0 (because the time is 8:59:59 at the
time you do the "%H" business, and but it's 9:00:00 by the time you
get to "%M").  That would throw you off by an hour.  The same kind of
thing can happen a little before the (any) minute changes too.

>sec_left=secs_24hr-((hours*60*60)+(mins*60)+secs)
>
># If we are before 8:05, then ...
>if sec_left>secs_8hr_24hr:
>return sec_left-secs_8hr_24hr
>
># If we are after 8:05, then ...
>return sec_left+secs_8hr

Here's a different way, computing current time only once, and using
the datetime module to do all the fiddly work:

def seconds_until(h, m=0, s=0):
from datetime import datetime, time, timedelta

target_time = time(h, m, s)
now = datetime.now()
target = datetime.combine(now.date(), target_time)
if target < now:
target += timedelta(days=1)
diff = target - now
return diff.seconds + diff.microseconds / 1e6

This returns seconds as a float, which is good (Python's time.sleep()
can make sense of floats, and sleep for fractional seconds).

> Then I ...
> 
> sleep(secs_till_805())

With the above, you'd do

time.sleep(seconds_until(8, 5))

instead.

> I expected the script to re-start 2-3 seconds after 8:05, python
> reloading after a long sleep etc, what I get is the script restarting at
> 08:04.55, earlier ???

You'll probably never know why for sure.  Python calls platform C
library gimmicks to sleep, which in turn invoke operating system
facilities.  Understanding the whole story would require that you
understand everything all of those do.

[later]
> It must be cummulative error over 10s of thousands of seconds.

Maybe.

> Its a bodge (& cron or at are better) but I suppose I could calculate seconds
> to 8:05 sleep(seconds*0.95), re calculate secs to 8:05 sleep(seconds)
> which should reduce the error to almost zip.

That's also a good idea in order to avoid surprises due to crossing
daylight time boundaries (assuming you mean 8:05 according to the
local wall clock).  Here's a function building on the above:

def sleep_until(h, m=0, s=0):
from time import sleep

while True:
delay = seconds_until(h, m, s)
if delay < 10.0:
sleep(delay)
return
else:
sleep(delay / 2)

That is, it cuts the sleep time in half repeatedly, until less than 10
seconds remain.  It can sleep for hours at a time, but as the target
time approaches it wakes up more frequently.  This should keep the
program loaded in memory as the target time gets near.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-07 Thread Tim Peters
[Brian van den Broek]
...
> Or, so I thought. I'd first tried getting the alarm datetime by simply
> taking the date component of datetime.datetime.now() and adding
> to the day value. That works fine, provided you are not on the last
> day of the month. But, when checking boundary cases before
> posting the code I sent, I discovered this sort of thing:
> 
> >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity
> >>> ldj = last_day_of_june# short for typing
> >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
>
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
> ValueError: day is out of range for month
> >>>
> 
> So, adding to the day or the month was out, unless I wanted
> elaborate code to determine which to add to under what
> circumstances.

Actually, you needed simpler code :

>>> import datetime
>>> ldj = datetime.datetime(2004, 6, 30)
>>> new_day = ldj + datetime.timedelta(days=1)
>>> print new_day
2004-07-01 00:00:00

or even

>>> ldy = datetime.datetime(2004, 12, 31)
>>> new_day = ldy + datetime.timedelta(days=1)
>>> print new_day
2005-01-01 00:00:00

In other words, if you want to move to the next day, add one day! 
That always does the right thing.  Subtracting one day moves to the
previous day, and so on.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-07 Thread Tim Peters
[Dick Moores]
...
> Brian, where did you learn about the ".seconds". And
> the .year, .month,.day of
>
> "alarm_datetime = datetime.datetime(now.year + 4, now.month,
>  now.day, alarm_hour, alarm_minute)"?
>
> Does this come from a general knowledge of OOP, or is it
> somewhere in the Python docs? The only thing I've seen, and it's
> not an explanation, is in note (1) on
> http://docs.python.org/lib/datetime-date.html

On that very page, the instance attributes of datetime objects are documented:

"""
Instance attributes (read-only): 

year 
Between MINYEAR and MAXYEAR inclusive. 

month 
Between 1 and 12 inclusive. 

day 
Between 1 and the number of days in the given month of the given year.
"""

That's how you know that a datetime instance d has d.year, d.month and
d.day attributes, and how you know what they mean.  The docs for the
other datetime module objects have similar sections.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-09 Thread Tim Peters
[Dick Moores]
> VERY helpful, Matt. Thanks.
> 
> One question: This seems to not compute accurately at all
> when the imaginary part of number=complex() is other than 0.

That's just because the math was wrong .  Starting with theta =
0.0 *assumed* the imaginary part is 0, although I can't guess whether
that was by accident or design.

Try this instead:

def croots(c, n):
"""Return list of the n n'th roots of complex c."""
from math import sin, cos, atan2, pi

arg = abs(c)**(1.0/n)
theta = atan2(c.imag, c.real)
result = []
for i in range(n):
theta2 = (theta + 2*pi*i)/n
x = arg * cos(theta2)
y = arg * sin(theta2)
result.append(complex(x, y))
return result
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-10 Thread Tim Peters
[Dick Moores]
> Aw, that's just amazing.

Well, complex numbers are amazing in many ways.  The code is actually
obvious, if you understand the motivation.  Polar coordinates are more
natural for complex * /  and **.  If you a view a complex number c as
a vector in the complex plane (from the origin to c), then c's n'th
roots are just n equally spaced spokes on a wheel, with one of the
spokes coinciding with c's "natural" angle divided by n.  That
determines the angles of all the spokes, since there are n spokes
altogether and the angular difference between adjacent spokes is
constant (2*pi/n).  All the seeming obscurity in the code is really
just due to converting between rectangular (x, y) and polar (length,
angle) representations.

If we worked with polar coordinates all along, the input would be
given as a magnitude and angle, say r and a.  The n n'th roots then
(still in polar coordinates) all have magnitude r**(1./n), and the n
angles are a/n, a/n + b, a/n + 2*b, ..., and a/n + (n-1)*b where
b=2*pi/n.  Piece o' cake!

> I put your function in http://www.rcblue.com/Python/croots.py, 

That's fine by me -- but I'd appreciate it if you stopped claiming
there that my name is Bill .

...

> Actually, I'm trying to write a Python script that computes all 3
> roots of a cubic equation. Do you happen to have one tucked
> away in your store of wisdom and tricks? (One for real coefficients
> will do).

I don't, no.  You can code one for cubics from Cardano's formula, e.g.,

http://mathworld.wolfram.com/CubicFormula.html
 
but it's rarely worth the bother -- it's complicated and doesn't
generalize.  In practice, roots for polynomials beyond quadratics are
usually obtained by numerical approximation methods that don't care
much about the polynomial's degree.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-12 Thread Tim Peters
[Dick Moores]
>>> Actually, I'm trying to write a Python script that computes all 3
>>> roots of a cubic equation. Do you happen to have one tucked
>>> away in your store of wisdom and tricks? (One for real coefficients
>>> will do).

[Tim Peters]
>> I don't, no.  You can code one for cubics from Cardano's formula, e.g.,
>>
>> http://mathworld.wolfram.com/CubicFormula.html
>>
>> but it's rarely worth the bother -- it's complicated and doesn't
>> generalize.

[Dick]
> I accept this challenge to write a complicated script of little value.

Cool!  If it's just for fun, it's fun.

>> In practice, roots for polynomials beyond quadratics are
>> usually obtained by numerical approximation methods that don't care
>> much about the polynomial's degree.

> Are these "numerical approximation methods" pythonically possible?

Of course, but coding general-purpose root finders-- even if "general"
is limited to just polynomials --requires mathematical and numeric
expertise.  If it interests you, there are book-length treatments of
the subject, and there's really no easy reliable approach.  Good
online sources for numeric algorithms include:

http://www.netlib.org/

Just Googling on

polynomial roots Python

will point you to

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


Re: [Tutor] turning a number into a formated string

2004-12-15 Thread Tim Peters
[Ertl, John]
> I need to take a number and turn it into a formatted string.
> The final output needs to look like    when the X is the
> integer part padded on the left and  Y is the decimal part padded
> on the right.
> I figured I could split the number at "." and then use zfill or
> something like this  (LEVEL1 = "%04d" % LEVEL1) for the 
> part but I am not sure how to right pad the decimal part of the
> number.
> Example.
> 1 and 1.0  needs to look like 0001 ( I figured I would have to
> check the length of the list made from the split to see if a decimal
> portion existed)
> 1.1 needs to look like 00011000
> 22.33 needs to look like 00223330

Really?  The input has two digits 3, but the output has three digits
3.  I'll assume you meant 00223300 instead.

> .22 needs to look like 2200
> Any ideas on the right padding the decimal side using "0"

I expect that a "%09.4f" format does everything you asked for, except
that it contains a period.  So let's try to repair that:

>>> def johnpad(n):
... return ("%09.4f" % n).replace('.', '')

Then:

>>> johnpad(1)
'0001'
>>> johnpad(1.0)
'0001'
>>> johnpad(1.1)
'00011000'
>>> johnpad(22.33)
'00223300'
>>> johnpad(.22)
'2200'
>>>
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


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

2004-12-15 Thread Tim Peters
[Brian van den Broek]
> in Marc's check_range thread, I had proposed:
>
> def check_in_range(value):
> 
> in_range = False
> if 9 < value < 90:
> in_range = True
> return in_range
>
> and DogWalker suggested the better:
> 
> def check_in_range(value):
> return 9 < value < 90
> 
> As I mentioned, I feel as though I have a mental block getting in the
> way of coming up with code in the smoother fashion of the second snippet
> above.

Don't feel frustrated -- using Boolean expressions idiomatically is
very much a learned skill.  So is adding integers, but *that* got
drilled into you over years, and years, and years.  It won't take
quite as long to sling bools .

The worst abuse is one you're perhaps not prone to:  having a Boolean
expression e, and then writing

if e == True:

instead of

if e:

For some reason, that's extremely common in code written by newcomers
to Pascal.  I haven't seen it nearly as often in Python code, but
don't have a theory as to why not.

> As I have been making a lot of use of a construct (pattern?)
> similar to my code above, wherein I try something, and return True if it
> works, False if it doesn't, I've begun to wonder if I am overlooking a
> improvement similar to that in DogWalker's suggestion. As an example of
> the sort of thing I have been doing:
>
> import datetime
> def is_leap_year(year):
> '''-> boolean
> 
> Returns True or False as year is, or is not, a leap year.
> '''
> is_leap = True
> try:
> datetime.date(year, 2, 29)
> except ValueError:
> is_leap = False
> return is_leap
> 
> Please ignore that there is a function in the calendar module to do
> exactly this, and that, as that library function does, it could be done
> by simply testing if the leap year conditions are met. In the general
> case, it doesn't seem that there will always be an easy conditional
> test.

That's true!  You shouldn't work too hard to contrive one either, or
the clarity of your code will suffer.

> This function here was written so as to illustrate the structure
> I'm interested in, without the complications of the details of actual
> cases I have used.
> 
> (I hope that's clear enough--it felt much clearer before I'd spent the
> time drafting a post.)

So far as leap years go, the obvious difference is that February has
29 days in leap years, but only 28 otherwise.  You exploit that above
by checking whether trying to construct "February 29th" raises an
exception.  That's fine.  At least an equally good way is to note that
the difference between March 1 and Februrary 28 is 2 days only in a
leap year, so:

from datetime import date, timedelta
def isleap(year):
return (date(3, 1, year) - date(2, 28, year)).days == 2

is another clear way to do it, and so is

def isleap(year):
return (date(year, 2, 28) + timedelta(1)).month == 2

and so is

def isleap(year):
return (date(year, 3, 1) - date(year, 2, 1)).days == 29

or even, keying off the observation that only leap years contain 366 days,

def isleap(year):
return (date(year+1, 1, 1) - date(year, 1, 1)).days == 366

IOW, if you can think of one way to do it with a Boolean expression,
it's common to think of more.  And, of course, that's the kind of
practice that makes it feel natural, over time.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hooray! I finished the 'Learning Python for absolute beginners'

2010-01-09 Thread Tim Goddard
Ok, it's not a big deal, but once I learned enough I went off on a few
tangents to create programs of my own design.  Since I had to return
the book to the public library, I finally got back to finishing the
last chapter.  Since the book is not current, I took the time to
decipher the differences and eventually figured out the final project
creating an asteroids game using the latest livewires.  I would
eventually like to use pygame, but for now I'm content that it works.

I know there have been some questions in the past about errors, so
this is simply being submitted as a placemarker for those working
through the same book.

I'm really glad I decided to learn Python!

I also figured out how to configure Eclipse IDE to recognize modules.
Apparently in the preferences for each 'project' is a separate
PYTHONPATH.. which is not to be confused with sys.path.  Adding the
appropriate folders to the preferences allows the user to browse
through a module i.e.

after writing:
'from livewires import games'

typing:
'games.'  yields a drop down menu of all methods etc very
convenient when trying to follow older tutorials of older packages.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hooray! I finished the 'Learning Python for > absolutebeginners'

2010-01-10 Thread Tim Goddard
 "Alan Gauld"  wrote:

> I assume you have already installed the PyDev plugin?
>
> I'm currently reading a book on Eclipse (Eclipse Distilled) which has
> turned up many settings and tricks that I was unaware of. It is a
> powerful tool but like all such it takes a lot of learing to get the most
> from it.
>
> Alan G.
>

Sorry Alan, I am being too vague in my writing.  My instance of
Eclipse was installed as part of Python(x,y) and included the Pydev
plugin.  I was fortunate as a beginner programmer, that someone else
figured out how to configure Eclipse with the PyDev plugin.  Using
other IDE installed as part of Python(x,y) i.e. Spyder, gave me
insight into what I was missing with Eclipse.  I'm missing a lot, I
mean simply missing out on one aspect of Eclipse.

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


Re: [Tutor] SYS Long File Names?

2010-02-07 Thread Tim Golden

On 06/02/2010 21:36, FT wrote:

 I was looking at the sys.argv(1) file name and it is the short 8 char
name. How do you place it into the long file name format? I was reading
music files and comparing the name to the directory listing and always comes
back as not found because the name was shortened.


I'm assuming you're on Windows (because I don't
think *nix has a long/short-name concept). I've
never seen sys.argv return an 8.3 name, but taking
your word for it:


import win32api

print win32api.GetLongPathName ("eight.thr")



If you don't have the pywin32 packages installed
(and you don't want to) then you can do the same
using ctypes by accessing the kernel32 DLL:

http://msdn.microsoft.com/en-us/library/aa364980%28VS.85%29.aspx

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


[Tutor] distutils and the postinstallation script

2010-02-24 Thread Tim Brown
Hi,

I've written an installation, for Windows, using distutils to produce a .exe 
setup file.
When the setup.exe is run, can my postinstallation script can find out which 
folder the setup.exe is in ?

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


Re: [Tutor] Cannot open SQLite database

2010-02-25 Thread Tim Golden

On 25/02/2010 15:18, Michael M Mason wrote:

ALAN GAULD wrote on 25 February 2010 at 08:50:-


So I think that was a red herring, sorry.
It also looks like the Read Only check box in the main
Explorer property dialog tab doesn't mean what it says...


Doesn't the Read Only checkbox have a coloured square rather than
a tick?

AFAIK the coloured square is intended to mean "doesn't apply", and
you should see the same thing on all folders. You can tick the
checkbox and click the "Apply" button to make all the files in the
folder Read-Only in one easy move.  It doesn't make the folder
Read-Only, and if you close and re-open the Properties dialog after
ticking the checkbox you'll find the coloured square will reappear.



Haven't been following this thread, but just picking up on this: the
read-only attribute on folders means: this is a special folder
(eg My Documents). There's no way to make a directory read-only
like this...

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


Re: [Tutor] browing windows registry

2010-03-17 Thread Tim Golden

On 17/03/2010 02:35, Jeff Peery wrote:

hello,
I want to browse the windows registry for the program ids listed under the 
categories:
63D5F430-CFE4-11d1-B2C8-0060083BA1FB
63D5F432-CFE4-11d1-B2C8-0060083BA1FB

where might be the best way to learn how to do that with python?


Hopefully this might be of use:

http://timgolden.me.uk/python-on-windows/programming-areas/registry.html

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


Re: [Tutor] Remote access from Windows PC to a Linux box

2010-03-31 Thread Tim Golden

On 30/03/2010 17:29, Mike Baker wrote:

I'm trying to connect to a Linux box from my Windows machine and execute a
series of commands

I want a script to always
execute the same series of commands without having to do so manually.   I
also have code that will execute a single command like cat a file and write
the ouput to a new file. However, when I try to use the communicate object
in subprocess, my window hangs.



This works for me:


import os, sys
import subprocess

PLINK = "plink"
REMOTE_USER = "tgol...@web30.webfaction.com"
PIPE = subprocess.PIPE

p = subprocess.Popen ([PLINK, REMOTE_USER, "ls"], stdout=PIPE)
stdout, stderr = p.communicate ()
print "#1:", stdout.splitlines ()[0]

with open ("out.txt", "w") as f:
  p = subprocess.Popen ([PLINK, REMOTE_USER, "cat .bashrc"], stdout=f)
  p.communicate ()
print "#2:", open ("out.txt").read ().splitlines ()[0]

p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
stdout, stderr = p.communicate ("ls\nexit\n")
print "#3", stdout

p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
p.stdin.write ("ls\nexit\n")
stdout, stderr = p.communicate ()
print "#4", stdout



A few things to note, none of which I believe to be germane to the
issues you're experiencing:

* You almost never need to use shell=True on a Windows call to subprocess.
  If in doubt, don't use it.

* Definitely better to pass the list-of-params style as the first param
  of subprocess.Popen; it sorts out issues with embedded spaces etc.

* The open ("...", "w") in your second example *may* be closing the
  file immediately. I doubt it, since you'd expect Popen to hold a
  reference, but I haven't checked the implementation.

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


[Tutor] Creating class instances through iteration

2010-04-15 Thread Tim Goddard
I came across a situation where what I thought I wanted to do was to create
a class that was spawned from data in a .csv file.  Where column 1 was the
name I wanted to use for each instance.  I had it all figured out and
working except for how to write a statement where the left hand side could
be a changing identifier.

All I could figure out was how to create the same instance 50 times albeit
in different ways.

For example each row would look like [name, value1, value2, value3], I
planned on passing the three values as a tuple

The code would simply be:

for row in csvimport:
tuple = (row[1],row[2],row[3])
instancename = Classname(tuple)

How could I create different instances inside an iteration loop for each row
?  Is it possible to change the name through modification of self attribute
(wait is self an attribute?)  Are cats sleeping with dogs here or what?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Programming microsoft excel

2010-05-07 Thread Tim Golden

On 06/05/2010 17:51, hbu...@ovi.com wrote:

Hi
guys can i use python's win32com module to do the same tasks
that i do with visual basic for applications (vba).
I mean automating tasks for excel e.t.c and accessing
Access databases. If win32com doesnt which module can i use?


You want to look at the http://www.python-excel.org/ page and
the associated (and older) http://groups.google.com/group/python-excel
Google group

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


[Tutor] Successfully trapping the [505 file not found] error

2010-05-26 Thread Tim Johnson
Using Python 2.6.2 on Slackware 13.0 32-bit.
I'm using Python as a command-line application to do an FTP download
which processes a file of jpg filenames, downloading each. Not all
of the file names can be found.

I'm having a problem trapping *all* of the file not found errors.
As an example my application (which is heavily logged) will
successfully handle the 'not found' exeception multiples of time,
continuing with the download process, and then inexplicably (to me)
fails.

What follows is the exception handling snippet:
## --
except ftplib.error_perm, e:
msg = "Couldn't get %s  %s" % (fname,str(sys.exc_info()[1]))
log.add(msg)
more-code-follows
## --
When the code above is successful, the application simply
logs the exception and continues.
When the code above fails the traceback is as follows:

## --
Traceback (most recent call last): 
<... traceback stack of program locations removed ...>
error_perm: 550 file not found.
ERROR MESSAGE: 550 file not found.
ERROR TYPE: 
## --

Is there something that can improve my error handling process here
so that my application safely and consistantly continues downloading
so that the entire download process is completed?

-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Successfully trapping the [505 file not found] error

2010-05-26 Thread Tim Johnson
* Luke Paireepinart  [100526 15:37]:
> 
> Are you sure you aren't doing anything with the ftp object in the
> "more code follows"?
> You are probably creating another error of the same type while
> processing your exception, so the second one doesn't get caught.

  :) Ain't it nice to have a second set of eyes! You are correct.
 I'm attempting to reconnect without the exception handling.

  Thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] upgrade from 2.6.2 to 2.6.5?

2010-06-22 Thread Tim Golden

On 22/06/2010 13:40, Alex Hall wrote:

Hi all,
I am having problems with the Durus package, and I was told that
changing Python versions might help. Most of the other dependencies of
the project I have are 2.6 only, so I do not want to change versions
from 2.6.x, but I would like to try upgrading to 2.6.5 to see if that
fixes things. Will I lose all my packages (in lib/site-packages) if I
do this? Will anything else break, as far as third-party installs go?


Nope. That should just work (assuming your 3rd-party installs aren't
susceptible to changes occurring between 2.6.2 and 2.6.5... although,
that said, you're *relying* on Durus being affected by such changes :) )

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


Re: [Tutor] (no subject)

2010-06-30 Thread Tim Golden

On 30/06/2010 17:20, Aaron Chambers wrote:

I'm new to Python, and wanted to start messing around with it, but the
computer I'm using is running Windows 7, so is there a version of Python
that's compatible with 7?


Yes. I'm running versions from Python 2.1 all the way up to the latest
2.x and 3.x Subversion releases. Take your pick --->

  http://python.org/download/

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


Re: [Tutor] Strange sqlite3 behavior

2010-07-17 Thread Tim Golden

On 17/07/2010 8:10 AM, Lang Hurst wrote:

I just had the weirdest issue with sqlite3.  I was trying to update a
field to "Active".  I have a little database of students and sometimes
they get sent to juvi, or just check out for a couple of months and show
back up.  Anyway, I wanted to just have a field that had either "Active"
or "Inactive".  I know, could go all boolean, but wanted to leave my
options open.

Anyway, my code was along the lines of

 UPDATE students SET active="Inactive" where id="123456"


That would work, but

 UPDATE students SET active="Active" where id="123456"


wouldn't.  It wouldn't do anything, the field still held "Inactive".


My guess -- without bothering to check the sqlite docs -- is that
sqlite uses single quotes to delimit strings and double quotes to
delimit column. Or at least that it can be set up to do that. If
that is the case then "Active" is taken to refer to the column
active and not to the string active. So you're just setting it
to itself.

Try it with 'Active' instead.

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


Re: [Tutor] need help with msvcrt.getch()

2010-07-27 Thread Tim Golden

On 27/07/2010 15:22, Richard D. Moores wrote:

Python 3.1 on Vista.

Please see.

I'm trying to recall what I used to know, thus this simple script. But 'y'
or 'q' do nothing. What's wrong?


msvcrt.getch returns bytes on Python 3.1; you're comparing against
string. Try

if key == b'y':
  ... etc.

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


Re: [Tutor] how to do excel in python

2010-08-05 Thread Tim Golden

On 05/08/2010 15:08, invincible patriot wrote:


hi, can any one tell me how can I access MS excel worksheet in python and how 
can I access itz individual cells..??


http://www.python-excel.org/

(First hit for python excel in Google)

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


Re: [Tutor] os.urandom()

2010-08-10 Thread Tim Golden

On 10/08/2010 15:33, Steven D'Aprano wrote:

On Tue, 10 Aug 2010 02:24:00 pm Dave Angel wrote:

[...]

Any suggestions how to fix the Windows console to interpret utf8?


There are several tracker issues relating to this one. The current
position seems to be: it's not easy. I've done no more than play
with it myself. Steven's suggestions about chcp 65001 look good but
Python doesn't supply a 65001 codec so you have to play about with
aliases and even then it doesn't work :(

Feel free to search the tracker and research a solution :)

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


Re: [Tutor] Module for browsing Windows?

2010-08-11 Thread Tim Golden

On 11/08/2010 01:17, Chorn, Guillaume wrote:

Hello,

I'm pretty new to Python programming and it is my first programming
language.  I made a script that uses data from two different .csv files
to make calculations and then spit the results out in a third .csv file.
However, the process of typing in the path to each of the two input
files and the output file (or even copying and pasting those paths) is
somewhat cumbersome from a UI perspective, and so I was wondering if
there is a Python module out there that allows you to browse to and
select files using a Windows-style interface.  Thanks!


Take you pick of any of these:

  http://wiki.python.org/moin/GuiProgramming

Although (to select one) you might find that EasyGui
gets you going the quickest:

  http://easygui.sourceforge.net/

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


Re: [Tutor] os.access unreliable?

2010-08-25 Thread Tim Golden

On 25/08/2010 09:28, Albert-Jan Roskam wrote:

Hi,

Hi I'm using os.access to do a preliminary check to see if I have RW access, but
it seems to be unreliable. In a dir for which I have only read access, os.access
also says I have write access. This is under Windows 2000. I could of course use
a try-except and catch the IOError, but I'd like to know why the code below
isn;t working.

 def isAcccessible(self):
 if os.access(self.path, os.R_OK) and os.access(self.path, os.W_OK):
 return True
 else:
 return False


os.access is effectively meaningless under Windows, especially
against directories. It only checks the read-only flag (which
doesn't mean anything for directories anyway).

There is a long-open issue here:

  http://bugs.python.org/issue2528

which I am half-minded to close although I could be
persuaded to pursue it if anyone were interested enough.
On the other hand, os.access checks are open to race-conditions
in any case, so you might simply be better off with a
try-except block as you suggest.

If you want more information I can explain further but unless you
want to dive into the Windows API and use AccessCheck -- which is
what that patch is doing -- then I suggest you use try-except

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


Re: [Tutor] os.access unreliable?

2010-08-25 Thread Tim Golden

On 25/08/2010 11:15, Steven D'Aprano wrote:

It also warns that os.access doesn't take into account network file
sharing permissions.


Heh. On Windows it doesn't take into account *any* file sharing
permissions :)

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


Re: [Tutor] Can't process all my files (need to close?)

2010-09-20 Thread Tim Golden

On 20/09/2010 16:19, aenea...@priest.com wrote:

My Python script needs to process 45,000 files, but it seems to blow
up after about 10,000. Note that I'm outputting
bazillions of rows to a csv, so that may be part of the issue.

Here's the error I get (I'm running it through IDLE on Windows 7):

Microsoft Visual C++ Runtime Library Runtime Error! Program:
C:\Python26\pythonw.exe This application has requested the Runtime to
terminate it in an usual way.


OK. Just for starters (and to eliminate other possible side-issues)
can you run the same code directly from the command line using
c:\python26\python.exe?

ie just open cmd.exe, cd to the directory where your code is and type:

c:\python26\python.exe 

I assume that the same thing will happen, but if it doesn't then
that points the finger at IDLE or, possibly, at pythonw.exe. (And
might also give you a workaround).


I think this might be because I don't specifically close the files
I'm reading. Except that I'm not quite sure where to put the close.


On this note, it's worth learning about context managers. Or, rather,
the fact that files can be context-managed. That means that you can
open a file using the with ...: construct and it will automatically
close:



with open ("blah.csv", "wb") as f:
  f.write ("blah")

# at this point f will have been closed




1) During the self.string here:

class ReviewFile: # In our movie corpus, each movie is one text file.
That means that each text file has some "info" about the movie
(genre, director, name, etc), followed by a bunch of reviews. This
class extracts the relevant information about the movie, which is
then attached to review-specific information. def __init__(self,
filename): self.filename = filename self.string =
codecs.open(filename, "r", "utf8").read() self.info =
self.get_fields(self.get_field(self.string, "info")[0])
review_strings = self.get_field(self.string, "review") review_dicts =
map(self.get_fields, review_strings) self.reviews = map(Review,
review_dicts)


So that could become:


with codecs.open (filename, "r", "utf8") as f:
  self.string = f.read ()





2) Maybe here? def reviewFile ( file, args): for file in
glob.iglob("*.txt"): print "  Reviewing" + file rf =
ReviewFile(file)


Here, with that many files, I'd strongly recommend using the
FindFilesIterator exposed in the win32file module of the pywin32
extensions. glob.iglob simply does a glob (creating a moderately
large in-memory list) whose iterator it then returns. The
FindFilesIterator actually calls underlying Windows code to
iterate lazily over the files in the directory.



3) Or maybe here?

def reviewDirectory ( args, dirname, filenames ): print
'Directory',dirname for fileName in filenames: reviewFile(
dirname+'/'+fileName, args ) def
main(top_level_dir,csv_out_file_name): csv_out_file  =
open(str(csv_out_file_name), "wb") writer = csv.writer(csv_out_file,
delimiter=',') os.path.walk(top_level_dir, reviewDirectory, writer )
main(".","output.csv")


Again, here, you might use:


with open (str (csv_out_file_name), "wb") as csv_out_file:
  writer = csv.writer (csv_out_file, delimiter=",")



I'm fairly sure that the default delimiter is already "," so you
shouldn't need that, and I'm not sure where csv_out_file_name
is coming from but you almost certainly don't need to convert it
explicitly to a string.

Note, also, that the os.walk (*not* os.path.walk) function is often
an easier fit since it iterates lazily over directories, yielding a
(dirpath, dirnames, filenames) 3-tuple which you can then act upon.
However, you may prefer the callback style of the older os.path.walk.

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


Re: [Tutor] Windows printing

2010-09-23 Thread Tim Golden

On 23/09/2010 07:30, Rance Hall wrote:

I'm using this page as a reference:
http://timgolden.me.uk/python/win32_how_do_i/print.html

I'm able to print to the default printer ok, but I can't seem to find
out how to get to pick the printer I want to use.

This is from a CLI app, so there is no gui.

win32print seems like it has everything I need, I just can't quite see
how to put it together

I'd like to have my python app ask which printer to use as opposed to
just using the default printer.

win32print.EnumPrinters() does give me a list, but its not just a list
of names. the list also includes other items like network paths
depending on the level of detail you specify in EnumPrinters.


Tim has two possible ways to print.  Tim shows how to use the win32api
to pass a ShellExecute command that prints.  The catch to this command
is you have to print a file type and it has to be the default type for
an app to open.

He also shows a way to skip the ShellExecute and use the print api
directly to gain some more control.

Based on my needs, I'm pretty sure that I'll need to use win32print,


Tim's how-to is likely not for my version of python (mine is 3.1)
since some of his command fail on my system because mine wants options
or parameters that Tim doesn't mention.


I've fixed one issue: the win32print example now passes bytes for Py3.x
and str for 2.x; that example now works for me. I haven't worked through
the other examples yet but thanks for the heads-up.


I'm going to be printing automatically generated check-in tickets.

I can make the ticket, save it as a temp file, but I can not print to
the default printer, I must be able to select the destination printer.

My plan is to ask the user what printer to use for the session, and
save that printer name in a variable and direct all automated prints
to that printer.

As we move the laptop from place to place the default printer is not
always available.  And the available printer changes depending on
location.

Ideally there would be a variation of the ShellExecute command that
would let me specify a printer name.

Windows 7 is the predominate windows platform we are using.


OK. Thanks for the fairly clear explanation of the situation. I agree
that a ShellExecute variant which allowed printer selection would be
good, but I don't believe there is one. That's basically because
ShellExecute is really what the user indirectly actions when they
double-click or right-click on a file and choose one of the actions:
there's no scope for additional info within the ShellExecute mechanism.
Obviously a program called in this way is free to do whatever it wishes
in the way of selection dialogs and the like.

One thing which isn't entirely clear to me is whether your ticket-saved-
as-a-temp-file is printer-ready, eg plain text, PS or PCL, or whether
you'd really want to format it further before printing. On the basis
that it's ready to go direct, the following very slight variation should
do what I think you want: (tested only on XP; I'll try to get hold of
a W7 machine to double-check)


import os, sys
import win32print

printer_info = win32print.EnumPrinters (
  win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
)
printer_names = [name for (flags, description, name, comment) in 
printer_info]

for i, name in enumerate (printer_names):
  print ("%d) %s" % (i + 1, name))

n_printer = int (input ("Which printer: "))
printer_name = printer_names[n_printer+1]
print ("Using", printer_name)

hPrinter = win32print.OpenPrinter (printer_name)
#
# ... and so on, per the original example
#



Is this what you're after? Or have I missed the point?

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


Re: [Tutor] Windows printing

2010-09-23 Thread Tim Golden

On 23/09/2010 14:05, Rance Hall wrote:

For the first roll-out and testing I figured plaintext was good enough.

Future revisions will probably use the PDF library you also referred
to on your page.

Either way that is as printer ready as I expect I will be able to get it.


One option you might want to consider is to use IE as a print
engine. Here's some code I use to print stuff via IE, converting
it to HTML via Pygments. (Handy for printing Python code).

Obviously you could skip the conversion step and just format your
ticket as HTML in the normal way. The key bit is the multipurpose
ExecWB function. The second param controls whether the printer
selection dialog is shown or not. I generally tell it not to
prompt, which goes to the default. In this example I've set it to
1 which forces a prompt.


import os, sys
import codecs
import glob
import tempfile
import time

import pygments
from pygments.lexers import get_lexer_for_filename
from pygments.formatters import HtmlFormatter
import win32com.client


css_filepath = os.path.join (os.path.dirname (__file__), "print.css")

def main (fileglob, encoding="utf-8"):
  ie = win32com.client.gencache.EnsureDispatch 
("InternetExplorer.Application")

  html_filepaths = []
  try:
for filepath in glob.glob (fileglob):
  formatter = HtmlFormatter (
title=filepath,
linenos="inline",
full=True,
cssfile=css_filepath,
noclobber_cssfile=True
  )
  lexer = get_lexer_for_filename (filepath)
  with tempfile.NamedTemporaryFile (suffix=".html", delete=False) 
as html_file:

utext = codecs.open (filepath, encoding=encoding).read ()
highlighted = pygments.highlight (utext, lexer, formatter)
html_file.write (highlighted.encode ("utf8"))

  #
  # Load the temporary HTML file up in IE and
  # print it to the default printer, relying
  # on the fact the IE will load Windows filepaths
  # without strictly requiring file:// URLs with
  # escaped paths.
  #
  ie.Navigate (html_file.name)
  while ie.ReadyState != 4 or ie.Busy:
pass
  ie.ExecWB (6, 1, None, None)
  while ie.ReadyState != 4 or ie.Busy:
pass
  html_filepaths.append (html_file.name)
  finally:
#
# This is arbitrary, but avoids having to implement
# event handlers. It takes a while for the print
# handler to complete; wait until it does before
# closing IE.
#
time.sleep (5)
ie.Quit ()
for filepath in html_filepaths:
  os.unlink (filepath)

if __name__ == '__main__':
  main (*sys.argv[1:])





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


Re: [Tutor] Windows Printing, Round 2

2010-09-23 Thread Tim Golden

On 23/09/2010 7:18 PM, Rance Hall wrote:

Again I'm referencing Tim Golden from

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


This code block is relevant:



import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()
#
# raw_data could equally be raw PCL/PS read from
#  some print-to-file operation
#
if sys.version_info>= (3,):
   raw_data = bytes ("This is a test", "utf-8")
else:
   raw_data = "This is a test"

hPrinter = win32print.OpenPrinter (printer_name)
try:
   hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data",
None, "RAW"))
   try:
 win32print.WritePrinter (hPrinter, raw_data)
   finally:
 win32print.EndDocPrinter (hPrinter)
finally:
   win32print.ClosePrinter (hPrinter)





Things are progressing along and I'm really more and more excited
about python, every time I try to do something, It just seems to work
and be straightforward.

Notes:  AFAICS win32pring.StartDocPrinter(hPrinter, 1, (jobname, None,
None)) might be better as the last "None" tells the system to process
through the print driver, Raw Data bypasses the print driver.
Due to the variety of printers involved, I think bypassing the print
driver with "RAW" will come back and bite me later.

I also added a variable to catch the output from
win32print.WritePrinter() so it would not display on the screen.  I
called it hSize.

Questions:

Under python 3 I need to send a byte string to the printer.  But I
wont have a byte string, I'll have a filename

What is the pythonic way to convert a file to a bytestream?

I can open the file for reading, and loop line by line through the
file appending bytes(line, "utf-8") to variable but this doesn't seem
right to me somehow.

Is there a better way to do this?


My HP laserjet 1100 does not print the job automatically.  It accepts
the job, processes the job, and then lights up the lights on the front
of the printer and waits.  When I hit the button, then the document
prints.

I have only seen this behavior before when printing envelopes.  When
an envelope print job goes to the printer it behaves the same way my
python print jobs are.

I suspect that this has to do with the fact that the page size of the
printjob is either not specified or different from the standard 8.5 in
wide x 11 in long it can handle.

win32print documentation mentions DocumentProperties and
DeviceCapabilities that might help, but I don't see how to use them to
implement a solution for my problem.

I further suspect that there are other printers out there that will
behave similarly if they don't have specified what they needed.

How do you deal with this problem?


Essentially the complexity of the answer to this question -- the big
gap between raw (textish) data and any other formatted output -- was
what prompted my earlier suggestion to use IE as a print engine.

An easy answer to your questions above would be:

send the file's byte contents (see snippet below) followed by a formfeed
to prompt the printer into actually doing something.


import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()  # for simplicity

raw_data = open ("filename.txt", "rb").read () + b"\x0c"

# OpenPrinter / ClosePrinter dance as above



Does that help?

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


[Tutor] function with multiple checks

2010-09-27 Thread Tim Miller
I've got a small function that I'm using to check whether a password is 
of a certain length and contains mixed case, numbers and punctuation.


Originally I was using multiple "if re.search" for the patterns but it 
looked terrible so I've read up on list comprehensions and it's slightly 
improved. I just can't escape the feeling that there's a more elegant 
way to do this that I'm missing.


I've been looking through all the python stuff that I thought might be 
relevant (lambda, map, filter, set, frozenset, etc) but nothing has come 
together. Just wondering if anyone has suggested reading material for 
alternate ways they'd handle this code.


CODE:

from string import ascii_lowercase, ascii_uppercase, digits, punctuation


def complex_password(password):
"""Checks password for sufficient complexity."""
if len(password) < 12:
return False
if len([c for c in password if c in punctuation]) == 0:
return False
if len([c for c in password if c in digits]) == 0:
return False
if len([c for c in password if c in ascii_uppercase]) == 0:
return False
if len([c for c in password if c in ascii_lowercase]) == 0:
return False
return True
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function with multiple checks

2010-09-27 Thread Tim Miller

set does seem to have what you want: isdisjoint() could do the trick.
Eg:

 if set(punctuation).isdisjoint(password) or 
set(digits).isdisjoint(password) or set(ascii_uppercase).isdisjoint(password) 
or set(ascii_lowercase).isdisjoint(password):
  return False
 return True


You could even confuse yourself and put it all on one line:

   return not any(set(chars).isdisjoint(password) for chars in 
[punctuation, digits, ascii_uppercase, ascii_lowercase])

but I wouldn't recomended it. I guess this can even shortened further.
(note: the 'not' operator is needed, because isdisjoint returns True for what 
you probably prefer as False.)


Here I was thinking I'd read through set types thoroughly and now that 
you've pointed out isdisjoint it really jumps out describing exactly the 
usage I was looking for.


isdisjoint(other)¶

Return True if the set has no elements in common with other. Sets 
are disjoint if and only if their intersection is the empty set.

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


Re: [Tutor] function with multiple checks

2010-09-27 Thread Tim Miller

On 28/09/10 01:46, Jerry Hill wrote:

The way you've written it obviously works fine.  That being said, I'd
probably do something like this:

from string import ascii_lowercase, ascii_uppercase, digits, punctuation

def complex_password(password):
 '''Checks to make sure a password is complex'''
 checks = [
 lambda p: len(p)>  12,
 lambda p: any(c in punctuation for c in p),
 lambda p: any(c in digits for c in p),
 lambda p: any(c in ascii_uppercase for c in p),
 lambda p: any(c in ascii_lowercase for c in p),
 ]

 return all(check(password) for check in checks)

if __name__ == '__main__':
 passwords = ['password', 'Password1234567', 'Password1.234567']
 for password in passwords:
 print password, complex_password(password)


In the complex_password function, I create a list of tests, each of
which is a function that returns either true or false.  In this case I
used lambdas to create the function objects, since all the tests
easily fit on a single line, but it would be fine to define a function
elsewhere and use it in the list if you had more complicated checks to
do.

all() is a built in function that returns True if all of the elements
in an iterable are true (or the iterable is empty), and otherwise
returns False.  That seems like an ideal way to execute a bunch of
tests and return True if all of them pass, and otherwise return false.
  In this case, the iterable is a generator expression that evaluates
each of the rules with the supplied password.

any() is similar, but it returns True if any member of the iterable is True.

Looking back at it, I probably should have used longer variable names
in my rules, which would have made them a bit easier to read.  When I
was writing them, I was worried about the lines getting too long with
longer names.  It didn't turn out to be a problem though.



After doing a bit more reading and trying out some of the very useful 
suggestions people have made in this thread, I've decided to rework that 
section based on your example.


I was trying to use lambdas to solve this earlier but it's new territory 
for me and I couldn't figure out how to string them together as you've 
done above. The explanation is especially invaluable, thanks.

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


Re: [Tutor] function with multiple checks

2010-09-27 Thread Tim Miller

On 28/09/10 01:50, Brian Jones wrote:



On Mon, Sep 27, 2010 at 11:43 AM, Brian Jones mailto:bkjo...@gmail.com>> wrote:

How about this:

d = [digits, punctuation, ascii_uppercase, ascii_lowercase]
s = 'asdf1234A'
for c in d:
if not [x for x in s if x in c]:
print x, ' not in ', c

Just a quick hack, but you get the idea. It breaks when you want
different numbers of characters from the different lists in the password.

You can probably make other optimizations, but just to start, you
can get rid of 'len' and '== 0':

if not [c for c in password if c in ascii_lowercase]:
return False

will return False if there are no lowercase characters. An empty
list evaluates to False. With that in mind, you could just 'return
[c for c in password if c in ascii_lowercase]' if the calling code
is written to handle it.


I've rewritten that section of code using the lambda example from this 
thread since to me it just looks very clean. Thanks for the pointers on 
list comprehensions though, I've managed to go through and simplify 
quite a few bits of code based on that. I'm a little embarrased about 
all the len() now. :)

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


Re: [Tutor] console output that is same in Python 2 and 3

2010-09-28 Thread Tim Golden

On 27/09/2010 17:11, Thierry Tung wrote:

Hello tutor at python.org.

How can I write strings to the console in a way that will give the same result 
in Python 3 and Python 2?



I tried sys.stdout.write('hello') on Microsoft vista.

with python 3.1.2

sys.stdout.write('hello')

hello5




with python 2.7

sys.stdout.write('hello')

hello>>>

Why is the string length appended to the output with python 3.1.2?


Because in Py 3.x the .write method returns the length written.
The interpreter echoes the non-None return value of any function
to stdout. This won't happen when you run the program -- you won't
get a stream of numbers. To avoid it happening in the interpreter,
simply assign the return value:

  n = sys.stdout.write("hello")

In Python 2.x n will be None; in Python 3.x it will be 5

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


Re: [Tutor] I am looking for a book on Beginners who never programmed before or have no experience in programming

2010-09-29 Thread Tim Golden

On 29/09/2010 12:20, Calle's Pyt(h)onkonto wrote:

Or if you're like me (= Thinks reading a guide online is annoying
since you have to switch between your browser and IDLE all the time),
and would like to have a book that is easy to read and easy to
understand,


Merely from that perspective alone, you might be interested in
something like http://trypython.org which gives you the main Python
tutorial side by side with a console in a browser window. It
uses Silverlight (it's put together by Michael Foord, long associated
with promoting IronPython) which may be a stumbling block for
technical or philosophical reasons, but it's quite a neat tool.

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


[Tutor] 'module' object has no attribute (setting a class attribute)

2010-10-15 Thread Tim Johnson
My intention is to set a class attribute so that any number of
instantiations will have this value.

the module is tmpl.py. the class is tmpl.

if from the script I do this:
import tmpl
tmpl.tmpl.templatepath = kbLib.templatepath

I get error message: 
'module' object has no attribute 'templatepath'

I ended up getting completely befuddled, and then realized that the
problem was the right side of the assignment statement. I.E.  I had
a typo on the right and python was not informing me of *which*
module didn't have the attribute

I have two questions regarding this:
1)Am I using the correct method to set a class attribute?
2)Is there a system configuration that would cause the
AttributeError exception to print out the module name.
(In this cause it was 'kbLib' not 'tmpl'.

thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'module' object has no attribute (setting a class attribute)

2010-10-16 Thread Tim Johnson
* Dave Angel  [101016 03:45]:
>
> 1) The code is correct.  But it'd be much clearer if you followed  
> conventions and named your class with a leading uppercase.  So the  
> module would be called tmpl, and the class would be called Tmpl.
  I didn't know there was such a convention. Serves me right
 for being self-taught and self-employed 
> 2) For the general case, this error is about fetching attributes from  
> arbitrary objects.  Such an object is not always bound to a single name,  
> so it reports the object's type, rather than its name.  In this  
> particular case, a module has a unique name, so the message could have  
> been more helpful.  But it's not clear how the error display logic could  
> have readily known that.
  Ah! Understood.

> Two things could help you figure it for yourself more quickly.  a) On  
> the left side of such an assignment, this error can only refer to  
> attributes other than the last, since the last one is being created  
> here, and it wouldn't matter if it already existed.  b) You could  
> refactor the line, and see where the error message moves to.  Let's try  
> that:
  Good trick.
>
> a = kbLib.templatepath
> tmpl.Ttmpl.templatepath = a
>
> If the line that now gets the error had still been confusing, you could  
> try to refactor that in turn.
  thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Requesting restricted URL (further authentication requested)

2010-10-19 Thread Tim Johnson
I've written the following function which successfully gets an
authenticated URL:
def getRestrictedURL(authName,URL,log,pswd):
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(authName, URL,log,pswd)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
return opener.open(URL).read()
# But, alas, any links in content 'beneath' the URL
# require additional authentication. 
Any way around this?
Thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Requesting restricted URL (further authentication requested)

2010-10-19 Thread Tim Johnson
* Vince Spicer  [101019 12:25]:
> On Tue, Oct 19, 2010 at 1:56 PM, Tim Johnson  wrote:
> 
> 
> Tim,
> 
> Unless you are tied to the standard library I would recommend looking at
> 
> httplib2  http://code.google.com/p/httplib2/
> 
> This handles your authentication and connection much better then the
> standard urllib.
 
  Thanks Vince, I will give that a try. I'd like to keep things
  simpler than a global opener as per the other response. I'll let
  you all know how that goes.
  cheers
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-21 Thread Tim Golden

On 21/10/2010 13:42, Richard D. Moores wrote:

Traceback (most recent call last):
   File "c:\P26Working\test_urllib2_21a.py", line 148, in
 unchanged_count, higher_count, lower_count, secs =
sleep_seconds_control(unchanged_count, higher_count, lower_count,
secs)
TypeError: 'int' object is not iterable

I'm working on a script that keeps track of the USD ->  Japanese Yen
exchange rate. I'm experimenting with adding functionality that
changes the seconds to sleep between web scrapes, depending on
consecutive outputs of no change in the exchange rate. Please see the
code at


sleep_seconds_control is returning an integer.

You're trying to assign that integer to the four names:
unchanged_count, higher_count, lower_count, secs

Python therefore tries to iterate over the integer to
allocate one item to each of the four name.

And it can't. Because it's an integer

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


Re: [Tutor] 2.6 vs 2.7: package compatibility?

2010-10-25 Thread Tim Golden

On 25/10/2010 02:20, Alex Hall wrote:

Hi all,
I want to run a certain program from source. One dependency, Durus,
keeps giving me an error that no one can figure out. Someone said that
it will work if I use 2.7 instead of 2.6, but a lot of packages I have
installed work only on 2.6. I know I can install both, but here is the
question: all these packages that say they need 2.6... would they work
on 2.7?


I'm going to assume that you're running on Windows -- because
you usually are :) The answer, then, is that pure python modules
would need to be reinstalled into (or at least made visible to)
the newer Python version, but that extension modules would need
to be recompiled against the newer version -- possibly making use
of a precompiled binary.

Just to try, I've compiled Durus without issue on Python 2.6
from the tarball on their website:

  http://www.mems-exchange.org/software/durus/Durus-3.9.tar.gz

but it's not clear from your message above whether it's the
build which is the issue or some aspect of using it. Can
you clarify? I'm quite happy to post up an .msi or something
for you to use if that'll help.

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


Re: [Tutor] 2.6 vs 2.7: package compatibility?

2010-10-25 Thread Tim Golden

It tells me that persistent_dict does not exist, when it clearly does.
Another user had the exact same problem when running the source on
2.6, but he had no problem when running 2.7. If you had an msi to
install Durus for 2.6 specifically, it would be interesting to see if
the persistent_dict error went away...


http://timgolden.me.uk/python/downloads/Durus-3.9.win32-py2.6.msi

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


[Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
FYI: I am working in a linux environment with python 2.6.5
am an experienced web developer with 8 years in python, but
:) I have never tried this trick before:

I note that with the right .htaccess file, I can run a php file,
from a non-cgi location.
Example: On my machine, my wwwroot is at /home/http/, I have
/home/http/php/test/index.php and I have run index.php as
http://localhost/php/test/ (again with the correct .hataccess).

Is it possible to run a python script this way?

thanks
tj
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
* Evert Rol  [101030 13:23]:
> > FYI: I am working in a linux environment with python 2.6.5
> > am an experienced web developer with 8 years in python, but
> > :) I have never tried this trick before:
> > 
> > I note that with the right .htaccess file, I can run a php file,
> > from a non-cgi location.
> > Example: On my machine, my wwwroot is at /home/http/, I have
> > /home/http/php/test/index.php and I have run index.php as
> > http://localhost/php/test/ (again with the correct .hataccess).
> > 
> > Is it possible to run a python script this way?
> 
> I wouldn't think so, because index.php is not run as a cgi-script. 
> Whether Python will be interpreted correctly depends entirely on the 
> configuration of your webserver, in particular whether you're using/loading 
> the correct modules.
> But if configured correctly, yes, you can 'run' Python scripts. Mod_wsgi 
> arranges this for you, and this is generally how things like Django run.
 That's the keyword - 'mod_wsgi' 
> But the easiest way to find out is to try it out, right?
 I did, didn't work.  

> I also guess this question might be better answered on the forum
> corresponding to your webserver (Apache?), since it appears to
> deal more with the server setup than actually with Python.
  Understood. Thanks 

-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
* शंतनू  [101030 14:08]:
> Hi Tim, Reply inline.
 Sorry, I don't understand the preceding line. 
> On 31-Oct-2010, at 1:02 AM, Tim Johnson wrote:
> 
> > FYI: I am working in a linux environment with python 2.6.5 am an
> > experienced web developer with 8 years in python, but :) I have
> > never tried this trick before:
> > 
> > I note that with the right .htaccess file, I can run a php file,
> > from a non-cgi location.  Example: On my machine, my wwwroot is
> > at /home/http/, I have /home/http/php/test/index.php and I have
> > run index.php as http://localhost/php/test/ (again with the
> > correct .hataccess).
> > 
> > Is it possible to run a python script this way?
> 
> 
> Following link could be helpful.
> http://docs.python.org/library/cgi.html
> 
> From http://en.wikipedia.org/wiki/Common_Gateway_Interface
 
> From the Web server's point of view, certain locators, e.g.
> http://www.example.com/wiki.cgi, are defined as corresponding to a
> program to execute via CGI. When a request for the URL is
> received, the corresponding program is executed.
 
> Web servers often have a cgi-bin/ directory at the base of their
> directory tree to hold executable files called with CGI.

  I am familiar with the cgi interface, I've earned a living as a
  web programmer for 15 years and written several CGI APIs from
  scratch, as well as building my own python API on top of the
  standard python cgi module. However, I was approached by a client
  with a whole lot of python code that has grown like topsy without
  a formal framework like django or a CMS, for that matter. The
  client wanted to convert to what he called "clean URLs" not
  showing a cgi-bin path or a file extension. 

  I was well-advised by the previous respondant to post to an apache
  forum or mailing list and he also made reference to mod_wsgi,
  which likely will eventually be implemented on this project.

  For the time being, I did a little work-around:
  1)In my /etc/apache2/sites-available/default I placed the
  following entry:
  """
   ScriptAlias /reg/ /home/http/py/

AllowOverride all
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all

  """
  Note1: This is ubuntu 10.04, apache2 config directories differen
  with linux distros.  
  Note2: The scriptalias entry is *in addition to* the more
  standardized entry creating a cgi-bin path, which I also have, as
  apache2 supports multiple script aliases.

  2)I placed the following .htaccess file at /home/http/py/
"""
RewriteEngine on
RewriteCond $1 !^(index\.py|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.py/$1 [L,QSA]
"""
Disclaimer: I don't do a lot of apache configs and I don't know
beans about .htaccess protocols (always more to learn).
 - and I placed an executable called dispatch.py in the same directory.
Now I can point my browser at http://localhost/reg/dispatch
-with no cgi-bin and no file extension - and get a response.

 So I now can make my customer happy and hold the fort so to speak
 until I get up to speed on either django or mode_wsgi or both.

 Perhaps this info is of interest to others.
 thanks for the replies.
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Tim Johnson
* Tim Johnson  [101030 15:24]:
  I've taken this one step further:
.htaccess =>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ ./index.py/$1 [L,QSA]
now I get the response from http://localhost/reg/
cheers
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Displaying picture and Text

2010-11-04 Thread Tim Golden

On 04/11/2010 04:24, pa...@cruzio.com wrote:

Hi - I am running Python 2.6.6 on my HP netbook with Windows 7. The
default picture viewer is set to HP Photo Viewer.  I am working on a part
of my python program where a picture is supposed to display with a few
lines of text below it.  Ideally, I would like this to stay on the screen
for  a short  period of time (2 minutes?) but I am using raw_input() for
now.

I imported the Image library and when I run the program below, it brings
up a window (stdout or python?) with cursor flashing for a few seconds and
then the HP Photo Viewer comes up with the picture, I close this window
and then my text comes up in a python window.


The Image.show function in the PIL is simply a convenience for doing
a quick-and-dirty "What does this image look like?". It hands off to
the default image viewer -- as you discovered. It's not intended for
use in a production program which needs to control image size, placement
etc.

There probably *are* image viewers which you could control from the command
line to display what you want, but if you're going to need a solution
involving text and images, just use one of the existing GUI toolkits:
wxPython, PyQt or others (just search for "Python GUI") which let you
display text, images etc. with complete control.

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


[Tutor] Recommend a MVC framework

2010-11-14 Thread Tim Johnson
I've been web programming for 15 years now. 8 of it using python.

Lately I have been 'studying' PHP via the CodeIgnitor Framework.

Since python remains my first choice, but since I am also
impressed with the concept of CodeIgnitor, I would welcome
recommendations on a python MVC framework.

One restriction: must *not* need an application server, I.E. works
thru Apache and is adaptable to a shared server.
TIA
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommend a MVC framework

2010-11-14 Thread Tim Johnson
* Alan Gauld  [101114 13:12]:
> Not quite sure how you defione your terms there.
> But all of the above can be used with Apache.
  Hi Alan. See my reply to Evert where I refer to situations where I
  would have neither SSH nor root access.
  thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommend a MVC framework

2010-11-14 Thread Tim Johnson
* Evert Rol  [101114 12:12]:
> Django can run be run through mod_wsgi (or mod_python if you
> really want). And other web servers than Apache will also work. 
 
> Don't know what you mean with "shared server", but if you mean
> multiple accounts running their web apps through one Apache
> server, that can work (provided Apache is correctly configured).
  By "shared server", I mean a hosting situation where I would not
  be able to configure Apache. An example would be my own ISP's
  servers, which I avoid doing development work on *but* I just
  might have to.

> It'll also depend on your needs, but since you don't specify any,
> I'd suggest to look at Django first: http://www.djangoproject.com/
  Actually, :) I *have* looked at django and I've considered it to have the
  greatest appeal. In fact, for most of my deployment environments I
  have SSH and root access. Django would be my first choice in that
  case, however, I would like to consider other cases as well, thus
  my question regarding "shared server".

  From  
  
http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/ref=sr_1_2?s=books&ie=UTF8&qid=1289772638&sr=1-2
  Can you comment on the following exerpt of the third review, where
  the reviewer says:
  """
   
   one on deployment makes little mention of the fact that there's
   not really any good way to get Django running smoothly without
   root access to the server--something a lot of people do not
   have--and they actually expect their users to run TWO
   servers--one for Django and one for everything else, like image
   files.
  """
  Thank you for the response.
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommend a MVC framework

2010-11-14 Thread Tim Johnson
* Tim Johnson  [101114 11:45]:
> 
> One restriction: must *not* need an application server, I.E. works
> thru Apache and is adaptable to a shared server.
> 
thanks for all of who responded. I should clarify: I have been
considering django as a first choice for most of the deployment
environments I have access to, *but* am also looking for something
as a fall-back that can be installed without SSH or root access.
Looks like web2py may be the fall-back.
thanks again.

-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-21 Thread Tim Golden

Alan Gauld wrote:
Cut n paste of the path works, but you can also use tab to complete the 
file name which speeds things up considerably.


And you can drag a file in from explorer to a Console window
to get the full path pasted in automatically.

Even on DOS F3 repeated the last command but on XP (and indeed since 
Win95) you can use up/down arrow to step back through the command 
history. And you can set it to remember the history betweeen sessions 
(although I don't personally do that...) I think you can also search 
back through the history but I don't use that very often and I'm maybe 
confusing it with cygwin/bash!


No, you're right: if you press a few characters and then
F8 a matching line will be populated (can't remember if
it's the most recent or the oldest). If you press F7, a
selection list of all the lines entered pops up and you
can select from there.

And all the old tricks from the original DOS shells work:
F3 as you mentioned (altho' up/down arrows are easier for
this); F2 will copy up to a particular characters. Quite
limited but still they have their possibilities.


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


Re: [Tutor] Difference in minutes between two time stamps

2009-03-03 Thread Tim Michelsen

  import datetime

s = '09:35:23'
datetime.datetime.strptime(s, '%H:%M:%S')

datetime.datetime(1900, 1, 1, 9, 35, 23)

Can you figure out how to proceed from there?

In case she doesn't know:

import datetime as dt
start="09:35:23"
end="10:23:00"

start_dt = dt.datetime.strptime(start, '%H:%M:%S')

end_dt = dt.datetime.strptime(end, '%H:%M:%S')

diff.seconds/60

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


Re: [Tutor] Difference in minutes between two time stamps

2009-03-03 Thread Tim Michelsen



  import datetime

s = '09:35:23'
datetime.datetime.strptime(s, '%H:%M:%S')

datetime.datetime(1900, 1, 1, 9, 35, 23)

Can you figure out how to proceed from there?

In case she doesn't know:

import datetime as dt
start="09:35:23"
end="10:23:00"

start_dt = dt.datetime.strptime(start, '%H:%M:%S')

end_dt = dt.datetime.strptime(end, '%H:%M:%S')


I forgot to paste in between:
diff = (end_dt - start_dt)


diff.seconds/60


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


[Tutor] creating a list of all imported modules

2009-03-09 Thread Tim Michelsen

Hello,


how do I create a list of all modules imported by   my module/script?

I am looking for something like %who in Ipython.

Thanks for your help in advance.

Regards,
Timmie

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


Re: [Tutor] How to connect to an email server?

2009-03-16 Thread Tim Golden

Eduardo Vieira wrote:

Hello, I'm fairly new to programming and Python and am trying to
explore Python's email libraries. But I am having trouble making a
connection with an email server, I guess.
I'm running Windows XP, in a server environment. I have administrator
privileges to my machine (not the server machine) to install, delete
programs, for example. My email program (Outlook 2007) says that
Exchange Server is albertapdc.express.local
I would like to send emails using smtp in a script, but when I do
these lines, I get an error:

import smtplib
server = smtplib.SMTP('localhost') # if I replace 'localhost' with
'albertapdc.express.local' I get the same.

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
  File "C:\Python25\lib\smtplib.py", line 310, in connect
raise socket.error, msg
error: (10061, 'Connection refused')

The same error 'Connection refused' I get trying IMAP:
import imaplib
se = imaplib.IMAP4('albertapdc.express.local')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\imaplib.py", line 163, in __init__
self.open(host, port)
  File "C:\Python25\lib\imaplib.py", line 230, in open
self.sock.connect((host, port))
  File "", line 1, in connect
error: (10061, 'Connection refused')

What should I do? And how can I know I can use smtp or IMAP?



SMTP has to be enabled specifically on the Exchange Server:
it usually uses its own built-in protocols. It looks
as though your Exchange isn't running it. Either switch it
on (or ask your admins to do so) or look at using MAPI
or CDO instead.

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


Re: [Tutor] (no subject)

2009-03-17 Thread Tim Golden

Michael Connors wrote:

So the extent of your effort is "Would anyone know how to Ctrl+c".
That deserves an award.



I think you meant ctrl-v, but good point, nonetheless :)

(Took me a moment, because I thought you were referring
to a KeyboardInterrupt-type ctrl-c!)

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


Re: [Tutor] Trouble parsing email from Outlook

2009-03-20 Thread Tim Golden

Eduardo Vieira wrote:

Hello, list! I hope it's not too much out of place to ask this
question in the Tutor list.
I'm trying to process some information from email messages that goes
in a folder called: "SysAdmin". I could reproduce the recipe from
Python Programming on Win32 sucessfully to read the subject line of
the inbox, but not from a different folder:


It can be a bit confusing working out even what to search
for, and there are a few things which are similar but
subtly different. Ignoring more esoteric possibilities,
there are three main ways to do automatic things with
Outlook / Exchange emails, all of which are feasible from
Python + pywin32/ctypes/comtypes.

1) COM -> CDO ("MAPI.Session") -- that's what you're doing.
Altho' technically this is using Exchange rather than Outlook,
you basically need Outlook installed for this to work.

2) COM -> Outlook ("Outlook.Application") -- this is very similar
to CDO but gives you a few things which are tied to Outlook
rather than to the Exchange server.

3) COM -> MAPI -- this is a slightly lower-level Win32 API set
which is exposed in pywin32 through the slightly confusing
set of modules under win32comext/mapi

Of course it's all very confusing because the CDO CLSID
above uses the word "MAPI" (as it presumably calls MAPI
functions under the covers) while there's another thing
called CDONT which is/was a cut-down version of CDO and
which you still come across from time to time. 




So far my code is this:
import win32com.client
ses = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")


OK, now you've confused yourself. You don't need to use
*both* Outlook automation *and* CDO automation. Just
pick one. Let's go with CDO since that's effectively
what you've done.


ses.Logon("Default")
print ses.Inbox.Messages.Item(1).Subject


Right, because the Inbox is a well-known special case,
you get an easy reference to it from the CDO session
itself. To find other folders, you either have to
walk the tree of folders if you know where to look,
or to iterate over them if you just know it's there
somewhere but can't guarantee where.

The topmost things in a CDO Session is one or more
InfoStores. You can't iterate over them directly;
you have to loop over their count. Note that they
are counted from 1 upwards, while the Python loop
is 0-based:


for i in range (len (ses.InfoStores)):
 info_store = ses.InfoStores[i+1]
 print info_store.Name



If you already know the name of the one you want,
eg "Mailbox - Tim Golden", you can select that one:


mailbox = ses.InfoStores["Mailbox - Tim Golden"]


The infostore has a RootFolder which is a CDO Folder
object and once you've got that, you can just walk the
tree of folders. The key collections you'll be interested
in are the Folders and Messages. They can both be iterated
the same way, and the function below provides a Pythonish
wrapper:


def cdo_iter (cdo_collection):
 item = cdo_collection.GetFirst ()
 while item:
   yield item
   item = cdo_collection.GetNext ()



Each Folder may have a Folders attribute and a Messages
attribute. To walk a tree or subtree, you can do this,
making use of the function above:


def cdo_walk (folder): ## can be the RootFolder or a specific folder
 try:
   folders = cdo_iter (folder.Folders)
 except AttributeError:
   folders = []
 try:
   items = cdo_iter (folder.Messages)
 except AttributeError:
   items = []

 yield folder, folders, items

 for subfolder in folders:
   for r in cdo_walk (subfolder):
 yield r



Note that, because we're using generators, the sublists
of folders and items are generated lazily. If, as in the
case we're getting to, you don't need to look at messages
until you've got to the folder you want, then you just don't
iterate over the items iterable.

Putting it together, you can find a folder called "SysAdmin"
from a CDO session like this:


import os, sys
import win32com.client

def cdo_iter (cdo_collection):
 item = cdo_collection.GetFirst ()
 while item:
   yield item
   item = cdo_collection.GetNext ()

def cdo_walk (folder):
 try:
   folders = cdo_iter (folder.Folders)
 except AttributeError:
   folders = []
 try:
   items = cdo_iter (folder.Messages)
 except AttributeError:
   items = []

 yield folder, folders, items

 for subfolder in folders:
   for r in cdo_walk (subfolder):
 yield r

class x_found (Exception):
 pass
 
if __name__ == '__main__':

 session = win32com.client.gencache.EnsureDispatch ("MAPI.Session")
 session.Logon ()

 try:
   for i in range (session.InfoStores.Count):
 info_store = session.InfoStores[i+1]
 #
 # Ignore Public Folders which is very big
 #
 if info_store.Name == "Public Folders": continue
 print "Se

Re: [Tutor] Trouble parsing email from Outlook

2009-03-20 Thread Tim Golden

Eduardo Vieira wrote:

On Fri, Mar 20, 2009 at 2:29 PM, Eduardo Vieira  wrote:

On Fri, Mar 20, 2009 at 9:04 AM, Tim Golden  wrote:

Eduardo Vieira wrote:

Thank you very much, Tim for the thorough explanation. Much more than
I could expect. It will be specially useful for me a newbie python
amateur programmer. I will try your guidance as soon as possible
today, and see my progress.

That's ok; might be worth posting back to the list to say
whether it worked or not. All the posts go into the archive
so people looking in the future for the same kind of solution
might be interested to know if my suggestion worked or
whether there were any other obstacles.

TJG


Thanks again. I tried the code, trying to reformat the spaces and came
up with this code: http://paste.lisp.org/display/77353
I'm not sure if I indented correctly, and the result it gave me was:
Searching Archive Folders
Searching Mailbox - Eduardo Silva

I don't understand the part "for folder, folders, items in cdo_walk
(info_store.RootFolder):"
RootFolder is IPM_SUBTREE if I check the Name value


I worked! sorry, I had to just align "raise x_found" with the "for"
statement, thank you very much!


Glad you got it working. The "for folder, folders, items in..." bit
is looping over each folder (with its subfolders and subitems) in
turn. cdo_walk is a generator -- a function-type mechanism which keeps
returning values, rather than just returning once. Because of that,
you can keep looping over it as it walks down the tree of folders,
recursively in this case altho' other approaches are possible.

FWIW, RootFolder is nearly always IPM_SUBTREE; its name doesn't
really matter: it's just a place to start looking.


Sorry about the formatting. With something more than a few lines
long I usually stick it in pastebin or wherever, but I was moving
too quickly when I wrote that this morning!

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


Re: [Tutor] Opening a cmd.exe

2009-03-22 Thread Tim Golden

Alan Gauld wrote:

"Sigga Sig"  wrote

I am writing a code that is supoesed to act as routers and i need to 
open a
different cmd window for each one of them with it's name and so on. I 
do not

know how to implement in mi Python cod a sentece that opens such a cmd.

I know how to open a cmd.exe bud not with specific attributes that are
needed.


Neither do I. You can use shortcuts and set the name of the shortcut
and that will show up on the window title.

There are probably ways to do it using the Win32 API too, but you would
need to get the Window Handle using FindWindow(). And I'm still not sure
which API call would set the title. I'd probably just create a set of
shortfcuts on a folder and execute those.


You can do it with the win32console functions from pywin32:

 win32console.SetConsoleTitle (u"blahblah")

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


Re: [Tutor] Opening a cmd.exe

2009-03-22 Thread Tim Golden

Tim Golden wrote:

Alan Gauld wrote:

"Sigga Sig"  wrote

I am writing a code that is supoesed to act as routers and i need to 
open a
different cmd window for each one of them with it's name and so on. I 
do not

know how to implement in mi Python cod a sentece that opens such a cmd.

I know how to open a cmd.exe bud not with specific attributes that are
needed.


Neither do I. You can use shortcuts and set the name of the shortcut
and that will show up on the window title.

There are probably ways to do it using the Win32 API too, but you would
need to get the Window Handle using FindWindow(). And I'm still not sure
which API call would set the title. I'd probably just create a set of
shortfcuts on a folder and execute those.


You can do it with the win32console functions from pywin32:

 win32console.SetConsoleTitle (u"blahblah")


Ah, sorry, missed the point that you're not actually running
Python code in these windows. Yes, as Alan says, you'd have
to use FindWindow to identify your windows by their existing
titles and then use SetWindowText (or whatever) to set the
title. You probably are better off using shortcuts...

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


[Tutor] Python Logo

2009-03-24 Thread Tim Johnson
Hi Folks:
My company is setting up a new website, like to have a python logo
on it. Can anyone recommed a logo that would be legal for us to
use?
Thanks
Tim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Logo

2009-03-24 Thread Tim Johnson
On Tuesday 24 March 2009, Kent Johnson wrote:
> On Tue, Mar 24, 2009 at 4:45 PM, Tim Johnson  wrote:
> > Hi Folks:
> > My company is setting up a new website, like to have a python logo
> > on it. Can anyone recommed a logo that would be legal for us to
> > use?
>
> http://www.python.org/community/logos/
 thanks a lot!
cheers
tim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Logo

2009-03-25 Thread Tim Johnson
On Wednesday 25 March 2009, you wrote:
> On Tue, Mar 24, 2009 at 6:26 PM,   wrote:
> > http://img99.imageshack.us/img99/5422/webpy.png
>
> That is the logo for web.py (a Python web framework), not for the
> Python language itself.
> http://luke.jottit.com/webpy_logo
 All the same, I was glad to see it. I never knew about webpy, and now
 I do. Have found django and turbogears way too big for me. Now I will
 check out webpy.
thanks to all
tim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trapping warnings from MySQLdb

2009-04-13 Thread Tim Johnson
FYI: Using python 2.5 with the MySQLdb module.
I need to be able to raise an exeception on a MySQL warning.

I have used my own class for years that wraps the MySQLdb module,
but never did build in a feature that would let me 'tell' my class
instances to raise an except for a warning:
Example:
I'm converting csv data into Mysql commands and executing them via
a cursor object. I instantiate a cursor that returns a tuple as:
self._rdb = self._conn.cursor() ## where self._conn is an object of the 
  
 ## MySQdb.connect class
# And I instantiate a cursor that returns a dictionary with
self._rdb = self._conn.cursor(MySQLdb.cursors.DictCursor)

Is there a way to create a cursor that _will_ raise an exeception on a 
warning?

I have looked at the cursor.py module and was not able to find such
a feature. Any and all ideas would be appreciated. This will be very
useful to us.
thanks
tim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trapping warnings from MySQLdb

2009-04-13 Thread Tim Johnson
On Monday 13 April 2009, Kent Johnson wrote:
<>
> >From a quick look at MySQLdb-1.2.2, it seems to be using the python
>
> std lib module warnings to report warnings.
> http://docs.python.org/library/warnings.html
>
> >From the warnings docs, it seems like warnings.simplefilter() is what
>
> you are looking for. Try this, perhaps in your wrapper module:
> import warnings
> import MySQLdb
> warnings.simplefilter("error", MySQLdb.Warning)
>
> I think that will tell the warnings module to treat MySQLdb.Warning as an
 Yes! That is what I was looking for.
 Here's the code (in my wrapper class)
def rcmd(self,s,test=0,trapwarnings=0):
self._connect_method = 'row'
if test:
print("SQL = %s" % (s))  #DEBUG st
if trapwarnings:
warnings.simplefilter("error", MySQLdb.Warning)
return self._rdb.execute(s) 

## and the interface:
try:
db.rcmd(cmd,0,1)
except _mysql_exceptions.Warning,e:
## give user ad hoc analysis of the offending cmd
handle_warnings_here()

## Thanks a lot Ken
tim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Webpy vs Django

2009-04-20 Thread Tim Michelsen

I can recommend you web2py:
http://www.web2py.com/

It has been designed for didactical needs and has a low learning curve.

Look at the manual extarct for an idea:
Free manual chapters - 
http://mdp.cti.depaul.edu/examples/static/web2py_manual_cut.pdf


or check the docs:
http://www.web2py.com/examples/default/docs

All the best,
Timmie

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


Re: [Tutor] is it possible to traverse two lists simulatenously using python

2009-04-30 Thread Tim Johnson
On Wednesday 29 April 2009, mobiledream...@gmail.com wrote:
> Python
> for i,j in topgirls, richgirls:
> print i,j
>
>
> Cheetah
> #for $i,$j in $topgirls, $richgirls$i, $j
> #end for
> This doesnt work

Hello -
Please do not send email to the python ML via "undisclosed recipients".
It's really poor form and it screws up my mail filters.
thanks
-
Tim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running subProcesses in parallel for mixed external Windows.exe and Python functions on specified CPUs.

2009-05-01 Thread Tim Golden

Ian Campbell wrote:
Running subProcesses in parallel for mixed external Windows.exe and 
Python functions on specified CPUs.


How  does a newbie start to make this work?


[... snip most stuff ...]

p11 = subprocess.Popen("C:\myDdeServer.exe ") # loads 
DDE Serverp12 = subprocess.Popen("c:\ddeClicks.ahk 
group p21 = subprocess.Popen("C:\showRawData.xlsm 
   p22 = subprocess.Popen("c:\xlsClicks.ahk ")   # send 
subprocess.Popen("pw5.exe c:\legacyScript.was") # loads legacy 
   p32 = subprocess.Popen("c:\wasClicks.ahk ")# 



You're going to have to use raw strings or
reverse the backslashes on those paths:

r"C:\myDdeServer.exe "

or

"C:/myDdeServer.exe "



Haven't looked at the rest of the code yet, not least because it comes out
a bit messy on my email client.

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


[Tutor] how to reference a function itself when accessing its private functions?

2009-05-04 Thread Tim Michelsen

Dear Tutors and fellow pythonistas,
I would like to get access to the private methods of my function.

For instance:
Who can I reference the docstring of a function within the function itself?

Please have a look at the code below and assist me.

Thanks and regards,
Timmie

 CODE ###

s = 'hello'

def show(str):
"""prints str"""
print str

return str



def show2(str):
"""prints str"""
print str
d = self.__doc__
print d

>>> show2(s)
hello
---
NameError Traceback (most recent call last)

 in ()

 in show2(str)

NameError: global name 'self' is not defined

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


Re: [Tutor] how to reference a function itself when accessing its private functions?

2009-05-05 Thread Tim Michelsen

Thanks a lot!

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


Re: [Tutor] Need help with registry access

2009-05-08 Thread Tim Golden

ALAN GAULD wrote:
The _winreg module is part of the standard library and provides 
functions for accessing the Windows registry.


There's some (incomplete) help here, but as Alan said,
you need to learn Python to some extent before trying
to do this.

 http://timgolden.me.uk/python-on-windows/programming-areas/registry.html

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


Re: [Tutor] performance loss -- profiling

2009-05-19 Thread Tim Golden

Kent Johnson wrote:

The Python profiler is not hard to run. Interpreting the results is
more difficult :-) See the docs to get started:
http://docs.python.org/library/profile.html


Also, it's quite useful to run it as a module:

 python -mcProfile 

You have a certain amount of configurability via
the -s param.

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


Re: [Tutor] Getting file properties on winodws

2009-05-20 Thread Tim Golden

vishwajeet singh wrote:

Hi,

I am trying to read properties of file on windows like there is a property
call Keywords on file; I am to read this property independent of file type.


There's an unpolished (indeed, unfinished) example here:

 http://timgolden.me.uk/python/win32_how_do_i/get-document-summary-info.html

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


Re: [Tutor] Getting file properties on winodws

2009-05-21 Thread Tim Golden

[Rearranging for reading order]

[vishwajeet singh wrote]
I am trying to read properties of file on windows like there is a
property
call Keywords on file; I am to read this property independent of file
type.

[Tim Golden  wrote:]
There's an unpolished (indeed, unfinished) example here:
http://timgolden.me.uk/python/win32_how_do_i/get-document-summary-info.html

[vishwajeet singh wrote:]

It does not seems to be working for jpg and in general with image files any
pointers on that.


It would probably help if you specified what "does not seem[s] to be
working" meant. But I assume that you mean: if you add a Title into
the Summary on a JPEG then it doesn't get picked up by the script.
What's happening here (I think) is that for media types -- images,
movies, etc. -- the [Summary] property sheet is overridden, probably
by Windows Media Player which will use the properties embedded in
the JPEG (EXIF) or WMV. This isn't Structured Storage as such and
so isn't extracted by the script I showed.

If I get a chance, I'll look into this a bit further.

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


Re: [Tutor] Getting file properties on winodws

2009-05-21 Thread Tim Golden

Tim Golden wrote:

It would probably help if you specified what "does not seem[s] to be
working" meant. But I assume that you mean: if you add a Title into
the Summary on a JPEG then it doesn't get picked up by the script.
What's happening here (I think) is that for media types -- images,
movies, etc. -- the [Summary] property sheet is overridden, probably
by Windows Media Player which will use the properties embedded in
the JPEG (EXIF) or WMV. This isn't Structured Storage as such and
so isn't extracted by the script I showed.

If I get a chance, I'll look into this a bit further.


In principle, it ought to be possible to do this by
querying the IID_IPropertySetStorage on the corresponding
IID_IShellItem. But it doesn't look as though the pywin32
com stuff quite supports that yet. Could be wrong. Might
be worth trying with comtypes; I'll have a look if I can.

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


Re: [Tutor] Getting file properties on winodws

2009-05-21 Thread Tim Golden

Tim Golden wrote:

Tim Golden wrote:

It would probably help if you specified what "does not seem[s] to be
working" meant. But I assume that you mean: if you add a Title into
the Summary on a JPEG then it doesn't get picked up by the script.
What's happening here (I think) is that for media types -- images,
movies, etc. -- the [Summary] property sheet is overridden, probably
by Windows Media Player which will use the properties embedded in
the JPEG (EXIF) or WMV. This isn't Structured Storage as such and
so isn't extracted by the script I showed.

If I get a chance, I'll look into this a bit further.


In principle, it ought to be possible to do this by
querying the IID_IPropertySetStorage on the corresponding
IID_IShellItem. But it doesn't look as though the pywin32
com stuff quite supports that yet. Could be wrong. Might
be worth trying with comtypes; I'll have a look if I can.


OK, more useful version now up; reads JPEGs, WMVs, etc.
Still more work to be done, reverse-engineering the FMTID
and property names, but at least it takes you further without
too much extra work.

 http://timgolden.me.uk/python/win32_how_do_i/get-document-summary-info.html

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


Re: [Tutor] file enigma

2009-06-11 Thread Tim Golden

spir wrote:

Hello,

text = file(filename).read()

(or: open(filename).read())

How do you close() the file? ;-)


Well, in any version of Python, you can do this:


f = open (filename)
text = f.read ()
f.close ()


or, slightly more robsustly:


f = open (filename)
try:
 text = f.read ()
finally:
 f.close ()


But in Python 2.5+ that can be spelt:


with open (filename) as f:
 text = f.read ()



As it happens, in CPython at the moment, the file object will
be closed when all references are released -- which would be
at the end of the line in your example. I don't know whether
that's guaranteed by the implementation, or merely the case
at present. It's certainly *not* the case in other implementations,
such as IronPython & Jython which don't use the same kind of
refcounting.

FWIW, in non-critical code I often use the style you illustrate
above: text = open (filename).read (). But in production code,
I usually use the with statement.


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


Re: [Tutor] file enigma

2009-06-11 Thread Tim Golden

spir wrote:

Thank you, Tim, this really answers my question.


Glad to be of help :)



* I intended to write a helper func "filetext(filename)" to 
open/read/close/return (or equivalent using the with idiom).


This is one of those tricky things in Python: when the "raw" code
is possibly one line long, and at most two (for Python 2.5+), it's
only marginally worth creating a function for it unless you've got
some substantial extra functionality. Ultimately it's a matter for
personal taste / project needs.

TJG

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


Re: [Tutor] how to manage an encrypted file?

2009-06-20 Thread Tim Golden

Robert Lummis wrote:

Could you recommend a module or methods I should use to manage an
encrypted text file? I want to store passwords and associated contact
information in a file and feel confident that if the file is stolen
the information couldn't be read.



If you're on Windows, just encrypt the file under Explorer.

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


Re: [Tutor] Floor and modulus for complex arguments

2009-07-03 Thread Tim Peters
[Angus Rodgers]
> I'm a little confused by: (i) the definition of the modulus and
> floor division functions for complex arguments;

Perhaps you're confused by the current definitions simply because they
don't make good sense.


> (ii) the fact that these functions for complex arguments are
> now "deprecated";

And they're deprecated /because/ they never made good sense.


> and (iii) the fact that the math.floor() function is not defined
> at all for a complex argument.

The math module consists mostly of Python wrappers around the C
functions defined by the C standard in C's math.h.  C doesn't define
floor() for complex numbers, so neither does Python's math.floor().


> If I were thinking about this from scratch (in the context of
> mathematics, rather than any particular programming language),
> I /think/ I would be naturally inclined to define:
>
>  floor(x + yj) = floor(x) + floor(y)j     for all real x, y
>
>  z % w = z - floor(z / w) * w    for all complex z, w (!= 0)
>
> These seem like they would be mathematically useful definitions
> (e.g. in algebraic number theory, where one has to find the
> "nearest" Gaussian integer multiple of one Gaussian integer to
> another - I forget the details, but it has something to do with
> norms and Euclidean domains), and I don't understand why Python
> doesn't do it this way, rather than first defining it a different
> way (whose mathematical usefulness is not immediately apparent
> to me) and then "deprecating" the whole thing!  It seems like
> a wasted opportunity - but am I missing something?

My guess:  that in the absence of a /compelling/ reason to add
something, it's best to leave it out.  That you vaguely believe there
might be "a reason" for defining complex floor in a particular
more-or-less arbitrary way, but "forget the details" as to why /maybe/
that /might/ be useful ... well, that's not exactly compelling ;-)


> Has there been heated debate about this (e.g. in the context
> of Python 3, where the change to the division operator has
> apparently already provoked heated debate)?

Few people care about complex numbers in Python, and so no, there was
no heated debate about this.


> Also, by the way, is there some obvious reason for Python's use
> of the notation x + yj, rather than the more standard (except
> perhaps among electrical engineers) x + yi?

When complex numbers were first added to Python, there /was/ heated
debate about how to spell complex literals.  Guido got weary of the
debate, but didn't see a compelling reason to prefer "i" or "j", so
left it to a vote on comp.lang.python.  "j" got more votes.

See?  There's nothing "complex" about any of this after all ;-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Floor and modulus for complex arguments

2009-07-03 Thread Tim Peters
[Angus Rodgers]
> ...
> If I started to agitate for changes to a marginal and little-used
> feature of the language within days of starting to learn it, might
> I not quickly earn a reputation as a crank?  8-P

If that's your /goal/, it would be easier to rant about some imagined
flaw in the ring of algebraic integers, and insist Guido was the head
of a worldwide conspiracy to cover it up.  James Harris doesn't have a
copyright on inane babbling, after all ;-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is my style OK in this elementary student exercise?

2009-07-05 Thread Tim Peters
[Angus Rogers, suffering eval-angst]
> ...
> On the other hand, so long as I AM only executing the function
> myself, I am no more at risk than I already am every single time
> I type a command into a Python interpreter, of any description.
> (A somewhat Existentialist thought, perhaps!  Virtual suicide
> is always a possibility.) >->
>
> Does that seem reasonable?  You've made me clearly aware of a
> risk that I was only vaguely aware of before (I ruminated only
> briefly as to whether any harm might come from entering general
> Python expressions, but my main feeling about this facility was
> that it would probably be useful - in some "future exercise"),
> but isn't there a role for functions that one can use oneself,
> but never ever distribute to the "general public"?

Certainly!  I use eval() and input() all the time in my private code
(but never in released code), and you're never going to screw yourself
"by accident" doing so.  Especially if you have an interest in writing
mathematical code, it's a tremendous convenience for prompted input to
support arbitrary computation.


> If so, are the precautions I have suggested above sufficient?

In private code, any precautions are probably just a waste of time.
You really don't, for example, need to remind /yourself/ not to enter
a convoluted expression that emails your credit card info to a hacker
site in Nigeria.  Or if you do need to remind yourself not to do
things like that, you probably shouldn't be using a computer to begin
with ;-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Popen problem with a pipe sign "|"

2009-07-06 Thread Tim Golden

hyou wrote:

Thanks for the answer! I found the problem was because I put the 2nd
argument to Popen with Shell = true. Though I'm not sure why it doesn't work
with Shell = true while the same setting works for other commands.



There's a long-outstanding bug when shell=True is passed to
subprocess.Popen on Windows such that the rest of the line
isn't quoted correctly (ie doesn't cope with special chars
such as space, pipe and ampersand).

In general, you almost never need to pass shell=True on
Windows. The latest docs have just been updated with a
patch I wrote to that effect, but it basically says:
don't use shell=True unless you know you need to.

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


Re: [Tutor] renaming files within a directory

2009-07-26 Thread Tim Golden

davidwil...@safe-mail.net wrote:

Hello,
I have a directory containing svg/Flag_of_United_States.svg etc...


Flag_of_the_Seychelles.svg
Flag_of_the_Solomon_Islands.svg
Flag_of_the_United_Arab_Emirates.svg
Flag_of_the_United_Kingdom.svg
Flag_of_the_United_States.svg
Flag_of_the_Vatican_City.svg


Also I have a CSV file like

"us", "United States"
"es", "Spain"



How can I rename the svg files so that they become:

flag-us.svg
flag-es.svg



This is one of those ones where it helps if you have
a go first and tell us how far you got, or where
the problem lies. Otherwise you're likely to get
a lot of sarcastically helpful replies along the lines
of:

move Flag_of_the_Seychelles.svg flag-sc.svg


To get you started if you're nowhere at the moment,
you want to create a dictionary from your csv which maps 
the long name to the short name so that can then

parse the file name to find the long name, use the
dictionary to find the short name, and then issue
a rename command to the new name.

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


Re: [Tutor] renaming files within a directory

2009-07-26 Thread Tim Golden

davidwil...@safe-mail.net wrote:

Here is what I have so far, but I get stuck on the mapping of the filename with 
the csv file.


import os
files = [file for file in os.listdir(os.getcwd()) if file.endswith('svg')]
files

['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 
'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 
'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 
'Flag_of_Armenia.svg', 'Flag_of_Australia.svg']


import csv
reader = csv.reader(open("country.csv"))
for row in reader:
... print row   


['"km";"Comoros"']
['"dj";"Djibouti"']
['"er";"Eritrea"']
['"et";"Ethiopia"']


Here is where I am at.
Not sure how to map the two.



OK. Good stuff so far. You may not actually need
that auxiliary list of files, but no problem really.

Are you familiar with a dictionary in Python? It maps
a key to a value. Here, you want the long names to
be the keys and the short names to be values. If you
were putting them together by hand (as a constant)
it would look something like this:

countries = {
 "Comoros" : "km",
 "Ethiopia" : "et",
}

and you could look up like this:

ethiopia_tld = countries['Ethiopia']

So what you have to do is to use one of the dictionary
constructors (hint: help (dict)) to create a dictionary
out of the list of lists which you csv reader produced.
You'll need to swap the elements round as the csv has
the code first, but you want the country first.

Does that take you any further forward?

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


Re: [Tutor] renaming files within a directory

2009-07-26 Thread Tim Golden

davidwil...@safe-mail.net wrote:

OK I am lost ;(

I changed the code to:


reader = csv.reader(open("countries.csv"),  delimiter=";")
for row in reader:
... print row 
... 
['bi', 'Burundi']

['km', 'Comoros']
['dj', 'Djibouti']
['er', 'Eritrea']

...

Now each row is a list with two items each.

But when I do this:


dic = []
for row in reader:

... newdic.append({row[0]: row[1]})
... 

dic

[]

I get an empty dictionary


Well, you actually get an empty list :)
To instantiate an empty dictionary, you use curly brackets:

d = {}

To add something to a dictionary, you use:

d[] = 

Try something like this:


import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = {} # note the curly brackets
for row in reader:
  code, name = row # handy Python tuple unpacking
  countries[name] = code




Once you're used to the idea, you can get reasonably slick
with dictionary initialisers and generator expressions:

import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = dict ((row[1], row[0]) for row in reader)

And once you're really confident (and if you're a
fan of one-liners) you can get away with this:

import csv
countries = dict (
  (name, code) for \
(code, name) in \
csv.reader (open ("countries.csv"), delimiter=";")
)


BTW, I tend to open csv files with "rb" as it seems to
avoid line-ending issues with the csv module. YMMV.

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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Tim Golden

davidwil...@safe-mail.net wrote:

Here is what I have so far:

import os
import csv

countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])


You don't really need the set () here, as I doubt your operating
system allows two files of the same name in the same directory.
Also, you can use os.listdir (".") if you want.


print len(files)

for file in files:
file = file.strip('.svg')
print file
#if countries.has_key(file):
#   print file



[... snip ...]



The problem is that for example the file Flag_of_the_United_States.svg 
when I use the strip('.svg') it is returned as Flag_of_the_United_State


Yes, this is a common gotcha when using strip. Check out the
docs of strip:

"""
Help on built-in function strip:

strip(...)
   S.strip([chars]) -> string or unicode

   Return a copy of the string S with leading and trailing
   whitespace removed.
   If chars is given and not None, remove characters in chars instead.
   If chars is unicode, S will be converted to unicode before stripping
"""

The parameter to strip -- if given -- is a string of chars,
any and all of which are stripped from the ends of the
string. It is not a *string* which is stripped in its
entirety; it is a list of characters. So here, Python is
stripping any of ".", "s", "v", "g" from the ends of your
string.

I suggest you put together a little function, eg:

def rstrip_string (look_in, look_for):
 if look_in.endswith (look_for):
   return look_in[:-len (look_for)]
 else:
   return look_in

which you can then call:

files = [rstrip_string (f, ".svg") for f in files]



Also, How do I remove 'Flag_of', 'Flag_of_the_' 


Same sort of idea.



I guess after this I can compare the value with the key and map the tld?

Or is it better to use regex and then search from the list of countries? But 
how???


regex would be possible here, but probably overkill.
You're very nearly there. Assuming the format of the
strings is consistently simple, you can take shortcuts
as above. If it's possible that one file has "flag_of"
while another has "flag-of" and another "flags-of" then
you might need to get fancier.


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


[Tutor] regex problem with colon

2009-08-06 Thread Tim Johnson
using python 2.5.
I'm having a problem with including a colon as part of a substring
bounded by whitespace or beginning of line.
Here's an example:
p = re.compile(r'\bcc:\b',re.IGNORECASE)
>>> res = p.findall('malicious cc: here CC: there')
>>> res
[]
## Darn! I'd hope that the 'cc:' and 'CC:' substrings would be
found. So how to compose the expression correctly?
TIA
-- 
Tim 
t...@johnsons-web.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex problem with colon

2009-08-06 Thread Tim Johnson
* Kent Johnson  [090806 18:31]:
> On Thu, Aug 6, 2009 at 8:47 PM, Tim Johnson wrote:
> > using python 2.5.
> > I'm having a problem with including a colon as part of a substring
> > bounded by whitespace or beginning of line.
> > Here's an example:
> > p = re.compile(r'\bcc:\b',re.IGNORECASE)
> >>>> res = p.findall('malicious cc: here CC: there')
> >>>> res
> > []
> > ## Darn! I'd hope that the 'cc:' and 'CC:' substrings would be
> > found. So how to compose the expression correctly?
> 
> The problem is that : is not a "word" character, so there is no word
> boundary between : and space for \b to match. How about this:
> In [9]: p = re.compile(r'\bcc:',re.IGNORECASE)
 
  Yes. You nailed it Kent.
  I had grokked the logic but not entirely the syntax.
  I'm looking thru docs now. Just curious .. is there a flag that
  enables adding a ':' to the internal list of "word" characters?

> In [10]: p.findall('malicious cc: here CC: there')
> Out[10]: ['cc:', 'CC:']

thanks again.
-- 
Tim 
t...@johnsons-web.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Overriding MySQLdb.cursors.DictCursor.execute()

2009-08-07 Thread Tim Johnson
Hello:
I am currently using python 2.5 and do a lot of database programming
with MySQLdb.
I have developed a wrapper class that uses two cursors:
1)a MySQLdb.cursors.DictCursor object
2)a MySQLdb.cursors.Cursor object
#1 returning a dictionary from query results, #2 returning a tuple
from query results - :) but you all know that.

I need to tighten up control over queries since I am concerned about
malicious injections.
It would seem to me that overriding the execute() methods for both
objects would entail the least amount of code maintenance and
modification. I've used python for a long time, but not done much
with object inheritance. 
The following code:
class mysql_row_cursor(MySQLdb.cursors.DictCursor):
def __init__(self):
pass
# results in the following error message:
class mysql_row_cursor(MySQLdb.cursors.DictCursor):
AttributeError: 'module' object has no attribute 'cursors'
# say what? MySQLdb has been imported...
I would welcome both comments on why I am getting this error
message and whether my original thinking is correct.
thanks -- forever and always a noob --
-- 
Tim 
t...@johnsons-web.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Overriding MySQLdb.cursors.DictCursor.execute()

2009-08-08 Thread Tim Johnson
* Kent Johnson  [090808 05:06]:
> On Fri, Aug 7, 2009 at 10:18 PM, Tim Johnson wrote:
> 
> If you use the two argument form of cursor.execute - passing the
> parameter values in a sequence, rather than substituting them yourself
> - then you have to worry about injection attacks. The DB-API module
> should take care of any required escaping.
 
   Oh! Good to hear. Never use the two argument form.
> 
> You have to explicitly import subpackages. Try
> import MySQLdb.cursors
  Understood. And now probably now not necessary.
  thanks
-- 
Tim 
t...@johnsons-web.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pack/Unpack hacking

2009-09-06 Thread Tim Golden

Hope the people in the US are having a nice Labor Day! I am looking for
the source code
for the pack/unpack functions found in the struct package. As of this
email, I have tried a
strings on the struct.pyc file. The inspection of the pyc file was hoping
that I could find a
stub to the source. I also looked directly at struct.py, with no success.
Finally, I also tried
downloading the source and grepping through the files, which didn't prove
all that useful.
Does anybody have any ideas on how I can find the source without having to
go through
the entire source tree file by file?



http://svn.python.org/view/python/trunk/Modules/_struct.c?view=markup

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


Re: [Tutor] Invitation to connect on LinkedIn

2009-09-15 Thread Tim Golden

Kent Johnson wrote:

I'm going to be charitable and assume this is a mistake. This is completely
inappropriate to post to the tutor list.



I assume -- having seen a few of these go past -- that such
services say on joining: do you want me to email every one
in your address book to ask them to link in with you (or
be your friend, or whatever). Naive users will simply say:
yes; here are the keys to my mailbox... and the result will
be posts like these.

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


  1   2   3   4   5   6   >