Re: Variable + String Format

2009-02-10 Thread Steven D'Aprano
On Wed, 11 Feb 2009 18:52:40 +1100, Joel Ross wrote:

> Thanks for the quick response guys. Help me out a alot. I'm a newbie to
> python and your replies help me understand a bit more about python!!

Joel, unless you have Guido's time machine and are actually posting from 
the future, the clock, or possibly the time zone, on your PC is set 
wrong. 


-- 
Steven



--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Gabriel Genellina
En Tue, 10 Feb 2009 03:26:20 -0200, Michele Simionato  
 escribió:

On Feb 10, 4:29 am, "Gabriel Genellina"



> Honestly, I don't understand how this thing got so much out of
> control. If anyone starts an intelligent question or remark about
> super, this essay is thrown in no matter what. Anyone can explain why?

Because for a very loong time (seven years, 2001-2008) super was  
almost undocumented. The Library Reference -before release 2.6- only  
had a  
short paragraph, the online documentation referred (and still does) to  
the  
original essay by Guido introducing descriptors, which is inaccurate  
and  

outdated, and then the "... harmful" article was the only source of  
information available.


All right. This is way I made the effort of writing a comprehensive
collection of all the tricky points about super
I knew:

http://www.artima.com/weblogs/viewpost.jsp?thread=236275
http://www.artima.com/weblogs/viewpost.jsp?thread=236278
http://www.artima.com/weblogs/viewpost.jsp?thread=237121


You really should push them to be included in python.org, even in their  
unfinished form. (At least a link in the wiki pages). Their visibility is  
almost null now.

They're very clearly written - I wish you had published them years ago!


Also see this thread on python-dev about the issue of super
documentation: http://www.gossamer-threads.com/lists/python/dev/673833


Apart from a few remarks in the first posts, there is little criticism of  
your articles themselves. Looks like adding a section about Python 3 is  
the only important pending issue - again, you really should publish the  
series in a more prominent place.


--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-10 Thread Gerhard Weis

Once I have seen Haskell code, that ran fibonacci on a 4 core system.

The algorithm itself basically used an extra granularity paramet until 
which new threads will be sparked. e.g. fib(40, 36) means, calculate 
fib(40) and spark threads until n=36.

1. divide: fib(n-1), fib(n-2)
2. divide: fib(n-2), fib(n-3)
3. divide: fib(n-3), fib(n-4)

We tried this code on a 4 core machine using only 1 core and all 4 cores.
1 core wallclock: ~10s
4 core wallclock: ~3s

So there is a signifcant speedup, but I guess, this only works with 
Haskell out of the box.
I have not tried it, but I think you can simulate Haskell's behaviour, 
by caching the results of fib(n).
(We tried the same algorithm in Java. While it utilized all 4 cores, 
there was no speedup. This is why I think, that result caching is the 
only way to speedup fibonacci.


cheers

Gerhard


On 2009-02-10 17:34:54 +1000, Steven D'Aprano 
 said:



On Tue, 10 Feb 2009 14:28:15 +0800, oyster wrote:


I mean this
[code]
def fib(n):
if n<=1:
return 1
return fib(n-1)+fib(n-2)

useCore(1)
timeit(fib(500)) #this show 20 seconds

useCore(2)
timeit(fib(500)) #this show 10 seconds [/code]

Is it possible?


What does useCore(n) mean?



and more, can threads/multi-processors/clusters be used to improve fib?


No. The best way to improve fib is to improve fib, not to try running it
on faster hardware.

Your algorithm makes *many* recursive calls to fib() for each call:

fib(1) => 1 function call
fib(2) => 3 function calls
fib(3) => 5 function calls
fib(4) => 9 function calls
fib(5) => 15 function calls
fib(6) => 25 function calls
fib(7) => 41 function calls
fib(8) => 67 function calls
fib(9) => 109 function calls
...
fib(34) => 18454929 function calls
fib(35) => 29860703 function calls
fib(36) => 48315633 function calls
...
fib(498) => 1.723e+104 function calls
fib(499) => 2.788e+104 function calls
fib(500) => 4.511e+104 function calls

Calling fib(500) the way you do will make more than 450 thousand billion
billion billion billion billion billion billion billion billion billion
billion function calls. You claim that you calculated it in just 20
seconds. On my PC, it takes over a minute to calculate fib(38). I
estimate it would take over five hours to calculate fib(50), and fib(100)
would probably take 16 million years. I call shenanigans.



--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3D CAD -- need collaborators, or just brave souls :)

2009-02-10 Thread Hendrik van Rooyen
"rantingrick"  wrote

8< - dreams, goals and tentative spec -

Have you looked at Pycad ? - it started off with a similar rush
some time ago.

Maybe there is something there that you can use and/or salvage.

- Hendrik


--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple question - stock market simulation

2009-02-10 Thread Hendrik van Rooyen
"cptn.spoon"  wrote:
On Feb 9, 6:48 pm, "Hendrik van Rooyen"  wrote:

>> No.
>> At this level, just use a list of instances of your Stock class.
>>
>> - Hendrik
>
>How do I get a list of instances of a particular class? Is there a way
>to do this dynamically?

Yes there is. First make an empty list:

stock_market = []

Now when you create the instance:

stuff = GetStuffFromTheUserIfNecessary()
stock_market.append(Stock(stuff))

This leaves the new instance in the last position in the list.

When you have done that as many times as you wanted, 
to create the stocks in the market, you can do:

for stock in stock_market:
DoThingsWithThisOneStock(stock)

>
>Also, what would be the way of dynamically creating an instance of a
>class based on user input (ie a user wants to create a new instance of
>the Stock class via shell input)?

This means your program must be looking for that input.
Either look at thread and threading, or write a simple
loop that gets input, appends a stock, gets more input
if required, does something with all the stocks, and
either loops or terminates. Or some variation of that
like first building the market and then manipulating it.

>
>I'm not sure if I have the wrong mindset here.
>

I honestly cannot tell if your mindset is right or
wrong - I suppose it depends on your definitions
of the two terms.
:-)
- Hendrik


--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning a file character by character

2009-02-10 Thread Hendrik van Rooyen
"Spacebar265"  wrote:

>Thanks. How would I do separate lines into words without scanning one
>character at a time?

Type the following at the interactive prompt and see what happens:

s = "This is a string composed of a few words and a newline\n"
help(s.split)
help(s.rstrip)
help(s.strip)
dir(s)

- Hendrik


--
http://mail.python.org/mailman/listinfo/python-list


import wx works interactive but not from script

2009-02-10 Thread jefm
when I call "import wx" from the interactive console, it works (i.e.
it doesn't complain).
But when I call the same from a script, it complains that it can not
find the wx module.

works for interactive
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>>

does not work frm script--
Traceback (most recent call last):
  File "c:\temp\myscript.py", line 4, in 
import wx
ImportError: No module named wx


I run Vista Home premium 64bit. Python 2.6.1 (the 32-bit version).
I installed the latest 32-bit ANSI version of wxpython. (http://
downloads.sourceforge.net/wxpython/wxPython2.8-win32-ansi-2.8.9.1-
py26.exe)
In the folder C:\Python26\Lib\site-packages, I find a wx.pth file with
a single line in there: "wx-2.8-msw-ansi"
in that same directory is a folder named "wx-2.8-msw-ansi" and it
contains a subdirectory called "wx" with what appears to be the
regular wx libary stuff, including __init__.py
My PATH starts with C:\Python26;C:\Python26\Scripts;C:\Python26\lib;

any idea's ?






--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-10 Thread Steven D'Aprano
On Tue, 10 Feb 2009 18:18:23 +1000, Gerhard Weis wrote:

> Once I have seen Haskell code, that ran fibonacci on a 4 core system.
> 
> The algorithm itself basically used an extra granularity paramet until
> which new threads will be sparked. e.g. fib(40, 36) means, calculate
> fib(40) and spark threads until n=36. 1. divide: fib(n-1), fib(n-2)
> 2. divide: fib(n-2), fib(n-3)
> 3. divide: fib(n-3), fib(n-4)
> 
> We tried this code on a 4 core machine using only 1 core and all 4
> cores. 1 core wallclock: ~10s
> 4 core wallclock: ~3s

Three seconds to calculate fib(40) is terrible. Well, it's a great saving 
over ten seconds, but it's still horribly, horribly slow.

Check this out, on a two-core 2.2 GHz system:


>>> import timeit
>>> timeit.Timer('fib(40)', 'from __main__ import fib').timeit(1)
7.2956085205078125e-05

That's five orders of magnitude faster. How did I do it? I used a better 
algorithm.


def fib(n, a=1, b=1):
if n==0:
return a
elif n==1:
return b
return fib(n-1, b, a+b)


And for the record:

>>> fib(500)
225591516161936330872512695036072072046011324913758190588638866418474627738686883405015987052796968498626L
>>> timeit.Timer('fib(500)', 'from __main__ import fib').timeit(1)
0.00083398818969726562

Less than a millisecond, versus millions of years for the OP's algorithm. 
I know which I would choose. Faster hardware can only go so far in hiding 
the effect of poor algorithms.



-- 
Steven
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Tkinter's scale function.

2009-02-10 Thread Hendrik van Rooyen

Nicholas Feinberg wrote:


>Code that caused the problem (unlikely to be helpful, but no reason not to
include it):
>self.canvas.scale(self.body,self.radius/(self.radius-.5),self.radius/(self.radi
us-.05),0,0)#radius is greater than .5

scale's arguments are:

scale(TagOrID,xorigen,yorigen,xscale,yscale)

You seem to be moving the thing and scaling it to zero...

- Hendrik

--
http://mail.python.org/mailman/listinfo/python-list


Re: import wx works interactive but not from script

2009-02-10 Thread Tim Golden

jefm wrote:

when I call "import wx" from the interactive console, it works (i.e.
it doesn't complain).
But when I call the same from a script, it complains that it can not
find the wx module.

works for interactive
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

import wx



does not work frm script--
Traceback (most recent call last):
  File "c:\temp\myscript.py", line 4, in 
import wx
ImportError: No module named wx



Do you have only the one version of Python on this
machine? Did you upgrade from, eg, Python2.5? And
are you running this script by, eg, double-clicking
on it / running it from the command prompt with the
script name alone? If so, check that ftype python.file
shows that .py files are associated with the version
of Python you expect.

TJG
--
http://mail.python.org/mailman/listinfo/python-list


Convert date/time to unix timestamp?

2009-02-10 Thread Phillip B Oldham
Is there a simple way to set a date/time and convert it to a unix
timestamp? After some googling I found the following:

t = datetime.time(7,0,0)
starttime = time.mktime(t.timetuple())+1e-6*t.microsecond

That seems like very long-winded. Is there an easier way? I've read
the docs on the datetime and time modules, but nothing's jumping out
at me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-10 Thread Gabriel Genellina
En Tue, 10 Feb 2009 06:45:37 -0200, Steven D'Aprano  
 escribió:

On Tue, 10 Feb 2009 18:18:23 +1000, Gerhard Weis wrote:


We tried this code on a 4 core machine using only 1 core and all 4
cores. 1 core wallclock: ~10s
4 core wallclock: ~3s


Three seconds to calculate fib(40) is terrible. Well, it's a great saving
over ten seconds, but it's still horribly, horribly slow.

Check this out, on a two-core 2.2 GHz system:



import timeit
timeit.Timer('fib(40)', 'from __main__ import fib').timeit(1)

7.2956085205078125e-05

That's five orders of magnitude faster. How did I do it? I used a better
algorithm.


def fib(n, a=1, b=1):
if n==0:
return a
elif n==1:
return b
return fib(n-1, b, a+b)


I agree with your comment, but this is not the right way to write it in  
Python. This style is fine in a language with tail-call optimization --  
but fib(1000) raises `RuntimeError: maximum recursion depth exceeded`


The same thing after removing recursion can compute the 2089 digits of  
fib(1) without problems:


def fib(n):
a = b = 1
while n:
  n, a, b = n-1, b, a+b
return a


Less than a millisecond, versus millions of years for the OP's algorithm.
I know which I would choose. Faster hardware can only go so far in hiding
the effect of poor algorithms.


Completely agree!

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-10 Thread Chris Rebert
On Tue, Feb 10, 2009 at 12:45 AM, Steven D'Aprano
 wrote:
> On Tue, 10 Feb 2009 18:18:23 +1000, Gerhard Weis wrote:
>
>> Once I have seen Haskell code, that ran fibonacci on a 4 core system.
>>
>> The algorithm itself basically used an extra granularity paramet until
>> which new threads will be sparked. e.g. fib(40, 36) means, calculate
>> fib(40) and spark threads until n=36. 1. divide: fib(n-1), fib(n-2)
>> 2. divide: fib(n-2), fib(n-3)
>> 3. divide: fib(n-3), fib(n-4)
>>
>> We tried this code on a 4 core machine using only 1 core and all 4
>> cores. 1 core wallclock: ~10s
>> 4 core wallclock: ~3s
>
> Three seconds to calculate fib(40) is terrible. Well, it's a great saving
> over ten seconds, but it's still horribly, horribly slow.
>
> Check this out, on a two-core 2.2 GHz system:
>
>
 import timeit
 timeit.Timer('fib(40)', 'from __main__ import fib').timeit(1)
> 7.2956085205078125e-05
>
> That's five orders of magnitude faster. How did I do it? I used a better
> algorithm.
>
>
> def fib(n, a=1, b=1):
>if n==0:
>return a
>elif n==1:
>return b
>return fib(n-1, b, a+b)
>
>
> And for the record:
>
 fib(500)
> 225591516161936330872512695036072072046011324913758190588638866418474627738686883405015987052796968498626L
 timeit.Timer('fib(500)', 'from __main__ import fib').timeit(1)
> 0.00083398818969726562
>
> Less than a millisecond, versus millions of years for the OP's algorithm.
> I know which I would choose. Faster hardware can only go so far in hiding
> the effect of poor algorithms.

Indeed. And apparently memoization can hide it also:

$ #memoization added to OP's code
$ python -m timeit -s 'from memoized_naive_recursive_version import
fib' 'fib(40)'
100 loops, best of 3: 0.639 usec per loop
$ #your code
$ python -m timeit -s 'from your_version import fib' 'fib(40)'
10 loops, best of 3: 15.4 usec per loop
$ cat memoized_naive_recursive_version.py
def memoize(func):
cache = {}
def memoized(*args):
if args in cache:
return cache[args]
else:
result = func(*args)
cache[args] = result
return result
return memoized

@memoize
def fib(n):
if n <= 1:
return 1
else:
return fib(n-1) + fib(n-2)

However, the naive recursive version fails by exceeding the maximum
recursion depth if N is too large, whereas your version continues to
succeed for a much higher limit of N.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Marc 'BlackJack' Rintsch
On Tue, 10 Feb 2009 02:02:43 +, Benjamin Peterson wrote:

> Jean-Paul Calderone  divmod.com> writes:
>> Consider whether you really need to use super().
>> 
>> http://fuhm.net/super-harmful/
> 
> This article chiefly deals with super()'s harm in multiple inteheritance
> situations. For the simple case, though, like that presented by the OP,
> I believe super() is perfect.

But for the simple cases it is unnecessary because it was invented to 
deal with multiple inheritance problems.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which core am I running on?

2009-02-10 Thread Gerhard Häring
[email protected] wrote:
> On 9 Feb, 12:24, Gerhard Häring  wrote:
>> http://objectmix.com/python/631346-parallel-python.html
>>
> 
> Hmm. In fact, this doesn't seem to work for pp. When I run the code
> below, it says everything is running on the one core.
> 
> import pp
> import random
> import time
> from string import lowercase
> 
> ncpus = 3
> 
> def timedCharDump(waittime, char):
>   time.sleep(waittime)
>   mycore = open("/proc/%i/stat" % os.getpid()).read().split()[39]
>   print "I'm doing stuff!", mycore, char
>   return char
> 
> job_server = pp.Server(ncpus, ppservers=())
> 
> jobdetails = [ (random.random(), letter) for letter in lowercase ]
> 
> jobs = [ job_server.submit(timedCharDump,(jinput1, jinput2), (),
> ("os", "time",)) for jinput1, jinput2 in jobdetails ]
> 
> for job in jobs:
>   print job()

Quick look again found this:

http://brokestream.com/procstat.html

I guess I counted wrong and it's actually column 38, not 39.

-- Gerhard

--
http://mail.python.org/mailman/listinfo/python-list


Setting DNS using win32com

2009-02-10 Thread Nacho
I am trying to make a small python application to change DNS servers
in a small LAN.

I am trying this code but I don't manage it to work, I only get the
values removed.

My code is this:

import win32com.client

objWMIService = win32com.client.GetObject("winmgmts:
{impersonationLevel=impersonate}!" + strComputer + "\\root\
\cimv2")
nicList = objWMIService.ExecQuery("SELECT * FROM
Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

for nic in nicList:
nic.DNSServerSearchOrder = (u'1.2.3.4', u'2.3.4.5')
nic.SetDNSServerSearchOrder

nic.SetDNSServerSearchOrder returns 0 so it is supposed to have been
done correctly, but no DNS Server is found in the Network Properties.

I don't know what I am doing wrong so any hint or any documentation
about this would be appreciated.

Thank you by now.

--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-10 Thread Niklas Norrthon
On 10 Feb, 09:45, Steven D'Aprano
 wrote:
> On Tue, 10 Feb 2009 18:18:23 +1000, Gerhard Weis wrote:
> > Once I have seen Haskell code, that ran fibonacci on a 4 core system.
>
> > The algorithm itself basically used an extra granularity paramet until
> > which new threads will be sparked. e.g. fib(40, 36) means, calculate
> > fib(40) and spark threads until n=36. 1. divide: fib(n-1), fib(n-2)
> > 2. divide: fib(n-2), fib(n-3)
> > 3. divide: fib(n-3), fib(n-4)
>
> > We tried this code on a 4 core machine using only 1 core and all 4
> > cores. 1 core wallclock: ~10s
> > 4 core wallclock: ~3s
>
> Three seconds to calculate fib(40) is terrible. Well, it's a great saving
> over ten seconds, but it's still horribly, horribly slow.
>
> Check this out, on a two-core 2.2 GHz system:
>
> >>> import timeit
> >>> timeit.Timer('fib(40)', 'from __main__ import fib').timeit(1)
>
> 7.2956085205078125e-05
>
> That's five orders of magnitude faster. How did I do it? I used a better
> algorithm.
>
> def fib(n, a=1, b=1):
>     if n==0:
>         return a
>     elif n==1:
>         return b
>     return fib(n-1, b, a+b)
>
> And for the record:
>
> >>> fib(500)
>
> 225591516161936330872512695036072072046011324913758190588638866418474627738686883405015987052796968498626L

According to the common definition of fibonacci numbers fib(0) = 0, fib
(1) = 1 and fib(n) = fib(n-1) + fib(n-2) for n > 1. So the number
above is fib(501).

>>> timeit.Timer('fib(500)', 'from __main__ import fib').timeit(1)
>
> 0.00083398818969726562

And now for my version (which admitedly isn't really mine, and returns
slightly incorrect fib(n) for large values of n, due to the limited
floating point precision).

>>> import math
>>> sqrt5 = math.sqrt(5)
>>> golden_section = (sqrt5 + 1) / 2
>>> def fib(n):
return int(golden_section ** n / sqrt5 + 0.5)

>>> fib(501)
225591516161940121919323945317755919750165306733355143970858461525064153963081278412888159063487104942080L

>>> timeit.Timer('fib(501)', 'from __main__ import fib').timeit(1)
1.958083084179e-05

>
> Less than a millisecond, versus millions of years for the OP's algorithm.
> I know which I would choose. Faster hardware can only go so far in hiding
> the effect of poor algorithms.
>

I agree 100%

/Niklas Norrthon
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Michele Simionato
On Feb 10, 10:42 am, Marc 'BlackJack' Rintsch  wrote:
> On Tue, 10 Feb 2009 02:02:43 +, Benjamin Peterson wrote:
> > Jean-Paul Calderone  divmod.com> writes:
> >> Consider whether you really need to use super().
>
> >>http://fuhm.net/super-harmful/
>
> > This article chiefly deals with super()'s harm in multiple inteheritance
> > situations. For the simple case, though, like that presented by the OP,
> > I believe super() is perfect.
>
> But for the simple cases it is unnecessary because it was invented to
> deal with multiple inheritance problems.
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Unfortunately there is no good solution. If you have a single
inheritance hierarchy and you do
not use super, you make it impossible for users of your hierarchy to
subclass it by using multiple inheritance in a cooperative way (this
is not polite).
OTOH, if you user super, your users must know about it, to avoid
unexpected cooperation. It is all explained in the "super harmful"
paper, which is a must read even if you only use single inheritance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python binaries with VC++ 8.0?

2009-02-10 Thread greg

Mark Hammond wrote:

What problems specifically?  The only practical problems you should see 
will arise if you try and pass a "FILE *", or allocate memory you then 
ask python to free (or vice-versa) - both should be avoidable though...


It concerns a Ruby plugin for Sketchup that embeds a Python
interpreter and acts as a bridge between Ruby and Python.
I'm using Sketchup 7 which uses msvcrt80.dll, and includes
a Ruby dll which is presumably also linked against that
crt.

I've made some progress on the issue. One problem turned out to
be a result of allocating something with ruby_xmalloc() and
freeing it with free(), which was easy to fix.

Another one seemed to be something to do with trying to use
a global var that points to the current Ruby stack frame. I
don't really know what was happening, but I found another way
of doing things that sidestepped the issue.

I've now got it working, at first sight anyhow, using Python 2.3.

But it doesn't work properly with Python 2.5. The problem
appears to be related to compiling .py files to .pyc. The
first time I run it and try to import a module, a .pyc is
generated, but then a crash occurs when trying to call one
of the functions imported from it. If I run it a second time,
with the previously generated .pyc in place, it runs successfully.

Which makes me think it may be some kind of FILE * problem,
but I'm not sure what, since all the stdio operations on
the files concerned should be getting done by Python.

To add insult to injury, it's proving to be very difficult
to debug, because Sketchup seems to crash all on its own
when run under gdb on Windows, even when I don't load any
of my code. So I can't get a traceback of where the crash
is occurring.

There's one possibility I just thought of -- Python may
be trying to write something to stdout or stderr, in which
case it will probably be using the wrong crt to do it.
Something to look into after I've got some sleep...

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Converting timestamps across timezones

2009-02-10 Thread Christopher Culver
A script that I'm writing pulls the system time off of an iPod
connected to the computer. The iPod's time is represented as a Unix
timestamp (seconds since the epoch), but this timestamp does not
represent UTC time, but rather the local timezone of the owner. I need
to convert this local time timestamp into a UTC timestamp by referring
to the timezone specified by /etc/localtime on the computer.

I've read through the docs, but I'm rather lost on how to pull this
particular operation off. Any advice would be appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning a file character by character

2009-02-10 Thread Duncan Booth
Steven D'Aprano  wrote:

> On Mon, 09 Feb 2009 19:10:28 -0800, Spacebar265 wrote:
> 
>> How would I do separate lines into words without scanning one character
>> at a time?
> 
> Scan a line at a time, then split each line into words.
> 
> 
> for line in open('myfile.txt'):
> words = line.split()
> 
> 
> should work for a particularly simple-minded idea of words.
> 
Or for a slightly less simple minded splitting you could try re.split:

>>> re.split("(\w+)", "The quick brown fox jumps, and falls over.")[1::2]
['The', 'quick', 'brown', 'fox', 'jumps', 'and', 'falls', 'over']


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: AJAX Post requests

2009-02-10 Thread Paul
On Feb 10, 7:37 am, Tim Roberts  wrote:
> PJ  wrote:
>
> >I have a simple web server using  BaseHTTPServer, and the def do_POST
> >(self) function works fine for regular forms that are submitted to it,
> >but when I send anAJAXPOST to it it does nothing (I've tried to just
> >get it to print to check it's nothing else but it doesn't even do
> >that, although it does for a regular POST request.
>
> Are you absolutely sure yourAJAXrequest is being sent with Content-Type
> multipart/form-data?  Your code would explode silently if it didn't,
> because "query" would not exist when you got to "print(query.get('data'))",
> and your blanket "except" would hide the error.
> --
> Tim Roberts, [email protected]
> Providenza & Boekelheide, Inc.

Thankyou for that - you're right - I'm new to AJAX so it's taking me a
bit of time to get used to it - its an application data type being
submitted
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python binaries with VC++ 8.0?

2009-02-10 Thread bearophileHUGS
Paul Rubin:
> Gideon Smeding of the University of
> Utrecht has written a masters' thesis titled "An executable
> operational semantics for Python".

A significant part of Computer Science is a waste of time and money.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: generator object or 'send' method?

2009-02-10 Thread andrew cooke

steven probably knows this, but to flag the issue for people who are
looking at generators/coroutines for the first time: there's a little
"gotcha" about exactly how the two sides of the conversation are
synchronized.  in simple terms: send also receives.

unfortunately the example steven gave doesn't really show this, so i've
modified it below.  you can now see that the first next() after .send()
receives 2, not 1.  note that i am using python 3, so the .next() method
is .__next__() (the asymmetry between next and send seems odd to me, but
there you go).

(in a sense this is completely logical, but if you're used to the
asynchronous way the internet works, it can seem unintuitive)

how to handle this was one of the things the original post was asking
about (if i understood correctly).

>>> def gen(n):
...   while True:
... obj = yield n
... n += 1
... if obj is not None: n = obj
...
>>> g = gen(5)
>>> next(g)
5
>>> g.__next__()
6
>>> g.send(1)
1
>>> next(g)
2

andrew


Steven D'Aprano wrote:
> On Tue, 10 Feb 2009 05:28:26 +, John O'Hagan wrote:
>> I would love to see a simple code example of this if you have one; I've
>> been wanting to do this but couldn't even get started.
>
> Is this too simple?
>
 def gen(n):
> ... while True:
> ... obj = yield n
> ... if obj is not None: n = obj
> ...
 g = gen(5)
 g.next()
> 5
 g.next()
> 5
 g.send(12)
> 12
 g.next()
> 12


--
http://mail.python.org/mailman/listinfo/python-list


Re: Variable + String Format

2009-02-10 Thread Joel Ross

Steven D'Aprano wrote:

On Wed, 11 Feb 2009 18:52:40 +1100, Joel Ross wrote:


Thanks for the quick response guys. Help me out a alot. I'm a newbie to
python and your replies help me understand a bit more about python!!


Joel, unless you have Guido's time machine and are actually posting from 
the future, the clock, or possibly the time zone, on your PC is set 
wrong. 




I'm from the distant future. Too protect and Serve humankind!!!

lol thanks dude. I'm a day ahead of myself. I had my linux box running 
off UTC and it didn't include daylight savings so I adjusted it myself, 
must have accidentally changed the day as well :).

--
http://mail.python.org/mailman/listinfo/python-list


Re: Variable + String Format

2009-02-10 Thread Joel Ross

Joel Ross wrote:

Hi all,

I have this piece of code:
#

wordList = "/tmp/Wordlist"
file = open(wordList, 'r+b')


def readLines():

for line in file.read():
if not line: break
print line + '.com '
return line



readLines()
file.close()

##

It returns the results:

t.com

NOTE: Only returns the first letter of the first word on the first line 
e.g. test would only print t and readline() does the same thing.


I have also tried readlines() which gives me the result:

test
.com

The file Wordlist has one word on each line for example

test
test1
test2

I need it to loop though the Wordlist file and print/return the results

test.com
test1.com
test2.com

I'm just looking for a point in the right direction.

Much Thanks

JOelC



THAT'S BETTER!!! :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-10 Thread Lie Ryan
On Tue, 10 Feb 2009 14:28:15 +0800, oyster wrote:

> I mean this
> [code]
> def fib(n):
> if n<=1:
> return 1
> return fib(n-1)+fib(n-2)
> 
> useCore(1)
> timeit(fib(500)) #this show 20 seconds
> 
> useCore(2)
> timeit(fib(500)) #this show 10 seconds [/code]
> 
> Is it possible?
> 
> and more, can threads/multi-processors/clusters be used to improve fib?
> 
> thanx

Of course multi-core processor can improve single function using 
multiprocessing, as long as the function is parallelizable. The Fibonacci 
function is not a parallelizable function though.

However, there are ways to improve your fibonacci function. Either put 
off the recursion or implement a memoization. An imperative fibonacci is 
much faster than a naive recursion one because a naive recursive 
fibonacci function is O(2**n) while the imperative one O(n). Memoization 
must be used to help recursive fibonacci to become O(n).

--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-10 Thread Gerhard Weis

def fib(n, a=1, b=1):
if n==0:
return a
elif n==1:
return b
return fib(n-1, b, a+b)


And for the record:


fib(500)

225591516161936330872512695036072072046011324913758190588638866418474627738686883405015987052796968498626L
timeit.Timer('fib(500)', 



'from __main__ import fib').timeit(1)

0.00083398818969726562
Less than a millisecond, versus millions of years for the OP's algorithm.
I know which I would choose. Faster hardware can only go so far in hiding
the effect of poor algorithms.


I agree to 100% to this.

btw. the timeings are not that different for the naive recursion in 
OP's version and yours.

fib(500) on my machine:
OP's: 0.00116 (far away from millions of years)
This here: 0.000583
Gabriel's while loop: 0.000246

The fastest algorithm I've found does fib(100) in .25seconds on my machine.
However, I have not found a way to parallelize this algorithm and I 
think it is not possible.


To come back to the original question. Yes it is possible; however 
there are quite some restrictions about it. In case of the naive 
recursion it was possible to get a speedup of more than 3 times on a 4 
core machine. With the highly optimised version mentioned above, I had 
no success in utilizing more than one core.


As conclusion I would say, Yes, a single function can profit from 
multiple cores, but sometimes a better algorithm delivers better 
results than using more cores. However, it is possible that a slower 
but parallelizable algorithm might outperform the best serial 
algorithm, with enough cores :).


Gerhard

--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert date/time to unix timestamp?

2009-02-10 Thread Thomas Kraus

Phillip B Oldham schrieb:

Is there a simple way to set a date/time and convert it to a unix
timestamp? After some googling I found the following:

t = datetime.time(7,0,0)
starttime = time.mktime(t.timetuple())+1e-6*t.microsecond

That seems like very long-winded. Is there an easier way? I've read
the docs on the datetime and time modules, but nothing's jumping out
at me.


The built-in function time.localtime() returns a 9-item tuple, e.g. 
(2009, 2, 10, 13, 29, 7, 1, 41, 0).


time.mktime() converts this tuple to the seconds since the Epoch as a 
floating point number, int() converts it to an integer.


int(time.mktime(time.localtime()))

--
Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert date/time to unix timestamp?

2009-02-10 Thread andrew cooke

the python routines are a bit basic - you really have to think quite hard
about what you are doing to get the right answer.

in your case, you need to be clear what the timezone is for the datetime
you are using.  timezone info is optional (see the datetime documentation,
where it talks about "naive" and "aware" objects).

anyway, ignoring that, i think you need the very useful, but oddly
located, calendar.timegm().

andrew


Phillip B Oldham wrote:
> Is there a simple way to set a date/time and convert it to a unix
> timestamp? After some googling I found the following:
>
> t = datetime.time(7,0,0)
> starttime = time.mktime(t.timetuple())+1e-6*t.microsecond
>
> That seems like very long-winded. Is there an easier way? I've read
> the docs on the datetime and time modules, but nothing's jumping out
> at me.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


--
http://mail.python.org/mailman/listinfo/python-list


Re: Import without executing module

2009-02-10 Thread Lie Ryan
On Tue, 03 Feb 2009 20:08:34 -0800, Stephen Hansen wrote:

> There is no need to try to make sure something is
> executed/compiled only once in Python like you may want to do in C.
> Every module is only ever compiled once: if you import it ten times in
> ten different places only the first will compile and execute the code,
> the rest of the calls will return that original module again.


If you import a module, it will be recompiled only if the module changes 
from the precompiled .pyc/.pyo. OTOH, if you run a module, it will be 
recompiled every time even if there is no change.


--
http://mail.python.org/mailman/listinfo/python-list


python ssh and Tetia SSH server

2009-02-10 Thread loial
Anyone out there any experience of using python ssh modules to connect
to the Tetia SSH server from SSH (ssh.com)?



--
http://mail.python.org/mailman/listinfo/python-list


COM and threading, "CoInitialize"?

2009-02-10 Thread Ferdinand Sousa
Greetings to list members,

I am trying to use an Acrobat COM object in a class that is subclassed from
threading.Thread.
Since threading.Thread is subclassed, the __init__ method of the inheriting
class must explicitly call the threading.Thread.__init__ method of the
parent. I guess I'm missing something similar for the COM object. Threading
code and traceback below. Any pointers?

CODE:
=
class process_file(threading.Thread):

def __init__(self,connection):
threading.Thread.__init__(self)
self.connection=connection

def run(self):

irrelevant code here


# Acrobat COM starts
AVD = win32com.client.Dispatch('AcroExch.AVDoc')   # Traceback
refers to this line (89)
pdfname=pdfname.replace('.pdf',PDFNAME_SUFFIX)
AVD.Open(pdf.name, pdfname) # 
print 'opened avdoc'
==

TRACEBACK:
==
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
  File "D:\Ferdinand\#Storage\Ferdi-python\Acrobat Automation\temp
testing.py", line 89, in run
AVD = win32com.client.Dispatch('AcroExch.AVDoc')
  File "C:\Python25\Lib\site-packages\win32com\client\__init__.py", line 95,
in Dispatch
dispatch, userName =
dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", line 98,
in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", line 78,
in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
pythoncom.IID_IDispatch)
com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
==

TIA. Best regards,
Ferdi
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert date/time to unix timestamp?

2009-02-10 Thread M.-A. Lemburg
On 2009-02-10 10:26, Phillip B Oldham wrote:
> Is there a simple way to set a date/time and convert it to a unix
> timestamp? After some googling I found the following:
> 
> t = datetime.time(7,0,0)
> starttime = time.mktime(t.timetuple())+1e-6*t.microsecond
> 
> That seems like very long-winded. Is there an easier way? I've read
> the docs on the datetime and time modules, but nothing's jumping out
> at me.

>>> from mx.DateTime import DateTime
>>> DateTime(2009,10,2,7,0,0).ticks()
1254459600.0

http://www.egenix.com/products/python/mxBase/mxDateTime/

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Feb 10 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
--
http://mail.python.org/mailman/listinfo/python-list


Re: python ssh and Tetia SSH server

2009-02-10 Thread Tino Wildenhain

loial wrote:

Anyone out there any experience of using python ssh modules to connect
to the Tetia SSH server from SSH (ssh.com)?


Did you call their support? Personally I see no reason why
paramiko http://www.lag.net/paramiko/ should not work, given
that openssh ssh client also worked in the past with ssh.com
ssh.

Maybe you can get a test version and just try it out.

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


poplib

2009-02-10 Thread Gabriel Rossetti

Hello,

I am using poplib and I noticed that calls to top() don't return the msg 
info (2nd index in the returned list, e.g. email.top(1,0)[1]) in the 
same order, by that I mean the date could be email.top(1,0)[1][2] or 
email.top(1,0)[1][5], etc. Is there a reason for that other than that 
may be how the server is sending them? Why not re-order them and send 
back a list that always had the date as element n or even better a dict?


Thank you,
Gabriel
--
http://mail.python.org/mailman/listinfo/python-list


Python at the SoCal Linux Expo

2009-02-10 Thread joe
Hey guys,

The Southern California Linux Expo, a community run conference taking
place in Los Angeles on February 20th to 22nd, is offering a 50% discount
to the Python community. When you go to register[1], just enter the promo
code: PYTHN. If you have any questions, please let me know.

Thanks!
Joe Smith
Southern California Linux Expo

[1] https://socallinuxexpo.org/reg7/



--
http://mail.python.org/mailman/listinfo/python-list


STMP, mail, sender-from, to-bcc-addr

2009-02-10 Thread durumdara

Hi!

I wanna ask that have anyone some experience with email.msg and smtplib?

The email message and smtp.send already have "sender/from" and 
"recip/addr to".
Possible the smtp components does not uses the email tags if I not 
define them only in the message?


Can I do same thing as in GMAIL that the mail does not have TO, only BCC 
tags/recipients, and no one of the recipients who knows about the each 
others?


Thanks:
   dd

--
http://mail.python.org/mailman/listinfo/python-list


Re: Local python web server problem

2009-02-10 Thread Farsheed Ashouri
Thanks guys, Really appreciate your help. I am trying to solve the
problem and will keep you posted when I found a solution.

Farsheed Ashouri,
Tehran, Iran
--
http://mail.python.org/mailman/listinfo/python-list


codecs.open and buffering modes...

2009-02-10 Thread Sam
codecs.open defaults to line buffering.  But open defaults to using
the system buffer size.  Why the discrepancy?  Is it different for a
reason?

How do these choices affect performance?  (Particularly under Linux).

Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.0 has more duplication in source code than Python2.5

2009-02-10 Thread Дамјан Георгиевски
> I have made the same analysis to some commercial source code, the
> dup60 rate is quite often significantly larger than 15%.

commercial code sucks often .. that's why they hide it :)


-- 
дамјан ( http://softver.org.mk/damjan/ )

Scarlett Johansson: You always see the glass half-empty.
Woody Allen: No. I see the glass half-full, but of poison.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Cheetah and hungarian charset...

2009-02-10 Thread durumdara

Hi!

Ok, I forget to set encodings.

from Cheetah.Template import Template
d = {'a' : 'almás'}
tp = Template("# encoding: iso-8859-2\nhello world éááá ${d['a']}!", 
searchList = {'d': d})

print tp

sys.exit()

This code is working for me in Windows.

dd

2009.02.05. 16:21 keltezéssel, durumdara írta:

Hi!

I wanna ask that have anyone some exp. with Cheetah and the non-ascii 
chars?


I have a site. The html template documents are saved in ansi format, 
psp liked them.
But the cheetah parser makes ParseError on hungarian characters, like 
"á", "é", "í", etc. When I remove them, I got good result, but I don't 
want to remove them all...


I cannot parse them. Please help me, how to force cheetah to eat them 
all?


Thanks for your help:
dd



--
http://mail.python.org/mailman/listinfo/python-list


Re: COM and threading, "CoInitialize"?

2009-02-10 Thread Tim Golden

Ferdinand Sousa wrote:

Greetings to list members,

I am trying to use an Acrobat COM object in a class that is subclassed from
threading.Thread.
Since threading.Thread is subclassed, the __init__ method of the inheriting
class must explicitly call the threading.Thread.__init__ method of the
parent. I guess I'm missing something similar for the COM object. Threading
code and traceback below. Any pointers?


[... snip lots of code and traceback ...]


com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
==


Well, much as I may grumble about opaque error messages, you're not going
to find one much more explicit than this. Try calling CoInitialize,
once per thread, eg before your Dispatch line. You'll have to import
pythoncom and then just call pythoncom.CoInitialize ()

TJG
--
http://mail.python.org/mailman/listinfo/python-list


Using paramiko rsa key

2009-02-10 Thread loial
I want to connect via ssh from a python script on windows to an AIX
server running openSSH using rsa keys rather than a password.

Can anyone provide me with /point me at  a simple tutuorial on the
steps I need to go though in terms of geneerating the key, installing
on the server and connecting in my python code?

Thanks in advance.



--
http://mail.python.org/mailman/listinfo/python-list


OpenERP 5.0 - Fully developed with Python

2009-02-10 Thread Stephane Wirtel

OpenERP 5.0 is out !


Why do I talk about OpenERP on this mailing list ? Because OpenERP is fully 
developed with Python

That major enhancement of Open ERP can now answer to all the needs of a business. Open ERP V5 not only provides management functions, but also all functionalities necessary to a SMB, like : a process 
management by modules, a wiki, a webmail, a Business Intelligence (Cube OLAP),  a Document Management System, an eCommerce, an idea box, etc.


Emphasis was placed on an extreme simplification of the software for the new users, a carefully designed ergonomy of the web client with, amongst others, drag&drop, Gantt graph, editable processes, 
etc., and more then 350 modules for specific sectors and big companies.


This new version comes with a full review of the web site giving access to more then 1500 pages of documentations on business management and a reorganization of the community sources build upon the 
Open Object framework. Free cycles of conferences are planned with the version 5.0 release of Open ERP.


Thanks to its huge community, Open Object produce more then 20 modules a month. The Open Object community it is more then 1000 contributors, 126 development branches in parallel, an average of 400 new 
functinalities or bugfix per month, one commit every 5 minutes and functional and technical  experts specialized by activity and working in teams.


The rise of Open Object and the diversity of the projects makes it an unmatched framework composed of more then 400 modules installable in a few clicks to cover all kinds of need or to simply start, 
with a simple module, to answer a simple need. Then, you can install other functionalities to come to a fully integrated and automaized system.


Open ERP v5 is characterized by the appearance of many functionalities far 
beyond the perimeter of traditional management.
One can underline the following innovations:

* A integrated wiki.
* An integrated document management system.
* A Business Intelligence (BI) using a OLAP database.
* An integrated BPM (management of process).
* A web portal for clients and suppliers.
* Improvement of translations (1 translation file by language and module).
* A touchscreen point of sale.
* A full Ajax webmail .
* A shared calendar.
* Plugins for Outlook, OpenOffice, ms. Office, Thunderbird.
* An integrated eCommerce, etc

This new release offers 3 user interfaces :
* the rich application client for a day to day advanced use,
* the web interface allowing a remote access and an easy deployment,
* the QT client that perfectly fits in a KDE environment.

Numerous improvements have been added to the client interfaces, like :
* dynamic graphs and dashboards,
* really ergonomic calendar views,
* dynamic Gantt graphs for planning,
* workflows editors,
* a fully integrated documentation,
* a dynamic process view used for the end-user training,
* etc.

The web version of Open ERP includes numerous functions to  modify or create 
your own application :
* an visual view editor,
* an object editor,
* a workflow (process) editor,
* an Open Office integrated report editor
* a statistics engine (BI cube),
* etc.

URL: http://www.openerp.com
URL: http://www.openobject.com
DOC: http://doc.openerp.com
Screencast: http://www.openerp.tv
LaunchPad Project: http://launchpad.net/openobject
--
Stephane Wirtel - "As OpenERP is OpenSource, please feel free to contribute."
Developper - Technical Instructor OpenERP
OpenERP - Tiny SPRL
Chaussee de Namur, 40
B-1367 Gerompont
Tel: +32.81.81.37.00
Web: http://www.tiny.be
Web: http://www.openerp.com
Planet: http://www.openerp.com/planet/
Blog: http://stephane-wirtel-at-tiny.blogspot.com
begin:vcard
fn:Stephane Wirtel
n:Wirtel;Stephane
org:OpenERP - Tiny sprl
adr;quoted-printable;quoted-printable:;;Chauss=C3=A9e de Namur, 40;G=C3=A9rompont;;1367;Belgium
email;internet:[email protected]
title:Developer
tel;work:+32.81.81.37.00
note;quoted-printable:OpenERP is an Open Source enterprise management software=0D=0A=
	=0D=0A=
	http://www.openerp.com
x-mozilla-html:FALSE
url:http://www.tiny.be
version:2.1
end:vcard

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Launcher.app on OS X

2009-02-10 Thread Philip Semanchuk


On Feb 9, 2009, at 10:26 PM, kpp9c wrote:


okay... for the life of me i do not see any Python Launcher.app and i
just installed OS X 10.5 (running 10.5.6 on intel)  and i also
installed the dev kit.

Where the heck is this application?


Hi kp,
I don't seem to have any such beast on my system except for the one  
in /Applications/MacPython 2.5/. Perhaps the documentation is mistaken?



--
http://mail.python.org/mailman/listinfo/python-list


Re: Using paramiko rsa key

2009-02-10 Thread Tino Wildenhain

loial wrote:

I want to connect via ssh from a python script on windows to an AIX
server running openSSH using rsa keys rather than a password.

Can anyone provide me with /point me at  a simple tutuorial on the
steps I need to go though in terms of geneerating the key, installing
on the server and connecting in my python code?


Sure, where can we send the invoice too?

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: STMP, mail, sender-from, to-bcc-addr

2009-02-10 Thread Philip Semanchuk


On Feb 10, 2009, at 7:29 AM, durumdara wrote:


Hi!

I wanna ask that have anyone some experience with email.msg and  
smtplib?


The email message and smtp.send already have "sender/from" and  
"recip/addr to".
Possible the smtp components does not uses the email tags if I not  
define them only in the message?


Can I do same thing as in GMAIL that the mail does not have TO, only  
BCC tags/recipients, and no one of the recipients who knows about  
the each others?


Hi dd,
I'm not exactly sure what you're asking, but my memories of  
implementing BCC are that there is no BCC tag. It's your job as the  
programmer building the application that sends the message to send the  
mail to everyone on the BCC list. Something like this:


for recipient in bcc:
   send_mail(to=recipient)

Hope this helps
Philip
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling into Python from a C thread

2009-02-10 Thread Philip Semanchuk


On Feb 9, 2009, at 3:59 PM, Christian Heimes wrote:


Philip Semanchuk wrote:
Yes, that's accurate except for the word "forgot". To forget  
something

one must first know it. =) I found the threading API documentation
difficult to follow, but I suppose that what I'm doing is a little
unusual so if it is not well-documented territory, that's what I  
get for

wandering off the map.


I see. Apparently the threading and embedding docs don't cover your
case. The docs at
http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock
and http://docs.python.org/extending/embedding.html should explain how
and when to initialize Python threads. Please report a documentation  
bug at

http://bugs.python.org/.


I read that several times and eventually got my code working. I  
wouldn't say that the documentation didn't cover my case (implementing  
a callback). I'd say that it doesn't cover *any* cases in particular.  
It's more like a list of tools for manipulating the GIL and thread  
state and an explanation of the need for them rather than a tutorial  
on how to use them. The latter is what I needed, but as I said, what  
I'm doing is atypical and I think it is reasonable to expect thin  
documentation on atypical situations.



PS: I know a great way to learn more about Python's internal threading
CAPI: fix your code, test it and attach a doc patch to your bug  
report.

*hint* :)


I will file a bug on a least one specific point which is that  
PyGILState_Ensure() acquires the GIL and PyGILState_Release() appears  
to release it; the latter point is undocumented.


Cheers
Philip
--
http://mail.python.org/mailman/listinfo/python-list


Uploading big files wit cherrypy

2009-02-10 Thread Farsheed Ashouri
I use this code to upload using cherrypy:
#Code Start==
class NoteServer(object):
_cp_config = { 'tools.sessions.on': True }

def index(self):
return """


filename: 



Pars Studios, 2009


"""
#~ return compose().run()
index.exposed = True
def upload(self, myFile):
out = """

myFile length: %s
myFile filename: %s
myFile mime-type: %s

"""

# Although this just counts the file length, it demonstrates
# how to read large files in chunks instead of all at once.
# CherryPy uses Python's cgi module to read the uploaded file
# into a temporary file; myFile.file.read reads from that.
size = 0
allData=''
while True:
data = myFile.file.read(8192)
allData+=data
if not data:
break
size += len(data)
savedFile=open(myFile.filename, 'wb')
savedFile.write(allData)
savedFile.close()
return out % (size, myFile.filename, myFile.type)
#~ return allData
upload.exposed = True
#Code End

But I couldn't upload files bigger than 100Mb.
Why and what is workaround?

Thanks in advanced.
--
http://mail.python.org/mailman/listinfo/python-list


Re: STMP, mail, sender-from, to-bcc-addr

2009-02-10 Thread Roel Schroeven
durumdara schreef:
> Hi!
> 
> I wanna ask that have anyone some experience with email.msg and smtplib?
> 
> The email message and smtp.send already have "sender/from" and 
> "recip/addr to".
> Possible the smtp components does not uses the email tags if I not 
> define them only in the message?

smtplib.SMTP.sendmail() does not look in the message to find the sender
or recipients; it only uses the parameters you pass.

> Can I do same thing as in GMAIL that the mail does not have TO, only BCC 
> tags/recipients, and no one of the recipients who knows about the each 
> others?

Include the BCC-recipients in the call to sendmail(), but don't put them
in the email message itself. Include TO-recipients in both. In other
words, what you put in the TO-header is what all recipients will see;
what you pass to sendmail() is what recipients the mail will be send to.
Simple example (not tested):

from_addr = '[email protected]'
to_addr = ['[email protected]', '[email protected]']
bcc_addr = ['[email protected]', '[email protected]']

msg = """From: %s
To: %s
Subject: test

hello
""" % (from_addr, ', '.join(to_addr))

smtp = smtplib.SMTP(...)
smtp.sendmail(from_addr, to_addr + bcc_addr, msg)


-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Marc 'BlackJack' Rintsch
On Tue, 10 Feb 2009 02:11:10 -0800, Michele Simionato wrote:

> Unfortunately there is no good solution. If you have a single
> inheritance hierarchy and you do not use super, you make it impossible
> for users of your hierarchy to subclass it by using multiple
> inheritance in a cooperative way (this is not polite).

So I'm impolite.  :-)  I'm using multiple inheritance only for mixin 
classes and even that quite seldom.  No `super()` in my code.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using paramiko rsa key

2009-02-10 Thread loial
Can anyone be a little more helpful than Tino?

I have generated the key file as follows on windows and ftp'd the
id_rsa.pub file to the .ssh directory on the server and renamed to
authorized_keys


import paramiko


key = paramiko.RSAKey.generate(2048)

key.write_private_key_file('Z:/id_rsa')
file = open('Z:/id_rsa.pub','w')
file.write("ssh-rsa " +key.get_base64())
file.close()

But when I try to connect as follows I get an authentication failed
error.


import paramiko

paramiko.util.log_to_file('demo_sftp.log')

try:
try:
key = paramiko.RSAKey.from_private_key_file("Z:/id_rsa") #the
generated private key
except Exception, e:
print str(e)
t = paramiko.Transport(('10.5.1.15', 22))
print "here"
t.start_client()
t.auth_publickey('prod2',key)

if t.is_authenticated():
print "Got it!"
sftp = paramiko.SFTPClient.from_transport(t)
dirlist = sftp.listdir('.')
print "Dirlist:", dirlist
t.close()
except Exception, e:
print str(e)
t.close()



--
http://mail.python.org/mailman/listinfo/python-list


Re: how to find out vesion of a python module

2009-02-10 Thread Martin
Hi,

2009/2/10 Atishay :
> Now the point is, how do I avoid setting LD_LIBRARY_PATH everytime for
> python? I know I can write a bash script, but I am sure python would
> have some feature that I can tweak to make it work.

On debian you can modify

 * /etc/ld.so.conf and/or
 * /etc/ld.so.conf.d/

to include the path you need.

hth
martin

-- 
http://soup.alt.delete.co.at
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
--
http://mail.python.org/mailman/listinfo/python-list


Change in cgi handling of POST requests

2009-02-10 Thread Mac
We just upgraded Python to 2.6 on some of our servers and a number of
our CGI scripts broke because the cgi module has changed the way it
handles POST requests.  When the 'action' attribute was not present in
the form element on an HTML page the module behaved as if the value of
the attribute was the URL which brought the user to the page with the
form, but without the query (?x=y...) part.  Now FieldStorage.getvalue
() is giving the script a list of two copies of the value for some of
the parameters (folding in the parameters from the previous request)
instead of the single string it used to return for each.  I searched
this newsgroup looking for a discussion of the proposal to impose this
change of behavior, and perhaps I wasn't using the right phrases in my
search, but I didn't find anything.  I see that Perl still behaves the
way pre-2.6 Python used to (not that I view that as a reason for
anything).  We'll work around the breakage by explicitly setting the
'action' attribute everywhere, of course, but I usually see some
discussion (often heated) of the impact of behavior changes on
existing software when something like this is in the works.  Did I
miss it?

I also noted that the module is making some deprecated use of the
BaseException class.

Cheers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Import without executing module

2009-02-10 Thread rdmurray
Lie Ryan  wrote:
> On Tue, 03 Feb 2009 20:08:34 -0800, Stephen Hansen wrote:
> 
> > There is no need to try to make sure something is
> > executed/compiled only once in Python like you may want to do in C.
> > Every module is only ever compiled once: if you import it ten times in
> > ten different places only the first will compile and execute the code,
> > the rest of the calls will return that original module again.
> 
> 
> If you import a module, it will be recompiled only if the module changes 
> from the precompiled .pyc/.pyo. OTOH, if you run a module, it will be 
> recompiled every time even if there is no change.
> 

As long as we are nitpicking, and trying to clarify things for a new
Python userlet me give it a try.  By doing this I get to find out
if I really understand it as well as I think I do :)

If a file is run as a script ('python somefile.py', or shebang magic on
unix or the equivalent on other OSes), then the code is compiled/executed
each time that is done.  If a module is imported (or something is imported
from a module), then the _first time_ during a given run of the python
interpreter that such an import is done, the timestamp of the .py file
(if it exists) is compared to the timestamp of the .pyc/.pyo file, and
if the .py is newer, the .py file is compiled to byte code, the resulting
byte code is written to the .pyc (or .pyo), and the byte code is executed.
If the .py file is older, then the saved byte code is loaded and executed.
It is the execution of the byte code that creates the module's namespace
(a collection of names pointing to objects).  This namespace is registered
in sys.modules under the module's name.  During the remainder of that
run of the python interpreter, any import statement that draws from
that module simply loads a pointer to the module's namespace (or to
objects referenced by the module's namespace if it is a 'import from')
into the local namespace.

--RDM

--
http://mail.python.org/mailman/listinfo/python-list


Re: version in setup.cfg

2009-02-10 Thread Jasiu
> I don't think so. But there are several other options:

I was afraid of that.

Thanks anyway!

Mike
--
http://mail.python.org/mailman/listinfo/python-list


Re: import wx works interactive but not from script

2009-02-10 Thread jefm
I ran the script from a command line, so it is not a file association
thing.
I do have multiple versions of Python installed on that machine. I
will uninstall them all and install a single version from clean.
Thanks for the suggestion
--
http://mail.python.org/mailman/listinfo/python-list


Re: import wx works interactive but not from script

2009-02-10 Thread Tim Golden

jefm wrote:

I ran the script from a command line, so it is not a file association
thing.


Ummm... if you ran it by just typing the script name --
c:\test\whatever.py rather than c:\pythonxx\python c:\test\whatever.py --
then it certainly could be a file association issue.


I do have multiple versions of Python installed on that machine. I
will uninstall them all and install a single version from clean.
Thanks for the suggestion


Hope it helps. Let us know how it turns out.

TJG
--
http://mail.python.org/mailman/listinfo/python-list


Tricky question about native extension packaging

2009-02-10 Thread olivierbourdon38
let's assume I (almost) have and extension available as a C file and
the setup.py and I want to generate from this single c file 2 .so
files using

cc -DOPTION1 x.c to produce x_1.so
cc -DOPTION2 x.c to produce x_2.so

and at runtime depending of my OS version either load x_1 or x_2

any (easy) way to do that and deliver the result as a single .egg
file ? What should the setup.py look like ?

Thanks for any insight

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Launcher.app on OS X

2009-02-10 Thread Benjamin Kaplan
On Tue, Feb 10, 2009 at 10:06 AM, Philip Semanchuk wrote:

>
> On Feb 9, 2009, at 10:26 PM, kpp9c wrote:
>
>  okay... for the life of me i do not see any Python Launcher.app and i
>> just installed OS X 10.5 (running 10.5.6 on intel)  and i also
>> installed the dev kit.
>>
>> Where the heck is this application?
>>
>
> Hi kp,
> I don't seem to have any such beast on my system except for the one in
> /Applications/MacPython 2.5/. Perhaps the documentation is mistaken?



It should be in there. It's in the Python framework folder instead of the
normal applications folder, and spotlight doesn't find it. Try checking
/System/Library/Frameworks/Python.framework/versions/2.5/Resources.


>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


UnitTest break on failure

2009-02-10 Thread Qian Xu
Hi All,

i am writing unit tests and have got a problem:
I want to test some code sequence like:

 self.assertEquals(testMethod1(), expected_value1);
 self.assertEquals(testMethod2(), expected_value2);

However, if the first test item is failed, no more tests will be executed.
Can I tell Python, 
1. go ahead, if a failure is occurred. 
2. stop, if an error is occurred?


Best regards,
Qian Xu
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Launcher.app on OS X

2009-02-10 Thread Philip Semanchuk


On Feb 10, 2009, at 11:49 AM, Benjamin Kaplan wrote:

On Tue, Feb 10, 2009 at 10:06 AM, Philip Semanchuk >wrote:




On Feb 9, 2009, at 10:26 PM, kpp9c wrote:

okay... for the life of me i do not see any Python Launcher.app and i

just installed OS X 10.5 (running 10.5.6 on intel)  and i also
installed the dev kit.

Where the heck is this application?



Hi kp,
I don't seem to have any such beast on my system except for the one  
in

/Applications/MacPython 2.5/. Perhaps the documentation is mistaken?




It should be in there. It's in the Python framework folder instead  
of the
normal applications folder, and spotlight doesn't find it. Try  
checking

/System/Library/Frameworks/Python.framework/versions/2.5/Resources.


Good call, you are 100% correct, with the footnote that Versions in  
that path should be capitalized.


/System/Library/Frameworks/Python.framework/Versions/2.5/Resources



--
http://mail.python.org/mailman/listinfo/python-list


Re: Using paramiko rsa key

2009-02-10 Thread Martin P. Hellwig

loial wrote:

Can anyone be a little more helpful than Tino?


I'll do some freebie hints :-)
What I would do is try first whether key authentication works at all, 
for example following a tutorial like 
http://the.earth.li/~sgtatham/putty/0.53b/htmldoc/Chapter8.html


And if that works translate it to the relevant python code.

--
mph
--
http://mail.python.org/mailman/listinfo/python-list


Re: what IDE is the best to write python?

2009-02-10 Thread Aahz
In article ,
  wrote:
>Quoth [email protected] (Aahz):
>> In article ,
>> Thorsten Kampe   wrote:
>>>* Aahz (2 Feb 2009 09:29:43 -0800)
 
 Polarized sunglasses don't work too well with LCD monitors
>>>
>>>Well, the answer to your issue with syntax highlighting is to use a 
>>>/decent/ highlighting colour scheme. Don't use that all 
>>>purple/red/green/yellow/blue one. That's for psychedelic trips.
>>>
>>>Use a decent colour scheme for adults and you will see that you will 
>>>benefit from syntax highlighting.
>> 
>> Then I have the problem of copying around the syntax highlighting
>> configuration to every computer I use.
>
>Well, _that's_ easy to fix.  I have a little bash script called
>'synchome' that uses rsync to update the home directory on any of the
>remote machines on which I work.  I've had to install rsync on one or
>two of the boxes, but that's a useful thing to do anyway.
>
>(Granted, I still have a couple bugs to work out, where I haven't taken
>the time to conditionalize things properly for some of the more exotic
>machine configurations, but hey, if I spend more time on those machines
>I'll get around to it...)

The need to conditionalize for different environments is the main reason
I haven't bothered, combined with the need to spend time working out a
decent color scheme I'm happy with.  I've been working this way (plain
vi) for more than twenty years and I don't see much point fixing what
ain't b0rken.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Logging in Python

2009-02-10 Thread aha
Hello All,

I have an application where logging may need to be configured in
multiple places.  I've used the Python Logging Framework for sometime,
but I'm still not sure how to test if logging has configured.  For
example, I have modules A, B, and C.

Below is some pseudo code...
moduleA

class A(object):
  def __init__(self):
...

startLogging(config):
  # Configure logging
  # global logger
  ...

moduleB
import moduleA
from myconfig import MyConfig
class B(object):
  def __init__(self):
# self.config = MyConfig()
# if logging has started [HOW DO YOU DO THIS?]
#   self.logger = logging.getLogger("moduleB")
# else
#   self.logger = moduleA.startLogging(self.config)
# moduleA.startLogging
...

Where I need help is determining if a logger has already been
configured.  Any advice?

Aquil
--
http://mail.python.org/mailman/listinfo/python-list


Can urllib check path exists on server?

2009-02-10 Thread Muddy Coder
Hi Folks,

urllib bridges up a client to a server, it works fine. I wonder: is
there a method that can check the existence of a file in the server
side? We can check such an existence on local filesystem by using
os.path.exists(), can I do such a check on server? For example,
http://somedomain.com/foo/bar.jpg is residing in a hosting server, can
I use urllib to check if bar.jpg file existing or not? Thanks!

Muddy Coder
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3D CAD -- need collaborators, or just brave souls :)

2009-02-10 Thread Mike C. Fletcher

rantingrick wrote:
...

It has long been my dream to create an open source 3D CAD program and
i am starting to crawl my way into the first steps. I now believe i am
ready to start this endeavor and i am currently looking for fellow
Python programmers (no matter what skill level) to get started
brainstorming this design.
  

I'm certainly willing to help with brainstorming...

Of course Python will limit the speed here, but at this point i want
to get a template up and running. Speed does not matter at this point,
and optimizations can come along later as i am sure a few complete re-
writes are inevitable :)
  
Simple CAD systems without shading/texturing shouldn't have any real 
performance issues under Python.  We had 3D CAD back in 1993 sufficient 
to build reasonably complex environments when I was in architecture.  
Python's only about 10x slower than C, and if you dump large C-level 
arrays into the graphics card your performance can be quite reasonable.  
If you have a visit @ every face/line for every refresh you'll spend all 
your time in the scenegraph traversal.

There will need to be mouse picking as i see this application as a
very interactive environment. Of course in the beginning all
interaction will most likely be in a command line type manner until
the functionality can be worked out.
  
Mouse picking is pretty easy, you can either use simple ray-intersection 
on your bounding-box hierarchy (easiest/fastest for CAD-type structures) 
or render-pass based stuff (if you have lots of organic shapes that will 
show through each other a lot and you want to be able to click on the 
thing "peeking through" behind another thing.  Both are very well 
documented and easy/fast to implement if/when your scenegraph is 
tracking bounding volumes.

There will need to be a hierarchy of instancing and grouping within
the model to facilitate easy transformation of entities within the
model.
  

Transform and Group nodes are definitely a good idea, as are "USE" nodes.

I am not too worried about any sort of texturing at this point. I want
to squeeze as much speed as possible and prettiness will come in due
course. I also have no plans for layering, or multiple scenes at this
time. Simple functionality is the end game here.
  

Fair enough.

#-- Entities --#
 face
 line-segment
  
That's pretty low-level.  You may want to work with "meshes" or the 
like, so that you select the mesh, then modify the faces/vertices/edges 
(a-la 3DSMax/Maya), particularly where you want faces to share 
coordinates.  Just a thought.

#-- Hierarchy --#
 Entity (one face, or line-segment)
  
Again, seems like you'd want something a little less soup-of-lines-ish, 
but then that's a 3D Modeler bias, rather than a CAD bias (where often 
it really is just a soup of lines).

 Group (contained of multiple entities that can be translated,
rotated, scaled as one)
  

Transform node.

 Instance (component definition)
  
Node with DEF + USE's node instance.  Or, if you mean a reusable, 
parameterized node, a PROTO definition and PROTO-using nodes.

#-- Tools --#
 line
 rect
 circle
 arc
  
You'll want mechanisms to define the current coordinate system as well 
(think AutoCAD "UCS") so that you can precisely align the work you are 
doing without needing to calculate cos/sin/tan for everything.  That is, 
your rotation/translation/scale should allow you to draw *within* the 
resulting Transform.  You'll likely also want to be able to translate 
objects to/from Transform spaces (i.e. reparent without moving).


Also (from my many-year-old recollection of doing CAD in architecture):

   * tan (when you want to draw lines tangential to a circle/arc and
 then trim)
   * chamfer/fillet (easy to code and pretty darn useful for a lot of
 detail drawings)
   * copy
   * align
   * delete/erase
   * hide/show hidden edges
   * mirror/mirror3d (used it all the time)
   * text (pretty important for CAD work)
   * snap control (critically important IMO)
   * polyline/polygon (or tools to combine lines/arcs into polygons and
 close the result for e.g. extrusion)
   * splines/nurbs or other high-order surfaces (eventually)
   * boolean operators (eventually, use a library for this unless you
 really want to learn, and even then, do it yourself and then use a
 library)


 select
  

Critical to get that right to make it usable.

 rotation
 translation
 scale
  
I'd suggest a Maya-like control for this as far as the GUI goes, put 
snaps on it, but make a single widget that lets you 
rotate/translate/scale.  You'll also want such things as 
scale-this-line-to-be-this-size rescales (scale, pick two points, pick 
two other points, scale is the relative length of the two points)...

 extrusion along path
  
Available in GLE extensions (nodes available too).  Also want "revolve" 
(extrude around a path, which may be a point).  Depending on your model, 
you may want to allow for converting extrusions to faces in order to 
allow tweaking the resu

Can urllib check path exists on server?

2009-02-10 Thread rdmurray
Muddy Coder  wrote:
> urllib bridges up a client to a server, it works fine. I wonder: is
> there a method that can check the existence of a file in the server
> side? We can check such an existence on local filesystem by using
> os.path.exists(), can I do such a check on server? For example,
> http://somedomain.com/foo/bar.jpg is residing in a hosting server, can
> I use urllib to check if bar.jpg file existing or not? Thanks!

urllib implements the http protocol for http URLs, so you can only do
what the http protocol allows.  Thus if http://somedomain.com/foo/bar.jpg
is a valid URL on that server, you can do a urlopen, and then check
the 'getcode' method on the returned object to see if you got a '404'
(not found) code back.

--RDM

--
http://mail.python.org/mailman/listinfo/python-list


Re: what IDE is the best to write python?

2009-02-10 Thread rdmurray
[email protected] (Aahz) wrote:
> In article ,
>   wrote:
> >Quoth [email protected] (Aahz):
> >> Then I have the problem of copying around the syntax highlighting
> >> configuration to every computer I use.
> >
> >Well, _that's_ easy to fix.  I have a little bash script called
> >'synchome' that uses rsync to update the home directory on any of the
> >remote machines on which I work.  I've had to install rsync on one or
> >two of the boxes, but that's a useful thing to do anyway.
> >
> >(Granted, I still have a couple bugs to work out, where I haven't taken
> >the time to conditionalize things properly for some of the more exotic
> >machine configurations, but hey, if I spend more time on those machines
> >I'll get around to it...)
> 
> The need to conditionalize for different environments is the main reason
> I haven't bothered, combined with the need to spend time working out a
> decent color scheme I'm happy with.  I've been working this way (plain
> vi) for more than twenty years and I don't see much point fixing what
> ain't b0rken.

I did the conditionalization bit by bit, and there isn't much of it
since I can install my "standard environment" (zsh, screen, vim) on
almost all the boxes on which I work.

I was as you are on colorization until about three months ago.  Then I
figured out how to get 256 colors in my xterms and found 'desert.vim',
which works for me (nice gentle colors).  Now I'm a happy user of
colorization, and have even written a colorizor for a file whose syntax
I defined, that helps me avoid making stupid typos in said file, that
I used to make far too often.  In other words, the benefits tipped over
into outweighing the costs for me just recently...

--RDM

--
http://mail.python.org/mailman/listinfo/python-list


python3 tutorial for newbie

2009-02-10 Thread Gary Wood
Can someone recommend a good tutorial for Python 3, ideally that has tasks or 
assignments at the end of each chapter. 
Please,
--
http://mail.python.org/mailman/listinfo/python-list


Re: generator object or 'send' method?

2009-02-10 Thread Aaron Brady
On Feb 10, 6:30 am, "andrew cooke"  wrote:
> steven probably knows this, but to flag the issue for people who are
> looking at generators/coroutines for the first time: there's a little
> "gotcha" about exactly how the two sides of the conversation are
> synchronized.  in simple terms: send also receives.
>
> unfortunately the example steven gave doesn't really show this, so i've
> modified it below.  you can now see that the first next() after .send()
> receives 2, not 1.  note that i am using python 3, so the .next() method
> is .__next__() (the asymmetry between next and send seems odd to me, but
> there you go).
>
> (in a sense this is completely logical, but if you're used to the
> asynchronous way the internet works, it can seem unintuitive)
>
> how to handle this was one of the things the original post was asking
> about (if i understood correctly).
>
> >>> def gen(n):
>
> ...   while True:
> ...     obj = yield n
> ...     n += 1
> ...     if obj is not None: n = obj
> ...>>> g = gen(5)
> >>> next(g)
> 5
> >>> g.__next__()
> 6
> >>> g.send(1)
> 1
> >>> next(g)
>
> 2
>
> andrew
>
> Steven D'Aprano wrote:
> > On Tue, 10 Feb 2009 05:28:26 +, John O'Hagan wrote:
> >> I would love to see a simple code example of this if you have one; I've
> >> been wanting to do this but couldn't even get started.
>
> > Is this too simple?
>
>  def gen(n):
> > ...     while True:
> > ...             obj = yield n
> > ...             if obj is not None: n = obj
> > ...
>  g = gen(5)
>  g.next()
> > 5
>  g.next()
> > 5
>  g.send(12)
> > 12
>  g.next()
> > 12
>
>

I guess a generator that counts, but skips K numbers, where K can be
varied.  For instance, you initialize it with N, the starting number,
and K, the jump size.  Then, you can change either one later on.
(Unproduced.)

>>> j= jumper( N= 1, K= 1 )
>>> next( j )
1
>>> next( j )
2
>>> j.send( K= 3 )
5
>>> next( j )
8

However, if in the caller, the 'send' and 'next' come from two
different places, then your 'send' "eats" one of your 'next's, and the
'next' code just receives 1..2..8.

The above code isn't legal (or practical), due to the 'K=3' in send.
You could do 'j.send( dict( K= 3 ) )', but you can't do 'locals
().update( result )' in your generator, unfortunately.  So you have a
big switch statement there.

One solution: You could always query a dictionary for your variables,
and do 'my_locals.update( result )', and 'my_locals[ "K" ]' for a
variable.  Then you just need some sort of collector generator to go
around the first one, and duplicate the value 'send' returns, before
going back to 'next'.  (Unproduced.)

>>> j= repeat_on_send( jumper( N= 1, K= 1 ) )
>>> next( j )
1
>>> next( j )
2
>>> j.send( dict( K= 3 ) )
5
>>> next( j )
5
>>> next( j )
8

Two solution (er, solution two), would be to give a generator object
access.  Unfortunately, generators have no 'gi_dict' attribute, so
arbitrary attributes aren't possible.  So you have to be clever.
(Unproduced.)

>>> @gen_dict
>>> def jumper...
...
>>> j= jumper( N= 1, K= 1 )
>>> next( j )
1
>>> next( j )
2
>>> j.K= 3
>>> next( j )
5
>>> next( j )
8

This gets two birds with one stone, but is it possible?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using paramiko rsa key

2009-02-10 Thread loial
On 10 Feb, 17:08, "Martin P. Hellwig" 
wrote:
> loial wrote:
> > Can anyone be a little more helpful than Tino?
>
> 
> I'll do some freebie hints :-)
> What I would do is try first whether key authentication works at all,
> for example following a tutorial 
> likehttp://the.earth.li/~sgtatham/putty/0.53b/htmldoc/Chapter8.html
>
> And if that works translate it to the relevant python code.
>
> --
> mph

Thanks..I'll try that first
--
http://mail.python.org/mailman/listinfo/python-list


Re: UnitTest break on failure

2009-02-10 Thread Joe Riopel
On Tue, Feb 10, 2009 at 11:48 AM, Qian Xu  wrote:
>  self.assertEquals(testMethod1(), expected_value1);
>  self.assertEquals(testMethod2(), expected_value2);
>
> However, if the first test item is failed, no more tests will be executed.
> Can I tell Python,
> 1. go ahead, if a failure is occurred.
> 2. stop, if an error is occurred?

Typically you would have a different test for two different methods,
one for each method.
--
http://mail.python.org/mailman/listinfo/python-list


getopt index out of range

2009-02-10 Thread Matthew Sacks
Hi List,
I am getting an index out of range error when trying to parse with getopt.
Probably something simple. Any suggestions are appreciated

optlist, args = getopt.getopt(sys.argv[1:], 'h', ['connectPassword=',
'adminServerURL=', 'action=', 'targets=', 'appDir='])


#Assign Opts
connectPassword = optlist[0][1]
adminServerURL = optlist[1][1]
action = optlist[2][1]
targets = optlist[3][1]
appDir = optlist[4][1]

#this statement never gets executed
print "Args: " + connectPassword + " " + adminServerURL + " " + action
+ " " + targets + " " + appDir

  File "/home/msacks/untitled4.py", line 23, in ?
IndexError: index out of range: 0

TIA
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen - file like object from stdout=PIPE

2009-02-10 Thread Aahz
In article <[email protected]>,
Helmut Jarausch   wrote:
>
>These pipes are exposed as file-like objects which can be accessed via
>the stdin, stdout or stderr (resp.) attributes of an object of class
>subprocess.Popen .

Please file a doc request at bugs.python.org
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


bool evaluations of generators vs lists

2009-02-10 Thread Josh Dukes
quite simply...what???

In [108]: bool([ x for x in range(10) if False ])
Out[108]: False

In [109]: bool( x for x in range(10) if False )
Out[109]: True

Why do these two evaluate differently? I was expecting that they would
evaluate the same but the generator would return true *as soon as the
first value is detected*. I'd really expect it to act more like...

def has_values(g):
 for i in g:
 return True
 return False

So what's going on here? Am I using the wrong function or is this
actually just a bug?

-- 

Josh Dukes
MicroVu IT Department
--
http://mail.python.org/mailman/listinfo/python-list


Python DLL's for C++?

2009-02-10 Thread Geert Vancompernolle

Hi,

Is it possible to write DLL's in Python for applications that only 
provide C++ interfaces?  Example: NotePad++ is extendible by writing C++ 
DLL's which can call the NotePad++ interfaces.


I wonder if those DLL's also can be written in Python, which in the end 
calls the C++ interfaces of NotePad++...


--
Best rgds,

Geert


*Use EcoCho : environmentally friendly search the 
internet!*

--
http://mail.python.org/mailman/listinfo/python-list


Re: UnitTest break on failure

2009-02-10 Thread Scott David Daniels

Qian Xu wrote:

i am writing unit tests and have got a problem:
I want to test some code sequence like:

 self.assertEquals(testMethod1(), expected_value1);
 self.assertEquals(testMethod2(), expected_value2);

However, if the first test item is failed, no more tests will be executed.
Can I tell Python, 
1. go ahead, if a failure is occurred. 
2. stop, if an error is occurred?


Well, each test should be independent, so generally you are talking
about multiple tests.  If you really want a test to see if you get
through a sequence in a single test:
import unittest
...
class MyTest(unittest.TestCase):

def test_multi_step(self):
expectations = [(expected_value1, testMethod1),
(expected_value2, testMethod2),
(final_expected, another_test, arg1, arg2)]
try:
for step, ops in enumerate(expectations):
self.assertEquals(ops[0], ops[1](*ops[2:]))
except Exception, why:
raise ValueError('Step %s Failed: %s' % (step, why))
# here the test passed.
...
if __name__ == '__main__':
unittest.main()

Note this gives you less information (the traceback doesn't go down
to the actual error), but it shows you what step failed.

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Using TK and the canvas.

2009-02-10 Thread Kalibr
Hi all. I'm experimenting with making a UI for a little (well, not
quite) script that basically draws up a tech tree to some skills from
my favorite game. What I'm aiming for looks a little like this site
here:(apologies if I'm not supposed to direct link)
http://www.anderkoo.com/uploads/271/605/NewTechTree.jpg.

Anyway, I made a script which reads data from several files and saves
the data into an array of skill objects, here's what it looks like:

#define the class
class skill:
def __init__(self, name, description, a1, a2, rank, prereq):
self.name = name #string (example is "Anchoring")
self.desc = description #string (example is "blah blah blah")
self.a1 = a1   #string with attributes affecting the skill
(Example is "Int")
self.a2 = a2   #string
self.rank = rank   #how hard it is to train (example is "5")
(too lazy to convert to int
self.prereq = prereq  #any prerequsites (an array of ["skill",
"levelrequired"])

#the trained level already
self.skillowned = "0" #we change this later on when we access
another file :)

Finally, I set up a class which accepts a parent (normally root), and
the skill in question.
here it is:

class SkillInfo:
def __init__(self, parent, skill):
container = Frame(parent)
container.pack()

#we make this the top frame for some reason
labelcontainer = Frame(container, height=50, width=50)
labelcontainer.pack(side=LEFT, fill=BOTH, expand=YES)

desccont = Frame(container, height=50, width=50) #the
description content
desccont.pack(side=LEFT, fill=BOTH, expand=YES)

#make a name label
Label(labelcontainer, text=skill.name, wraplength=100).pack
(side=TOP, anchor=W)

#print the level buttons
for i in range(1, 6):
button = Button(labelcontainer)
button["text"] = "Level", i
if int(skill.skillowned) >= i:
button["background"] = "green"
button["width"] = 10
else:
button["background"] = "red"
button["width"] = 10
button.pack(anchor=W)

Label(desccont, text=("\n"+skill.desc), wraplength=100).pack()

Now I know all I have to do is set the SkillInfos parent to a canvas,
but how would I arrange and draw the lines? Thanks all :)
--
http://mail.python.org/mailman/listinfo/python-list


Introduction to Python, Washington DC, March 3-5

2009-02-10 Thread Steve Holden
Holden Web is pleased to announce its next public introductory Python
class in the Washington, DC area on March 3-5. To enroll, or to learn
more about the class please visit:

  http://holdenweb.com/py/training/

If you have multiple students requiring training you may be interested
to know that this course can also be presented on-site.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

--
http://mail.python.org/mailman/listinfo/python-list


Re: bool evaluations of generators vs lists

2009-02-10 Thread Chris Rebert
On Tue, Feb 10, 2009 at 11:15 AM, Josh Dukes  wrote:
> quite simply...what???
>
> In [108]: bool([ x for x in range(10) if False ])
> Out[108]: False

This evaluates the list comprehension and creates an empty list, which
is considered boolean False by Python.

> In [109]: bool( x for x in range(10) if False )
> Out[109]: True

Whereas this creates a /generator object/, whose inner expression is
*not evaluated until specifically required* (e.g. by for-looping over
the generator object). Generators don't have a specially defined
truthiness critera (it's impossible to define generally -- consider
something like `x for x in all_integers if f(x)`, for a complicated
f(x), which would require a solution to the halting problem to know in
advance if it will have a non-zero length), so they end up using the
default behavior for objects with otherwise undefined boolean truth,
which is to consider them True.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: bool evaluations of generators vs lists

2009-02-10 Thread Albert Hopkins
On Tue, 2009-02-10 at 11:15 -0800, Josh Dukes wrote:
> quite simply...what???
> 
> In [108]: bool([ x for x in range(10) if False ])
> Out[108]: False
> 
> In [109]: bool( x for x in range(10) if False )
> Out[109]: True
> 
> Why do these two evaluate differently? I was expecting that they would
> evaluate the same but the generator would return true *as soon as the
> first value is detected*. I'd really expect it to act more like...

The first example is a list.  A list of length 0 evaluates to False.

The second example returns a generator object.  A generator object
apparently evaluates to true.  Your example is not iterating of their
values of the generator, but evaluating bool(generator_object) itself.
My feeling is that bool(generator_object) is ambiguous so shouldn't be
used to begin with.

In both examples, bool() doesn't actually iterate over the arguments.
Maybe that's what confused you.

Instead look at this:

>>> type([x for x in range(10) if False ])

>>> type((x for x in range(10) if False ))


> def has_values(g):
>  for i in g:
>  return True
>  return False
> 
> So what's going on here? Am I using the wrong function or is this
> actually just a bug?

bool != has_values.  Check python.org for how Python determines the
"truthiness" of an object. Generally speaking the following evaluate to
False:

  * None 
  * False 
  * zero of any numeric type, for example, 0, 0L, 0.0, 0j. 
  * any empty sequence, for example, '', (), []. 
  * any empty mapping, for example, {}. 
  * instances of user-defined classes, if the class defines a
__nonzero__() or __len__() method, when that method returns the
integer zero or bool value False.

All other values are considered true -- so objects of many types are
always true.


--
http://mail.python.org/mailman/listinfo/python-list


ANN: Python 2.6 Quick Reference available

2009-02-10 Thread Richard Gruet

The Python 2.6 Quick Reference is available in HTML and PDF formats at 
http://rgruet.free.fr/#QuickRef.

This time I was helped by Josh Stone for the update.

As usual, your feedback is welcome (pqr at rgruet.net).

Cheers,

Richard Gruet
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Benjamin Peterson
Marc 'BlackJack' Rintsch  gmx.net> writes:

> 
> On Tue, 10 Feb 2009 02:02:43 +, Benjamin Peterson wrote:
> 
> > Jean-Paul Calderone  divmod.com> writes:
> >> Consider whether you really need to use super().
> >> 
> >> http://fuhm.net/super-harmful/
> > 
> > This article chiefly deals with super()'s harm in multiple inteheritance
> > situations. For the simple case, though, like that presented by the OP,
> > I believe super() is perfect.
> 
> But for the simple cases it is unnecessary because it was invented to 
> deal with multiple inheritance problems.

super() is great for single inheritance because it furthers the DRY principle
(base classes are not scattered through the code), and rather ugly use of
unbound methods. 




--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Jean-Paul Calderone

On Tue, 10 Feb 2009 19:40:56 + (UTC), Benjamin Peterson 
 wrote:

Marc 'BlackJack' Rintsch  gmx.net> writes:



On Tue, 10 Feb 2009 02:02:43 +, Benjamin Peterson wrote:

> Jean-Paul Calderone  divmod.com> writes:
>> Consider whether you really need to use super().
>>
>> http://fuhm.net/super-harmful/
>
> This article chiefly deals with super()'s harm in multiple inteheritance
> situations. For the simple case, though, like that presented by the OP,
> I believe super() is perfect.

But for the simple cases it is unnecessary because it was invented to
deal with multiple inheritance problems.


super() is great for single inheritance because it furthers the DRY principle
(base classes are not scattered through the code), and rather ugly use of
unbound methods.


It replaces one kind of repetition with another.  I think each kind is
about as unpleasant.  Has anyone gathered any data on the frequency of
changes of base classes as compared to the frequency of classes being
renamed?  I don't think either happens very often, but it might be
interesting to see some numbers.

Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tricky question about native extension packaging

2009-02-10 Thread Chris Rebert
On Tue, Feb 10, 2009 at 8:42 AM,   wrote:
> let's assume I (almost) have and extension available as a C file and
> the setup.py and I want to generate from this single c file 2 .so
> files using
>
> cc -DOPTION1 x.c to produce x_1.so
> cc -DOPTION2 x.c to produce x_2.so
>
> and at runtime depending of my OS version either load x_1 or x_2

I don't know about the setup.py part of your question, but as for
choosing between 2 modules at runtime:

#file foo.py
#assuming 'foo' is the desired name of the module
from sys import platform
SUN = 'sunos5'
LINUX = 'linux2'
WIN = 'win32'

if platform == SUN:
from x_1 import *
elif platform == LINUX:
from x_2 import *
elif platform == WIN:
from x_1 import *
else:
raise RuntimeError, "Unknown/unsupported platform"


Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Working with propositional formulae in Python

2009-02-10 Thread nnp
Hey,

I'm currently working with propositional boolean formulae of the type
'A & (b -> c)' (for example). I was wondering if anybody knows of a
Python library to create parse trees and convert such formulae to
conjunctive, disjunctive and Tseitin normal forms?

Cheers,
nnp

-- 
http://www.unprotectedhex.com
http://www.smashthestack.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using TK and the canvas.

2009-02-10 Thread r
On Feb 10, 1:27 pm, Kalibr  wrote:
[snip]
> Now I know all I have to do is set the SkillInfos parent to a canvas,
> but how would I arrange and draw the lines? Thanks all :)

You should really check out wxPython, there is support for just this
type of thing. of course you could do this with Tkinter, but just
thinking about it makes my head hurt :).
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Daniel Fetchinson
On 2/9/09, Gabriel Genellina  wrote:
> En Mon, 09 Feb 2009 23:34:05 -0200, Daniel Fetchinson
>  escribió:
>
>> Hello. I've been scouring the web looking for something to clear up a
>> little confusion about the use of "super()" but haven't found
>> anything
>> that really helps. Here's my simple example:
>>
>> [snip]
>>
>> "super(Child,self).__init__(filePath)
>> TypeError: super() argument 1 must be type, not classobj"
>>
>> What have I done wrong? Thanks in advance for any help.
>
> Consider whether you really need to use super().
>
> http://fuhm.net/super-harmful/

 Did you actually read that article, understood it, went through the
 tons of responses from python-dev team members, including Guido
>>>
>>> Yes.  Why the knee-jerk reaction?
>>
>> Because throwing around that link carries about the same amount of
>> information as "perl is better than python", "my IDE is better than
>> yours", "vim rulez!", "emacs is cooler than vim", etc, etc.
>
> Not at all. It contains accurate and valuable information that isn't
> available elsewhere.

But does not contain other valuable information which would demystify
super. If only this source is shown to a person who wants to learn the
proper usage of super, the impression he/she gets will be distorted.

Example: 1. somebody asks about threading 2. reply comes: there is a
GIL! you can't do real threading. Now this reply might be technically
more-or-less correct, it is misleading and does not help the poster.
An informed discussion of the various solutions that does not involve
a rant about the GIL would be very useful though.

>>> I simply pointed out a resource which
>>> might be helpful to someone trying to learn to use super.
>>
>> It will certainly not be helpful to anyone trying to learn the usage
>> of super. The person who wrote that essay is simply misunderstanding
>> the concept, as has been explained countless times by the python dev
>> team. Hence, it only increases confusion, adds to the noise and
>> spreads false alarm.
>
> AFAIK, all facts appearing in said article are still true (except for 3.x
> which uses a shorter form). If super usage had been clearly documented in
> the first place, this had not happened.
> Perhaps you could point us to some resource explaining how is super
> supposed to be used correctly?
> And of those giving explanations in python-dev, nobody cared to add a
> single word to the Python documentation for years.

You might want to start with

http://www.artima.com/weblogs/viewpost.jsp?thread=236275

You are right, it's not in the documentation. But if somebody asks on
c.l.p the appropriate answer, I think, is to point to information such
as the one above, and not the misleading "harmful" essay.

>> Honestly, I don't understand how this thing got so much out of
>> control. If anyone starts an intelligent question or remark about
>> super, this essay is thrown in no matter what. Anyone can explain why?
>
> Because for a very loong time (seven years, 2001-2008) super was
> almost undocumented. The Library Reference -before release 2.6- only had a
> short paragraph, the online documentation referred (and still does) to the
> original essay by Guido introducing descriptors, which is inaccurate and
> outdated, and then the "... harmful" article was the only source of
> information available.
> Worse was the fate of packages and how they're imported: nobody "could be
> bothered to spell that out" (sic); or how import works in general, still
> barely documented (one has to dig into the PEP collection, trying to guess
> what parts are truly implemented and what parts are only a wish...)

You are right, the documentation needs some work in this regard. But
again, just because some sources are not in the documentation doesn't
mean that the most opinionated essay is the best source. A little
search turns up much more useful ones.

Cheers,
Daniel



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Super()" confusion

2009-02-10 Thread Daniel Fetchinson
> Consider whether you really need to use super().
>
> http://fuhm.net/super-harmful/

Did you actually read that article, understood it, went through the
tons of responses from python-dev team members, including Guido
>
> "Tons" of responses?

This was mentioned already, but just to repeat: one good source, for
example, apart from the python-dev list:

http://www.artima.com/weblogs/viewpost.jsp?thread=236275

> I count 16, about a third of which are written by James Knight himself
> (the author of the page you are ranting against), and of the remaining,
> about half are low-to-zero information content, e.g. Tim Peter's joke
> about renaming the page for better marketing value.
>
> It's especially telling that even Guido, the most vocal critic of the
> article, is critical of the *title* but not the content. In his first
> post, he says: "I agree with the best practices in James's
> Conclusion...", and suggested that if the article was called "Multiple
> Inheritance Pitfalls in Python" he'd be much happier.
>
>
>>> Yes.  Why the knee-jerk reaction?
>>
>> Because throwing around that link carries about the same amount of
>> information as "perl is better than python", "my IDE is better than
>> yours", "vim rulez!", "emacs is cooler than vim", etc, etc.
>
> This is clearly not the case when even the most vocal critic agrees with
> the article's recommendations.
>
>
>>> I simply pointed out a resource which might be helpful to someone
>>> trying to learn to use super.
>>
>> It will certainly not be helpful to anyone trying to learn the usage of
>> super.
>
> I've read it, and found it very useful.
>
>
>> The person who wrote that essay is simply misunderstanding the
>> concept, as has been explained countless times by the python dev team.
>
> "Countless". Is that more or less than the "tons of responses" above?
>
>
>> Hence, it only increases confusion, adds to the noise and spreads false
>> alarm.
>
> So you say.
>
>
>> Honestly, I don't understand how this thing got so much out of control.
>> If anyone starts an intelligent question or remark about super, this
>> essay is thrown in no matter what. Anyone can explain why?
>
> Because inheritance is potentially confusing. Multiple inheritance is
> even more confusing. Multiple inheritance with diamond diagrams even more
> so, and multiple inheritance with diamond diagrams and non-cooperative
> classes are simply impossible to get right.
>
> Because there are many pitfalls to inheritance in Python, and they aren't
> obvious: who on earth would imagine that calling __init__ or __new__ with
> positional arguments could be dangerous? James Knight's article is a well-
> written, understandable description of some of them, in one place and
> with a catchy title. Of course people are going to link to it.
>
> And finally, because people do wrongly get the impression that using
> super will magically make those problems go away. I know this, because I
> was one of them.
>
> (I went through the anger period, sure that Knight must be full of it.
> How could anyone suggest that Guido made a super that isn't perfect? I
> got past that once I realised just how complex inheritance actually is.
> Currently I'm in denial, writing code with super and hoping that it will
> Just Work but not pushing it too hard in case it doesn't.)
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging in Python

2009-02-10 Thread Robert Kern

On 2009-02-10 11:50, aha wrote:

Hello All,

I have an application where logging may need to be configured in
multiple places.  I've used the Python Logging Framework for sometime,
but I'm still not sure how to test if logging has configured.  For
example, I have modules A, B, and C.

Below is some pseudo code...
moduleA

class A(object):
   def __init__(self):
 ...

startLogging(config):
   # Configure logging
   # global logger
   ...

moduleB
import moduleA
from myconfig import MyConfig
class B(object):
   def __init__(self):
 # self.config = MyConfig()
 # if logging has started [HOW DO YOU DO THIS?]
 #   self.logger = logging.getLogger("moduleB")
 # else
 #   self.logger = moduleA.startLogging(self.config)
 # moduleA.startLogging
 ...

Where I need help is determining if a logger has already been
configured.  Any advice?


I just do this in every module in which I'm doing logging:

  import logging
  logger = logging.getLogger(__name__)

I configure my logging only in my main() function(s).

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python DLL's for C++?

2009-02-10 Thread Martin v. Löwis
> Is it possible to write DLL's in Python for applications that only
> provide C++ interfaces?  Example: NotePad++ is extendible by writing C++
> DLL's which can call the NotePad++ interfaces.

Not directly, no. You have to write a C++ DLL which then can delegate
all calls to it to some Python function, and likewise expose Notepad++
API to Python.

> I wonder if those DLL's also can be written in Python, which in the end
> calls the C++ interfaces of NotePad++...

The actual logic can be in Python, but you do need a C++ wrapper module.

OTOH, if Notepad++ would also support COM/ActiveX plugins, then those
could directly be written in Python (assuming the COM interfaces
supported automation).

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


How to get a return from Button?

2009-02-10 Thread Muddy Coder
Hi Folks,

I want to use a Button to trigger askopenfilename() dialog, then I can
select a file. My short code is below:


def select_file():
filenam = askopenfilename(title='Get the file:')
   return filenam

root = Tk()
Button(root, text='Select a file', command=select_file).pack()
root.mainloop()

My goal is to get the path of filenam, but the function select_file()
has nowhere to return what it selected. Can anybody help me out? I
consulted the book of Programming Python, but found no demo in this
regard. If the function has no return, command=blabla will work
nicely. I am lost in the scope.

Thanks!


Muddy Coder
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging in Python

2009-02-10 Thread Vinay Sajip
On Feb 10, 5:50 pm, aha  wrote:
> Hello All,
>
> I have an application whereloggingmay need to be configured in
> multiple places.  I've used the PythonLoggingFramework for sometime,
> but I'm still not sure how to test iflogginghas configured.  For
> example, I have modules A, B, and C.
>
> Below is some pseudo code...
> moduleA
>
> class A(object):
>   def __init__(self):
> ...
>
> startLogging(config):
>   # Configurelogging
>   # global logger
>   ...
>
> moduleB
> import moduleA
> from myconfig import MyConfig
> class B(object):
>   def __init__(self):
> # self.config = MyConfig()
> # iflogginghas started [HOW DO YOU DO THIS?]
> #   self.logger =logging.getLogger("moduleB")
> # else
> #   self.logger = moduleA.startLogging(self.config)
> # moduleA.startLogging
> ...
>
> Where I need help is determining if a logger has already been
> configured.  Any advice?
>
> Aquil

It depends upon how complicated your logging requirements are. For
example, each module can have the following code in it:

import logging

logging.basicConfig(level=logging.DEBUG, filename="/tmp/myapp.log",
filemode="w") # An example

logger = logging.getLogger(__name__)

... your code, involving logger.debug(...) statements


basicConfig() attaches a FileLogger to the root logger, so all logging
output would be routed to the file "/tmp/myapp.log" in the example.
However, basicConfig() does nothing if the root logger already has
handlers, so calling it in each module shouldn't cause problems. It's
also nice to use the module name (__name__) as the logger name.

Another pattern is to configure logging in your main module, if there
is one, and then the other modules just assume logging is configured
and log away. If there isn't a main module, have all the modules
import a common module which, when imported, configures logging how
you want it. Under normal circumstances, the import code will only run
once, so your logging only gets configured the first time the module
gets imported by any of the others.

Regards,

Vinay Sajip
--
http://mail.python.org/mailman/listinfo/python-list


Functional schmunctional...

2009-02-10 Thread r0g
I remember being forced to do a bit of functional programming in ML back
at Uni in the mid 90, the lecturers were all in a froth about it and I
must admit the code was elegant to look at. The problem was the dog slow
performance for anything half practical, especially with recursion being
the technique de jour. The HP workstations we were using were really
quite beefy for their time yet simple ML stuff would just murder the CPU
and RAM. Added to that, recursive stuff could be extremely confusing to
debug so I wrote it off as a nice idea in concept but a waste of my time
for anything practical.

So fast forward 15 years to this very afternoon... I needed a routine to
convert IP address strings to INET numbers and vice-versa and I remember
writing one a couple of years back when I first picked up Python. So I
went and dug it out.  Looking back at old code can be a bit dispiriting
though and this was no exception...

def inet2ip(n):
  p = (n/16777216)
  q = ((n-(p*16777216))/65536)
  r = ((n-((p*16777216)+(q*65536)))/256)
  s = ((n-((p*16777216)+(q*65536)+(r*256
  return str(p)+"."+str(q)+"."+str(r)+"."+str(s)

def ip2in(a):
  li = a.split('.')
  assert len(li) == 4
  a = int(li[0])*16777216
  b = int(li[1])*65536
  c = int(li[2])*256
  d = int(li[3])
  return a+b+c+d


I thought "OMG, how naive and inelegant that looks, I can do far better
than that, after all I know things like list comprehensions and
map/reduce now!".  I had also noticed over the last year or two a lot of
chatter about functional programming especially in conjunction with python.

It seems to me that procedural programming has taken quite a kicking
against the more OO and functional methodologies over the last few years
and given my nothing-but-positive experience with OO of late I was
reconsidering the strength of my old opinions on FP. Maybe it was, as my
lecturers thought, the paradigm of the future and I was being a
crotchety old stick in the mud by spurning it as slow and confusing.

With this in mind I set about applying my hard won Python knowledge and
wisdom to the rewriting of these functions, not for any particularly
practical reasons, just to see what improvements I could wreak on them
several years down the line.

The IP string to INET number was first and I decided to throw list
comprehensions at it...

def ip2inet(a):
  li = a.split('.')
  assert len(li) == 4 or len(li) == 6
  return reduce(add,[int(li[e])*(256**((len(li)-1)-e)) for e in
xrange(0,len(li))])

Now, that did made it completely unreadable but I thought, "it's pretty
much all one line now so I've gained some conciseness and at least it
should run a little faster". After all list comprehensions are often
fast aren't they? Well actually no, It runs at less than half the speed
of the previous function and now it's entirely lexically impenetrable.

Shit :-(

So far so bad... As inauspicious as these beginnings were I figured I'd
plug on anyway and try a functional approach to the INET number to IP
string function - the above experience having reinforced in me the
notion that clarity is paramount. Functional programming is all about
the clarity and elegance right?

I figured it might be worth trading a few cycles for at least,
especially as the machine I'm using here in 2009 has more RAM and CPU
grunt than whole Uni computer department did back in 1994. Not only that
I would only need to do 4 or 6 recursions in this algorithm and so I
shouldn't need to worry about the exponential inefficiency problems of
yore...

def inet2ip(n, l=[], c=4):
  if c==0: return ".".join(l)
  p = 256**( c-1 )
  l.append( str(n/p) )
  return inet2ip( n-(n/p)*p, l, c-1 )

The thing is, that's not really any clearer though is it?  I'd wager if
you didn't know already it would take you longer to figure out this
version than it would the original.  Still, "at least" I thought "it's
more concise than the last one and it scales to IPv6 far more
elegantly". I figured as long as the performance wasn't too lousy I
would keep it and so I quickly ran a little benchmark to see how much of
a performance hit I would be taking by doing so. The results for 1
iterations of each were as follows...

0.113744974136 seconds for old INET->IP method
27.744112 seconds for new INET->IP method

:-/

FFS!

It just goes to show that...

1) Thinking you're a smart arse and actually being a smart arse are two
quite different things.

2) You should always take received wisdom with a good pinch of salt.

3) People aren't exaggerating when they say Python function calls are
expensive are they!


Roger Heathcote.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a return from Button?

2009-02-10 Thread Chris Rebert
On Tue, Feb 10, 2009 at 12:21 PM, Muddy Coder  wrote:
> Hi Folks,
>
> I want to use a Button to trigger askopenfilename() dialog, then I can
> select a file. My short code is below:
>
>
> def select_file():
>filenam = askopenfilename(title='Get the file:')
>   return filenam
>
> root = Tk()
> Button(root, text='Select a file', command=select_file).pack()
> root.mainloop()
>
> My goal is to get the path of filenam, but the function select_file()
> has nowhere to return what it selected. Can anybody help me out? I
> consulted the book of Programming Python, but found no demo in this
> regard. If the function has no return, command=blabla will work
> nicely. I am lost in the scope.

The function has nowhere to return its value to (except somewhere in
the innards of Tkinter, where it's discarded), so indeed it should
*not* return. You instead need to modify some program state to hold
the would-be return value.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Change in cgi module's handling of POST requests

2009-02-10 Thread Bob Kline

[Didn't realize the mirror didn't work both ways]

We just upgraded Python to 2.6 on some of our servers and a number of our CGI 
scripts broke because the cgi module has changed the way it handles POST 
requests.  When the 'action' attribute was not present in the form element on 
an HTML page the module behaved as if the value of the attribute was the URL 
which brought the user to the page with the form, but without the query 
(?x=y...) part.  Now FieldStorage.getvalue () is giving the script a list of 
two copies of the value for some of the parameters (folding in the parameters 
from the previous request) instead of the single string it used to return for 
each.  I searched this newsgroup looking for a discussion of the proposal to 
impose this change of behavior, and perhaps I wasn't using the right phrases in 
my search, but I didn't find anything.  I see that Perl still behaves the way 
pre-2.6 Python used to (not that I view that as a reason for anything).  We'll 
work around the breakage by explicitly setting the 'action' attri
bute everywhere, of course, but I usually see some discussion (often heated) of 
the impact of behavior changes on existing software when something like this is 
in the works.  Did I miss it?

I also noted that the module is making some deprecated use of the BaseException 
class.

Cheers.



--
http://mail.python.org/mailman/listinfo/python-list


Re: bool evaluations of generators vs lists

2009-02-10 Thread Josh Dukes
> The first example is a list.  A list of length 0 evaluates to False.
> 
> The second example returns a generator object.  A generator object
> apparently evaluates to true.  Your example is not iterating of their
> values of the generator, but evaluating bool(generator_object) itself.
> My feeling is that bool(generator_object) is ambiguous so shouldn't be
> used to begin with.

I was actually aware of that (thank you, though, for trying to help).
What I was not clear on was if the boolean evaluation is a method of an
object that can be modified via operatior overloading (in the same way
+ is actually .__add__()) or not. Clearly __nonzero__ is the operator I
was curious about. Thanks for that info. 

> bool != has_values.  Check python.org for how Python determines the
> "truthiness" of an object. Generally speaking the following evaluate
> to False:
> 
>   * None 
>   * False 
>   * zero of any numeric type, for example, 0, 0L, 0.0, 0j. 
>   * any empty sequence, for example, '', (), []. 
>   * any empty mapping, for example, {}. 
>   * instances of user-defined classes, if the class defines a
> __nonzero__() or __len__() method, when that method returns
> the integer zero or bool value False.
> 
> All other values are considered true -- so objects of many types are
> always true.

The thing I don't understand is why a generator that has no iterable
values is different from an empty list. Why shouldn't bool ==
has_value?? Technically a list, a tuple, and a string are also objects
but if they lack values they're evaluated as False. It seems to me that
a generator is an object that intends to replace lists where lazy
evaluation would be more efficent. Here is one place where that's
definitely true. 
The main reason I'm interested in this is that it improves performance
immensely over boolean evaluation of large lists (as the attached code
shows). It seems to me if I could use find a good use for it in my
experimentation that someone else might also want to do the same thing
in real-world code. 

Is there another list I should be asking these questions on?

-- 

Josh Dukes
MicroVu IT Department#!/usr/bin/env python
from datetime import datetime

def has_values(g):
for i in g:
return True
return False

print "creation time"
start=datetime.now()
print len([ x for x in range(1,1) if not [ y for y in range(2,x/2) if not x%y]]),"values"
print "LC time:",datetime.now()-start

start=datetime.now()
print len([ x for x in range(1,1) if not has_values( y for y in range(2,x/2) if not x%y)]),"values"
print "GE time:",datetime.now()-start


--
http://mail.python.org/mailman/listinfo/python-list


Re: Functional schmunctional...

2009-02-10 Thread andrew cooke
r0g wrote:
> def ip2inet(a):
>   li = a.split('.')
>   assert len(li) == 4 or len(li) == 6
>   return reduce(add,[int(li[e])*(256**((len(li)-1)-e)) for e in
> xrange(0,len(li))])

what a mess.

i don't use this extreme a functional style in python (it's not really how
the language is intended to be used), but i think you can do better than
that.

how about:

from itertools import count

def ip2inet(a):
blocks = a.split('.')
assert len(blocks) in (4, 6)
return sum(map(lambda (i, n): int(i) * 256**n,
   zip(reversed(blocks), count(0

i haven't looked at the other function, but as a general comment it sounds
me like you are in such a hurry to point out fp is bad that you haven't
bothered to master it first.

andrew


--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >