Re: Memory leak in Python

2006-05-12 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, 
Serge Orlov <[EMAIL PROTECTED]> writes
>The next step is to find out what type of objects contributes to the
>growth most of all,

Shame you aren't on Windows, as Python Memory Validator does all of 
this.

>after that print several object of that type that
>didn't exist on iteration N-1 but exist on iteration N

And this, but for garbage collection generations.

Stephen
-- 
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk/software.html
Computer Consultancy, Software Development
Windows C++, Java, Assembler, Performance Analysis, Troubleshooting
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling python functions from C

2006-05-12 Thread Nigel Rowe
[EMAIL PROTECTED] wrote:

> I am a newbie to Python. I want to call python functions from C. I
> looked for examples but I couldn't get any simple one. Lets say my
> python code is :
> def add(a,b)
>  return (a+b)
> 
> I want to call add from C. Could anybody please help me? Thanks in
> advance.
> 
> R.

You might look at elmer 

Quote:
What is elmer?
Elmer is a tool which embeds a Python module into a C, C++, or Tcl   
application. The embedded Python module is used just as if it was 
written in the same language as the application itself, without 
requiring any knowledge of the Python/C API. 

Elmer generates "glue" code that embeds an interpreter for one type of 
language into an extension for another. Elmer allows function calls and  
various data types, both native and custom, to pass transparently
between the two languages. 
 

-- 
Nigel Rowe
A pox upon the spammers that make me write my address like..
rho (snail) swiftdsl (stop) com (stop) au
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads

2006-05-12 Thread placid

Dennis Lee Bieber wrote:
> On 11 May 2006 17:02:51 -0700, "placid" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
>
> > I have a thread that has a job Queue, it continuosly polls this queue
> > to see if there are any jobs for it, what i really wont to be able to
> > do is, when the queue is empty, i want the thread to pause (or more
> > technical, i want the thread to block) until the queue gets populated
> > again. Is this possible ?
> >
>   Did you read the documentation for Queue methods?

there is no need to be patronizing about this dude, im just learning
Python in my spare time, as im a Intern Software Engineer

>
>   x = q.get(true) #blocks until data is available


this is even better, thanks dude

> --
>   WulfraedDennis Lee Bieber   KD6MOG
>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/
>   (Bestiaria Support Staff:   [EMAIL PROTECTED])
>   HTTP://www.bestiaria.com/

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


Re: Decorator

2006-05-12 Thread Sybren Stuvel
Lad enlightened us with:
> I use Python 2.3.
> I have heard about decorators in Python 2.4.
> What is the decorator useful for?

A whole lot of stuff. I've used them for:
- Logging all calls to a function, including its arguments.
- Ensuring there is a database connection before the function is
  called.
- Casting the arguments to certain types before passing them to
  the function.

And there is much more possible...

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads

2006-05-12 Thread Sybren Stuvel
placid enlightened us with:
>>  Did you read the documentation for Queue methods?
>
> there is no need to be patronizing about this dude, im just learning
> Python in my spare time, as im a Intern Software Engineer

There is nothing patronizing about the question, it's merely an
enquiry to a possible fact. If you're going to be a techie, you should
learn stuff like that.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critic of Guido's blog on Python's lambda

2006-05-12 Thread Michele Simionato
jayessay wrote:
> "Michele Simionato" <[EMAIL PROTECTED]> writes:
> I can't get this to work at all - syntax errors (presumably you must
> have 2.5?, I only have 2.4).

You can download Python 2.5 from www.python.org, but the important bit,
i.e. the use of threading.local to get thread-local variables is
already there in Python 2.4.
'with' gives you just a nicer lisp-like syntax.

> This has not so much to do with WITH as relying on a special "global"
> object which you must reference specially, which keeps track (more or
> less) of its attribute values, which you use as "faked up" variables.
> Actually you probably need to hack this a bit more to even get that as
> it doesn't appear to stack the values beyond a single level.

Yes, but it would not be difficult, I would just instantiate
threading.local inside
the __init__ method of the dynamically_scoped class, so each 'with'
block
would have its own variables (and I should change getvar and setvar a
bit).

I was interested in a proof of concept, to show that Python can emulate
Lisp
special variables with no big effort.

  Michele Simionato

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


Re: pythoncode in matlab

2006-05-12 Thread Daniel Klünder
Hi Sven,

I don't have Matlab on my computer so the following is just a wild guess:

As far as I know you can include C code into Matlab or at least into
Simulink. Maybe you could try to execute your Python script in that C code?

Daniel

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


Re: Threads

2006-05-12 Thread placid

Sybren Stuvel wrote:
> placid enlightened us with:
> >>Did you read the documentation for Queue methods?
> >
> > there is no need to be patronizing about this dude, im just learning
> > Python in my spare time, as im a Intern Software Engineer
>
> There is nothing patronizing about the question, it's merely an
> enquiry to a possible fact. If you're going to be a techie, you should

true enough

> learn stuff like that.

its always said that (in programming) that the easiest solution to a
problem is hard to find, well for me posting my question here was the
hardest, when the easier solution was for me to go look at the Python
documentation!

>
> Sybren
> --
> The problem with the world is stupidity. Not saying there should be a
> capital punishment for stupidity, but why don't we just take the
> safety labels off of everything and let the problem solve itself?
>  Frank Zappa

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


Re: Decorator

2006-05-12 Thread Paul McGuire
"Lad" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I use Python 2.3.
> I have heard about decorators in Python 2.4.
> What is the decorator useful for?
> Thanks for reply
> L.
>
Check out these examples on the Python wiki:
http://wiki.python.org/moin/PythonDecoratorLibrary

I've gotten to be a big fan of memoize.

-- Paul


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


Re: python soap web services

2006-05-12 Thread Ravi Teja
> Is there any reason why there isn't any python library that makes
> using soap as easy as how microsoft .net makes it.

SOAP with Python is easy too in a different sort of way. I don't know
about the equivalent for autogenerating WSDL bit as in .NET.

#!/usr/bin/env python
def hello():
  return "Hello, world"
import ZSI
ZSI.dispatch.AsCGI()

And you have SOAP available on ANY web server.

More here.
http://pywebsvcs.sourceforge.net/zsi.html
http://diveintopython.org/soap_web_services/index.html

> When do you think someone will make this available for python web service??
When? Will let you know soon as my crystal ball gets delivered :-)
Seriously, whenever someone gets that itch to scratch since that's how
things get done in OSS usually.

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


deleting texts between patterns

2006-05-12 Thread micklee74
hi
say i have a text file

line1
line2
line3
line4
line5
line6
abc
line8 <---to be delete
line9  <---to be delete
line10  <---to be delete
line11  <---to be delete
line12  <---to be delete
line13 <---to be delete
xyz
line15
line16
line17
line18

I wish to delete lines that are in between 'abc' and 'xyz' and print
the rest of the lines. Which is the best way to do it? Should i get
everything into a list, get the index of abc and xyz, then pop the
elements out? or any other better methods? 
thanks

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


New blog

2006-05-12 Thread vinu

Hi all,
  http://pyadmin.blogspot.com/
THis is my blog and This is related to python utilities for system and 
network administration.plz comment on this

regards
Vineesh Kumar
begin:vcard
fn:Vineesh Kumar
n:Kumar;Vineesh
email;internet:[EMAIL PROTECTED]
tel;work:0484 2337929
tel;home:0480 2793090
tel;cell:09895131700
version:2.1
end:vcard

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

Re: deleting texts between patterns

2006-05-12 Thread Ravi Teja

[EMAIL PROTECTED] wrote:
> hi
> say i have a text file
>
> line1
> line2
> line3
> line4
> line5
> line6
> abc
> line8 <---to be delete
> line9  <---to be delete
> line10  <---to be delete
> line11  <---to be delete
> line12  <---to be delete
> line13 <---to be delete
> xyz
> line15
> line16
> line17
> line18
>
> I wish to delete lines that are in between 'abc' and 'xyz' and print
> the rest of the lines. Which is the best way to do it? Should i get
> everything into a list, get the index of abc and xyz, then pop the
> elements out? or any other better methods?
> thanks

In other words ...
lines = open('test.txt').readlines()
for line in lines[lines.index('abc\n') + 1:lines.index('xyz\n')]:
lines.remove(line)
for line in lines:
print line,

Regular expressions are better in this case
import re
pat = re.compile('abc\n.*?xyz\n', re.DOTALL)
print re.sub(pat, '', open('test.txt').read())

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


Re: String concatenation performance

2006-05-12 Thread Cristian.Codorean
Thanks guys ! Growing and learning :)

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


Re: Reg Ex help

2006-05-12 Thread bruno at modulix
Edward Elliott wrote:
(snip)
>>don a écrit :
>>
>>>Also if there is a better way than using regex, please let me know.
>>
(snip)
> 
> I wouldn't call these better (or worse) than regexes, but a slight variation
> on the above:
> 
> marker = s.index('/CHECKEDOUT')
> branch = s [s.rindex('/', 0, marker) + 1 : marker]

Much cleaner than mine. I shouldn't try to code when it's time to bed !-)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: deleting texts between patterns

2006-05-12 Thread Duncan Booth
 wrote:

> hi
> say i have a text file
> 
> line1
> line2
> line3
> line4
> line5
> line6
> abc
> line8 <---to be delete
> line9  <---to be delete
> line10  <---to be delete
> line11  <---to be delete
> line12  <---to be delete
> line13 <---to be delete
> xyz
> line15
> line16
> line17
> line18
> 
> I wish to delete lines that are in between 'abc' and 'xyz' and print
> the rest of the lines. Which is the best way to do it? Should i get
> everything into a list, get the index of abc and xyz, then pop the
> elements out? or any other better methods? 
> thanks
> 

Something like this (untested code):

def filtered(f, stop, restart):
   f = iter(f)
   for line in f:
   yield line
   if line==stop:
   break
   for line in f:
   if line==restart:
   yield line
   break
   for line in f:
   yield line

for line in filtered(open('thefile'), "abc\n", "xyz\n"):
print line
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deleting texts between patterns

2006-05-12 Thread Fredrik Lundh

<[EMAIL PROTECTED]> skrev i meddelandet news:[EMAIL PROTECTED]
> hi
> say i have a text file
>
> line1
> line2
> line3
> line4
> line5
> line6
> abc
> line8 <---to be delete
> line9  <---to be delete
> line10  <---to be delete
> line11  <---to be delete
> line12  <---to be delete
> line13 <---to be delete
> xyz
> line15
> line16
> line17
> line18
>
> I wish to delete lines that are in between 'abc' and 'xyz' and print
> the rest of the lines. Which is the best way to do it? Should i get
> everything into a list, get the index of abc and xyz, then pop the
> elements out? or any other better methods?

what's wrong with a simple

emit = True
for line in open("q.txt"):
if line == "xyz\n":
emit = True
if emit:
print line,
if line == "abc\n":
emit = False

loop ?  (this is also easy to tweak for cases where you don't want to include
the patterns in the output).

to print to a file instead of stdout, just replace the print line with a 
f.write call.





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


Re: Threads

2006-05-12 Thread Sybren Stuvel
placid enlightened us with:
> its always said that (in programming) that the easiest solution to a
> problem is hard to find

Yeah, that's true allright!

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator

2006-05-12 Thread bruno at modulix
Lad wrote:
> I use Python 2.3.
> I have heard about decorators in Python 2.4.

What Python 2.4 adds is only syntactic sugar for decorators. You can do
the same - somewhat more explicitely - in 2.3.

> What is the decorator useful for?

FWIW, I'm not sure the name 'decorator' is such a great idea. A
decorator (read 'function decorator') is mainly a callable that takes a
callable as param and returns another callable, usually wrapping the
passed callable and adding some responsabilities (tracing, logging,
pre-post condition checks, etc). Two well-known examples are classmethod
and staticmethod.

The whole things looks like this:

def deco(func):
  print "decorating %s" % func.__name__
  def _wrapper(*args, **kw):
print "%s called " % func.__name__
res = func(*args, **kw)
print "%s returned %s" % (func.__name__, str(res))
  return _wrapper

# python < 2.4
def somefunc():
  print "in somefunc"
  return 42

somefunc = deco(somefunc)

The syntactic sugar added in 2.4 allows you to avoid the explicit call
to deco():

# python >= 2.4
@deco
def someotherfunc():
  return "the parrot is dead"


As you see, apart from the syntactic sugar, there's nothing new here.
It's just plain old higher order function, well known in any functional
language.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reusing parts of a string in RE matches?

2006-05-12 Thread Fredrik Lundh
Mirco Wahab wrote:

> In Python, you have to deconstruct
> the 2D-lists (here: long list of
> short lists [a,2] ...) by
> 'slicing the slice':
>
>char,num = list[:][:]
>
> in a loop and using the apropriate element then:
>
>import re
>
>t = 'a1a2a3Aa4a35a6b7b8c9c';
>r =  r'(\w)(?=(.)\1)'
>l = re.findall(r, t)
>
>for a,b in (l[:][:]) : print  b
>
> In the moment, I find this syntax
> awkward and arbitary, but my mind
> should change if I'm adopted more
> to this in the end ;-)

in contemporary Python, this is best done by a list comprehension:

   l = [m[1] for m in re.findall(r, t)]

or, depending on what you want to do with the result, a generator
expression:

   g = (m[1] for m in re.findall(r, t))

or

   process(m[1] for m in re.findall(r, t))

if you want to avoid creating the tuples, you can use finditer instead:

l = [m.group(2) for m in re.finditer(r, t)]
g = (m.group(2) for m in re.finditer(r, t))

finditer is also a good tool to use if you need to do more things with
each match:

for m in re.finditer(r, t):
s = m.group(2)
... process s in some way ...

the code body will be executed every time the RE engine finds a match,
which can be useful if you're working on large target strings, and only
want to process the first few matches.

for m in re.finditer(r, t):
s = m.group(2)
if s == something:
break
... process s in some way ...





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


Re: Python-list Digest, Vol 32, Issue 209

2006-05-12 Thread I.V. Aprameya Rao
which files?

On Fri, 12 May 2006 [EMAIL PROTECTED] wrote:

> Send Python-list mailing list submissions to
>   [email protected]
>
> To subscribe or unsubscribe via the World Wide Web, visit
>   http://mail.python.org/mailman/listinfo/python-list
> or, via email, send a message with subject or body 'help' to
>   [EMAIL PROTECTED]
>
> You can reach the person managing the list at
>   [EMAIL PROTECTED]
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Python-list digest..."
>

-- 
To steal information from a person is called plagiarism. To steal information 
from the enemy is called gathering intelligence.

Have no fear of perfection - you will never reach it

Teamwork is essential; it gives the enemy other people to shoot at.

Consciousness: That annoying time between naps.

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


Re: syntax for -c cmd

2006-05-12 Thread Edward Elliott
Fredrik Lundh wrote:

> hint:
> 
> $ python -c 'import sys; print sys.argv' 'else: print "no"'
> 
> 

Yeah the man page knows all.

About the only time I use python on the command line is with the timeit
module, which evals all arguments given.  Hence the confusion.

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads

2006-05-12 Thread antred
Aww shoot, I never knew that!! LOL, I implemented my own worker thread
class using a mutex protected job list and a pair of connected sockets
for interprocess communication when I could just have used the darn
Queue module instead. Gr  hehe.

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


Re: Reg Ex help

2006-05-12 Thread Edward Elliott
bruno at modulix wrote:

> parts = s.replace(' ', '/').strip('/').split('/')
> branch = parts[parts.index('CHECKEDOUT') - 1]
>  
> Edward Elliott wrote:
>>
>> marker = s.index('/CHECKEDOUT')
>> branch = s [s.rindex('/', 0, marker) + 1 : marker]
> 
> Much cleaner than mine. I shouldn't try to code when it's time to bed !-)

Not terribly readable though, hard to tell what the magic slice indexes
mean.  Yours is easier to follow.  I think I'd just use a regex though.

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Translation of C# DES Encryption

2006-05-12 Thread Andreas Pauley

Hi all,

I'm trying to implement a Python equivalent of a C# method that encrypts 
a string.
My Python attempt is in the attached file, but does not return the same 
value as the C# method (see below).


Any hints?

Thanks,
Andreas

The C# method:

public static string Encrypt(string decrypted)
{
   byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(decrypted);
   byte[] rgbKey = System.Text.ASCIIEncoding.ASCII.GetBytes("12345678");
   byte[] rgbIV  = System.Text.ASCIIEncoding.ASCII.GetBytes("87654321");

   MemoryStream memoryStream = new MemoryStream(1024);

   DESCryptoServiceProvider desCryptoServiceProvider = new
DESCryptoServiceProvider();


   CryptoStream cryptoStream = new CryptoStream(memoryStream,
   desCryptoServiceProvider.CreateEncryptor(rgbKey, rgbIV),
   CryptoStreamMode.Write);

   cryptoStream.Write(data, 0, data.Length);
   cryptoStream.FlushFinalBlock();
   byte[] result = new byte[(int)memoryStream.Position];
   memoryStream.Position = 0;
   memoryStream.Read(result, 0, result.Length);
   cryptoStream.Close();
   return System.Convert.ToBase64String(result);
}


_
This e-mail contains official information from Quality Business Consultants 
(Pty) Ltd and is intended for use by the addressee only.
Important notice: Important restrictions, qualifications and disclaimers ("the 
Disclaimer") apply to this email.
To read this click on the following address: http://www.qbcon.com/disclaimer
The Disclaimer forms part of the content of this email in terms of section 11 
of the Electronic Communications and Transactions Act, 25 of 2002. If you are 
unable to access the Disclaimer, send a blank e-mail to [EMAIL PROTECTED] and 
we will send you a copy of the Disclaimer.

#!/usr/bin/env python

from Crypto.Cipher import DES
import base64

def base64DESEncrypt(plaintext):

# Set the key to be used:
rgbKey = "12345678"

# Set the Initial Value (IV) to be used:
rgbIV  = "87654321"

des_object=DES.new(rgbKey, DES.MODE_ECB)
des_object.IV = rgbIV

ciphertext = des_object.encrypt(plaintext)
base64_ciphertext = base64.encodestring(ciphertext)

return base64_ciphertext

if __name__ == '__main__':
# The length of the string has to be a multiple of 8, for simplicity (for 
now).
# The C# code does not have this limitation, so I'd have to look at
# that as well.
print base64DESEncrypt('password')


# Original C# method that I'm trying to translate:
#
#public static string Encrypt(string decrypted)
#{
#byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(decrypted);
#byte[] rgbKey = System.Text.ASCIIEncoding.ASCII.GetBytes("12345678");
#byte[] rgbIV  = System.Text.ASCIIEncoding.ASCII.GetBytes("87654321");
#
#MemoryStream memoryStream = new MemoryStream(1024);
#
#DESCryptoServiceProvider desCryptoServiceProvider = new
DESCryptoServiceProvider();
#
#CryptoStream cryptoStream = new CryptoStream(memoryStream,
#desCryptoServiceProvider.CreateEncryptor(rgbKey, rgbIV),
#CryptoStreamMode.Write);
#
#cryptoStream.Write(data, 0, data.Length);
#cryptoStream.FlushFinalBlock();
#byte[] result = new byte[(int)memoryStream.Position];
#memoryStream.Position = 0;
#memoryStream.Read(result, 0, result.Length);
#cryptoStream.Close();
#return System.Convert.ToBase64String(result);
#}
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can Python installation be as clean as PHP?

2006-05-12 Thread Fredrik Lundh
Ravi Teja wrote:

> Python has zip imports (similar to Java's jar files). You can put all
> your *.py files in a zip file and access them from it if this means so
> much to you.

Python also supports "frozen" modules, where the module bytecode is
linked into a Python interpreter as data.  by combining frozen modules
and static linking of extension modules, it's relatively easy to create a
single-file python interpreter.

and to make things even simpler, you can get tools and ready-made
single-file distributions for a variety of platforms here:

http://www.egenix.com/files/python/mxCGIPython.html
http://phd.pp.ru/Software/Python/misc/mxCGI/





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


Re: deleting texts between patterns

2006-05-12 Thread John Machin
On 12/05/2006 6:11 PM, Ravi Teja wrote:
> [EMAIL PROTECTED] wrote:
>> hi
>> say i have a text file
>>
>> line1
[snip]
>> line6
>> abc
>> line8 <---to be delete
[snip]
>> line13 <---to be delete
>> xyz
>> line15
[snip]
>> line18
>>
>> I wish to delete lines that are in between 'abc' and 'xyz' and print
>> the rest of the lines. Which is the best way to do it? Should i get
>> everything into a list, get the index of abc and xyz, then pop the
>> elements out? or any other better methods?
>> thanks
> 
> In other words ...
> lines = open('test.txt').readlines()
> for line in lines[lines.index('abc\n') + 1:lines.index('xyz\n')]:
> lines.remove(line)

I don't think that's what you really meant.

 >>> lines = ['blah', 'fubar', 'abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy']
 >>> for line in lines[lines.index('abc\n') + 1:lines.index('xyz\n')]:
... lines.remove(line)
...
 >>> lines
['abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy']

Uh-oh.

Try this:

 >>> lines = ['blah', 'fubar', 'abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy']
 >>> del lines[lines.index('abc\n') + 1:lines.index('xyz\n')]
 >>> lines
['blah', 'fubar', 'abc\n', 'xyz\n', 'xyzzy']
 >>>

Of course wrapping it in try/except would be a good idea, not for the 
slicing, which behaves itself and does nothing if the 'abc\n' appears 
AFTER the 'xyz\n', but for the index() in case the sought markers aren't 
there. Perhaps it might be a good idea even to do it carefully one piece 
at a time: is the abc there? is the xyz there? is the xyz after the abc 
-- then del[index1+1:index2].

I wonder what the OP wants to happen in a case like this:

guff1 xyz guff2 abc guff2 xyz guff3
or this:
guff1 abc guff2 abc guff2 xyz guff3

> for line in lines:
> print line,
> 
> Regular expressions are better in this case

Famous last words.

> import re
> pat = re.compile('abc\n.*?xyz\n', re.DOTALL)
> print re.sub(pat, '', open('test.txt').read())
> 

I don't think you really meant that either.

 >>> lines = ['blah', 'fubar', 'abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy']
 >>> linestr = "".join(lines)
 >>> linestr
'blahfubarabc\nblahfubarxyz\nxyzzy'
 >>> import re
 >>> pat = re.compile('abc\n.*?xyz\n', re.DOTALL)
 >>> print re.sub(pat, '', linestr)
blahfubarxyzzy
 >>>

Uh-oh.

Try this:

 >>> pat = re.compile('(?<=abc\n).*?(?=xyz\n)', re.DOTALL)
 >>> re.sub(pat, '', linestr)
'blahfubarabc\nxyz\nxyzzy'

... and I can't imagine why you're using the confusing [IMHO] 
undocumented [AFAICT] feature that the first arg of the module-level 
functions like sub and friends can be a compiled regular expression 
object. Why not use this:

 >>> pat.sub('', linestr)
'blahfubarabc\nxyz\nxyzzy'
 >>>

One-liner fanboys might prefer this:

 >>> re.sub('(?i)(?<=abc\n).*?(?=xyz\n)', '', linestr)
'blahfubarabc\nxyz\nxyzzy'
 >>>

HTH,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deleting texts between patterns

2006-05-12 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> hi
> say i have a text file
> 
> line1
> line2
> line3
> line4
> line5
> line6
> abc
> line8 <---to be delete
> line9  <---to be delete
> line10  <---to be delete
> line11  <---to be delete
> line12  <---to be delete
> line13 <---to be delete
> xyz
> line15
> line16
> line17
> line18
> 
> I wish to delete lines that are in between 'abc' and 'xyz' and print
> the rest of the lines. Which is the best way to do it?  Should i get
> everything into a list, get the index of abc and xyz, then pop the
> elements out? 

Would be somewhat inefficient IMHO - at least for big files, since it
implies reading the whole file in memory.

> or any other better methods? 

Don't know if it's better for your actual use case, but this avoids
reading up the whole file:

def skip(iterable, skipfrom, skipuntil):
""" example usage :
>>> f = open("/path/to/my/file.txt")
>>> for line in skip_print(f, 'abc', 'yyz'):
>>> print line
>>> f.close()
"""
skip = False
for line in iterable:
if skip:
if line == skipuntil:
skip = False
continue
else:
if line == skipfrom:
skip = True
continue
yield line

def main():
lines = """
line1
line2
line3
line4
line5
line6
abc
line8 <---to be delete
line9  <---to be delete
line10  <---to be delete
line11  <---to be delete
line12  <---to be delete
line13 <---to be delete
xyz
line15
line16
line17
line18
""".strip().split()
for line in skip(lines, 'abc', 'xyz'):
print line


HTH

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


compiling module from string and put into namespace

2006-05-12 Thread glomde
Hi,

I want to create a function that preprocesses a file and then imports
the parsed file.

What I found out is that you can do something like this:

def ImportFile(fileName):
parsedCode = Parser(fileName).Parse()
module = new.module(name)
exec parsedCode in module.__dict__
sys.modules[name] = module
import name

But this works only if the ImportFile isnt loaded from a module.
Since the import is local.

So this wouldnt work:

from XXX import ImportFile

ImportFile(fileName)
fileName.Function()

Since the import in ImportFile isnt visible the module that calls it.
So how do I do so that the import is visible from callers namespace?

Best regards,

T

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


index of an element in a numarray array

2006-05-12 Thread avharut
hello everyone!
sorry to disturb you with this, but i really cant find anything
suitable about the topic in the numarray documentation.
how can i find in an efficient way the index of the last occurrence of
a given element in a numarray array?
many thanks in advance!

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


Re: Possible constant assignment operators ":=" and "::=" for Python

2006-05-12 Thread Piet van Oostrum
> [EMAIL PROTECTED] (T) wrote:

>T> As you can see, the "constant" A can be modified this easily. But if
>T> there were an intuitive mechanism to declare a symbol to be immutable,
>T> then there won't be this problem.

Mutability is not a property of symbols but of values. So it doesn't make
sense to declare an identifier to be immutable. And mutability is tied to
the object's type, not to individual instances.

What you want can only be obtained if Python would have an immutable
variant for each type or would add an immutable attribute to each object.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there any pure python webserver that can use FCGI

2006-05-12 Thread llothar
Hello,

as the subject says, for an embedded application i need a 100% pure
python webserver that can talk to a FCGI process (which runs ruby on
rails).  Of couse it also must be able to use simple CGI.

Please don't ask why i want a python webserver for a ruby application.
I just need it.

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


Re: Python memory deallocate

2006-05-12 Thread Fredrik Lundh
bruno at modulix" wrote:

> *please* re-read carefully what I and Diez wrote earlier in this thread
> before jumping to possibly erroneous conclusion. I didn't say that the
> problem *actually* was with Python - just that it *may* have to do with
> a memory management issue fixed in 2.5.

the only thing that has changed is that Python 2.5 is slightly more likely to 
release
memory areas held by the Python object allocator back to the C runtime memory
allocator.  if you have a leak in your application, changing to Python 2.5 won't
change a thing.

 



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


Re: Python memory deallocate

2006-05-12 Thread Fredrik Lundh
Heiko Wundram wrote:

> PIL isn't known to have any memory leaks, by the way (AFAICT), just to confirm
> what I've written before, but the effbot should be of more help here...

PIL is heavily used in 24/7 production systems, often by people who knows a lot
about how to run mission critical systems, so memory and resource leaks in PIL
tends to be noticed.

there has been one leak fix in 1.1.6, afaik: converting a grayscale image to a 
palette
image would (sometimes?) leak a palette structure.  but that's a couple of 
hundred
bytes, not a couple of hundred megabytes...

 



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


State of the "Vaults of Parnassus"

2006-05-12 Thread Christoph Zwerschke
Does anybody know what happened to the "Vaults of Parnassus" site at 
http://www.vex.net/~x/parnassus/?

"Dr Dobb's weekly Python news" still claims that it "ambitiously 
collects references to all sorts of Python resources." But I have the 
impression that it does not do this any more since April 2005, probably 
because we have the Cheese Shop now. It's strange that the site does not 
mention that it is not maintained any more, and it is still possible to 
submit and update entries, but these changes seem to be discarded. 
That's not very nice. Also, I found no contact address on the whole 
website. Who is in charge of it?

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


Re: python soap web services

2006-05-12 Thread Diez B. Roggisch
Butternut squash wrote:

> Is there any reason why there isn't any python library that makes
> using soap as easy as how microsoft .net makes it.
> 
> I mean I write rudimentary asmx files call them from a webbrowser.
> The WSDL is generated and then there is documentation and a form to
> invoke a function.

The WSDL will never as easily be created as in .NET/JAVA, as Python lacks
static typing annotations that are used by the WSDL-generators. So either
someone defines his own type annotation theme for that purpose that can be
used to infer the WSDL  - or you write WSDL yourself. Which is a major
PITA, as the whole SOAP mess. 

Ravi OTH has pointed out _running_ a SOAP service is easy as cake.

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


Re: compiling module from string and put into namespace

2006-05-12 Thread bruno at modulix
glomde wrote:
> Hi,
> 
> I want to create a function that preprocesses a file and then imports
> the parsed file.
> 
> What I found out is that you can do something like this:
> 
> def ImportFile(fileName):
> parsedCode = Parser(fileName).Parse()
> module = new.module(name)
> exec parsedCode in module.__dict__
> sys.modules[name] = module
> import name
> 
> But this works only if the ImportFile isnt loaded from a module.
> Since the import is local.

Look for __import__() (it's in the builtins) and sys.modules.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deleting texts between patterns

2006-05-12 Thread bruno at modulix
bruno at modulix wrote:
> [EMAIL PROTECTED] wrote:
> 
(snip)
> 
> Don't know if it's better for your actual use case, but this avoids
> reading up the whole file:

> def skip(iterable, skipfrom, skipuntil):
> """ example usage :
> >>> f = open("/path/to/my/file.txt")
> >>> for line in skip_print(f, 'abc', 'yyz'):
> >>> print line
> >>> f.close()
> """
(snip code)

Forgot to say this will also skip markers. If you want to keep them, see
the effbot answer...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deleting texts between patterns

2006-05-12 Thread bruno at modulix
Fredrik Lundh wrote:
(snip)
> to print to a file instead of stdout, just replace the print line with a 
> f.write call.
> 

Or redirect stdout to a file when calling the program !-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which windows python to use?

2006-05-12 Thread Don Taylor
Robert Kern wrote:

> In what way? Does the mingw gcc that we distribute interfere with Cygwin's 
> gcc?

Robert:

Which C compiler will you be using for the Enthought 2.4 Windows release?

Don.


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


Re: NEWBIE: Tokenize command output

2006-05-12 Thread bruno at modulix
Tim Chase wrote:
(snip)
> starLines = [line for line in p.readlines() if line.startswith("*")]

files are iterators, so no need to use readlines() (unless it's an old
Python version of course):

starLines = [line for line in p if line.startswith("*")]

> or you may optionally want to prune of the "\n" characters in the process:
> 
> starLines = [line[:-1] for line in p.readlines() if line.startswith("*")]

*please* use str.rstrip() for this:
starLines = [line.rstrip() for line in p if line.startswith("*")]

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python memory deallocate

2006-05-12 Thread bruno at modulix
Fredrik Lundh wrote:
> bruno at modulix" wrote:
> 
> 
>>*please* re-read carefully what I and Diez wrote earlier in this thread
>>before jumping to possibly erroneous conclusion. I didn't say that the
>>problem *actually* was with Python - just that it *may* have to do with
>>a memory management issue fixed in 2.5.
> 
> 
> the only thing that has changed is that Python 2.5 is slightly more likely to 
> release
> memory areas held by the Python object allocator back to the C runtime memory
> allocator.  if you have a leak in your application, changing to Python 2.5 
> won't
> change a thing.

Which is mostly what I meant - sorry if it wasn't clear.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: design a Condition class

2006-05-12 Thread bruno at modulix
Carl J. Van Arsdall wrote:
(snip)
> I just wanted to make the comment that there already exists a
> Condition() class in the threading module.  If you plan on using your
> class with the threading module you might wish to use another name.
> 
As far as I remember, Python has namespaces, so I don't see the point
here...


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New tail recursion decorator

2006-05-12 Thread Tim N. van der Leeuw
[...]
> >
> I'm not convinced by this. You have to recognise that the function is using
> tail recursion, and then you have to modify the code to know that it is
> using tail recursion. This is not always trivial. For example, the given
> example is:
>
> @tail_recursion
> def factorial(n, acc=1):
> "calculate a factorial"
> if n == 0:
>return acc
> res = factorial(n-1, n*acc)
> return res
>
> but a more common way to write the function would be:
>
> @tail_recursion
> def factorial(n):
> "calculate a factorial"
> if n == 0:
>return 1
> return n * factorial(n-1)
>
> which won't work because it isn't actually tail recursion, but it looks
> sufficiently close to tail recursion that it would probably mislead a lot
> of people into expecting it will work. If you are going to have to rewrite
> functions in a stilted manner, and they use simple tail recursion, then why
> not just factor out the tail recursion in the first place.
>
[...]

Hi Duncan,

I don't know why it wouldn't work this way, or why it isn't
tail-recursion?

I tried the tail_recursion decorator from the cookbook-recipe with both
definitions of factorial, and I tried both definitions of the factorial
function with and without tail_recursion decorator.

In all four cases I get the same results, so it does work with both
definitions of factorial(), even if (according to you) the second
definition is not proper tail-recursion.

Using the tail-recursion decorator (the version that does not inspect
the stackframes) I get a small performance-increase over using the
factorial-function undecorated.
However, calculating factorial(1000) with the factorial-function as
defined in the cookbook-recipe is much much faster than calculating the
same factorial(1000) with the factorial-function you gave!
I cannot yet explain why the first function has so much better
performance than the second function  - about a factor 10 difference,
in both python2.4.3 and python 2.5a2


Cheers,

--Tim

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


Re: deleting texts between patterns

2006-05-12 Thread Tim Chase
> I wish to delete lines that are in between 'abc' and
> 'xyz' and print the rest of the lines. Which is the best
> way to do it?

While this *is* the python list, you don't specify whether
this is the end goal, or whether it's part of a larger
program. If it *is* the end goal (namely, you just want the
filtered output someplace), and you're not adverse to using
other tools, you can do something like

sed -n -e'1,/abc/p' -e'/xyz/,$p' file.txt

which is pretty straight-forward.  It translates to

-n   don't print each line by default
-e   execute the following item
1,/abc/  from line 1, through the line where you match "abc"
pprint each line
  and also
-e   execute the following item
/xyz/,$  from the line matching "abc" through the last line
pprint each line


It assumes that
1) there's only one /abc/ & /xyz/ in the file (otherwise, it
defaults to the first one it finds in each case)
2) that they're in that order (otherwise, you'll get 2x each
line, rather than 0x each line)

However, it's a oneliner here, and seems to be a bit more
complex in python, so if you don't need to integrate the
results into further down-stream python processing, this
might be a nice way to go.  If you need the python, others
on the list have offered a panoply of good answers already.

-tkc






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


Re: index of an element in a numarray array

2006-05-12 Thread rory . brandybuck

[EMAIL PROTECTED] wrote:
> how can i find in an efficient way the index of the last occurrence of
> a given element in a numarray array?

Something like that:
>>> where(arange(100) == 10)
(array([10]),)
>>> _[-1][-1]
10

Or:
>>> your_array = arange(10)
>>> value = 3
>>> indices = where(your_array == value)
>>> last_index = indices[0][-1]
>>> print last_index

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


Creating an Active Desktop Window

2006-05-12 Thread rodmc
Hi,

Does anyone know how I can create  an Active Desktop window from within
a Python script? It would also be good to know how to refresh that
window and nothing else.

At present I have an application which writes to a file which is read
by the Active Desktop (embeded IE), then a refresh command is issued
which refreshes the whole screen. This is a bit clumsy and also the
user needs to manually set up the Active Desktop component.

I have been looking around for some solutions to this and as of today
my book on PyWin32 has still not arrived.

Thanks in advance for any pointers.

Best,

rod

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


Re: New tail recursion decorator

2006-05-12 Thread Michele Simionato
Tim N. van der Leeuw wrote:
>
> I don't know why it wouldn't work this way, or why it isn't
> tail-recursion?

>From the google page do "define: tail recursion"

> I tried the tail_recursion decorator from the cookbook-recipe with both
> definitions of factorial, and I tried both definitions of the factorial
> function with and without tail_recursion decorator.
> In all four cases I get the same results, so it does work with both
> definitions of factorial(), even if (according to you) the second
> definition is not proper tail-recursion.

For me factorial(1001) with the second definition does not work, I get
the recursion limit (which is what I expect). I suppose the recursion
limit is higher on your system, but definitely you should reach it at
some point with the non tail-recursive version of factorial.

> Using the tail-recursion decorator (the version that does not inspect
> the stackframes) I get a small performance-increase over using the
> factorial-function undecorated.
> However, calculating factorial(1000) with the factorial-function as
> defined in the cookbook-recipe is much much faster than calculating the
> same factorial(1000) with the factorial-function you gave!
> I cannot yet explain why the first function has so much better
> performance than the second function  - about a factor 10 difference,
> in both python2.4.3 and python 2.5a2

It is because the decorator is doing is job (converting a long
recursion in a loop)
only with the first function, which is properly tail recursive. Just as
Duncan said.

 Michele Simionato

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


Re: design a Condition class

2006-05-12 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> Hello,
> 
> i posted for suggestions a little idea even if it still needs further
> thoughts but as i'm sure you could help :)
> 
> if would like to implement some kind of Condition class which i coud
> use to build bricks of more complex condition, conditions are based on
> fields by using regexp
> 
> class Condition:

Do yourself a favor and use newstyle classes:
class Condition(object):
>   def __init__(self, field0, field1, field2):
>   self.field0 = field0
>   self.field1 = field1
>   self.field2 = field2
>   def match(self, against):
>   w, t, l = against
>   f0 = False
>   if self.field0 is None:
>   f0 = True
>   else:
>   f0 = self.field0.search(w)
>   if self.field1 is None:
>   f1 = True
>   else:
>   f1 = self.field1.search(t)
>   if self.field2 is None:
>   f2 = True
>   else:
>   f2 = self.field2.search(l)
>   return f0 and f1 and f2

> c0 = Condition(re.compile("something"), None,
> re.compile("somethingelse"))
> c1 = Condition(re.compile("another"), None, None)
> 
> i can use
> 
> if c0.search(myitem)

Have you actually tested this ?-)
(hint : the method name is 'match', not 'search')


> 
> but i would like to be able to have composition such as :
> 
> c2 = c0 | c1
> 
> which should be understood as defining a new c2 which is able to match
> (c0 or c1) from c0 and c1 already defined.
> 
> actually i can imagine a
> 
> def OR(c0, c1):
>  # here => missing None support 'a or None' is 'a'
>  return Condition(re.compile("|".join((c0.field0.pattern,
> c1.field0.pattern)),
>   re.compile("|".join((c0.field1.pattern,
> c1.field1.pattern)),
>   re.compile("|".join((c0.field2.pattern,
> c1.field2.pattern))
> 
> the idea is to build c2 = Condition(re.compile("something|another"),
> None, re.compile("somethingelse"))
> c2 = OR(c0, c1)
>
> but maybe have you clever suggestions ?

use the __or__(self, other) special method.
http://www.python.org/doc/2.4.2/ref/numeric-types.html


Here is a somewhat rewritten, hopefully more pythonic version - will
need some more works, specially wrt/ error handling :

class Condition(object):
def __init__(self, *exps):
self._exps = exps

def match(self, *targets):
# don't know how you want to handle this case
assert len(targets) == len(self._exps), \
"expected %d args, got %d" % (len(self._exps), len(targets))

for exp, target in zip(self._exps, targets):
# takes care of None in the expression list
if not (exp is None or exp.search(target)):
return False
return True

def __or__(self, other):
""" cf http://www.python.org/doc/2.4.2/ref/numeric-types.html

"""
# I let you take care of all error handling...
# take care of what happens if
# len(other._exps) != len(self._exps)
# NB : itertools might be of some help here
exps = [re.compile("(%s)|(%s)" % (e1.pattern, e2.pattern)) \
for e1, e2 in zip(self._exps, other._exps)]
return self.__class__(*exps)


HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: linking with math.so

2006-05-12 Thread Heiko Wundram
Am Donnerstag 11 Mai 2006 18:49 schrieb [EMAIL PROTECTED]:
> "importing math" as far as I can tell right now,  invokes a shared
> library (math.so).  Now I have a shared library dependency that I dont
> want. Is there a way to get the math  functionality from a  dot a or a
> dot o, so I dont have to make my app dependent on a shared library?
> cos, sin, and pi which is what I need do not live in the libpython2.4.a
>   - I did an nm on it I'm on linux.

bonifats modelnine # ls -la /usr/lib/libm.a
-rw-r--r-- 1 root root 1194744 May  9 02:23 /usr/lib/libm.a
bonifats modelnine #

You have to link statically against that part of libc.

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


Re: NEWBIE: Tokenize command output

2006-05-12 Thread Tim Chase
>>starLines = [line for line in p.readlines() if line.startswith("*")]
> 
> files are iterators, so no need to use readlines() (unless it's an old
> Python version of course):
> 
> starLines = [line for line in p if line.startswith("*")]

Having started with some old Python, it's one of those 
things I "know", but my coding fingers haven't yet put into 
regular practice. :)

>>or you may optionally want to prune of the "\n" characters in the process:
>>
>>starLines = [line[:-1] for line in p.readlines() if line.startswith("*")]
> 
> *please* use str.rstrip() for this:
> starLines = [line.rstrip() for line in p if line.startswith("*")]

They can yield different things, no?

 >>> s = "abc  \n"
 >>> s[:-1]
'abc  '
 >>> s.rstrip()
'abc'
 >>> s.[:-1] == s.rstrip()
False

If trailing space matters, you don't want to throw it away 
with rstrip().

Otherwise, just to be informed, what advantage does rstrip() 
have over [:-1] (if the two cases are considered 
uneventfully the same)?

Thanks,

-tkc







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


Re: Python memory deallocate

2006-05-12 Thread Heiko Wundram
Am Donnerstag 11 Mai 2006 18:07 schrieb Michele Petrazzo:
> Heiko Wundram wrote:
> > As was said before: as long as you keep a reference to an object, the
> > object's storage _will not be_ reused by Python for any other objects
> > (which is sensible, or would you like your object to be overwritten by
> > other objects before you're done with them?). Besides, even if Python did
> > free the memory that was used, the operating system wouldn't pick it up
> > (in the general case) anyway (because of fragmentation issues), so Python
> > keeping the memory in an internal free-list for new objects is a sensible
> > choice the Python developers took here.
>
> This isn't true. Just tried with python 2.5a2 and:
>
> d:\python25\python.exe
>
> >>> a = range(1000 * 100 *100) # 173 MB
> >>> del a # 122MB
>
> So now, like you saied, if I try to allocate another memory chunk,
>
> python'll re-use it... But this isn't true:
> >>> b = range(100 * 100 * 100) # 126 MB
> >>> del b # 122MB
> >>> exit() # :)
>
> d:\python25\python.exe
>
> >>> b = range(100 * 100 * 100) # 19 MB
>
> Do why python don't reuse the freed memory and re-allocate 4 MB (126 -
> 122)?

What the OS reports as the memory usage isn't actually what's allocated by 
Python objects. As Tim Peters pointed out in another post, this number just 
specifies the amount of memory the OS has given to libc, which in turn has 
given it to Python.

Basically, what you're seeing is exactly the reuse of memory that Python 
internally does. Why it allocates 4 more megabytes I wouldn't know, but as 
you can see, the range b is actually 19 megabytes in size (a little smaller, 
but >10MB), whereas it only takes up 4 megabytes when you construct it after 
you deleted the old list. That's a major difference.

I just tried the following:

[EMAIL PROTECTED] ~ $ python
Python 2.4.3 (#1, May  4 2006, 23:51:29)
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

1000  7836  0.0  0.3  15816  3540 pts/1S+   15:09   0:00 python

>>> x = range(100)

1000  7836  0.2  3.8  47656 35388 pts/1S+   15:09   0:00 python

>>> del x

1000  7836  0.2  2.9  39840 27572 pts/1S+   15:09   0:00 python

>>> x = range(100)

1000  7836  0.2  3.8  48720 35460 pts/1S+   15:09   0:00 python

>>> del x

1000  7836  0.2  2.9  40904 27644 pts/1S+   15:09   0:00 python

>>> x = range(100)

1000  7836  0.2  3.8  48720 35460 pts/1S+   15:09   0:00 python

>>> del x

1000  7836  0.2  2.9  40904 27644 pts/1S+   15:09   0:00 python

...

Ad infinitum (see the pattern?)

Convinced now that Python reuses memory? (see the sixth column for actual 
memory usage, the fifth is mapped memory, which contains shared libraries, 
etc.) The list is about 32MB in size (see the initial jump from 3MB to 35MB), 
but only adds about 8MB in each iteration, which are freed in each run.

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


RE: multi-threaded c++ callback problem

2006-05-12 Thread Ames Andreas
> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED]
> g] On Behalf Of pydev
> Sent: Tuesday, April 11, 2006 9:23 PM
> Subject: multi-threaded c++ callback problem
> 
> void pyCallEventCallback(  CALL hCall, 
> LINE hLine, 
> CALLSTATE_MAJOR eMajor,
> CALLSTATE_MINOR eMinor,  
> PyObject* def )
> {
> if( !PyCallable_Check( def ) ) 
> {
> PyErr_SetString( PyExc_TypeError, "Need a callable object!" );
> return;
> }
> printf( "EventCallback hCall: %i, hLine: %i, eMajor: %i, 
> eMinor: %i\n", hCall, hLine, eMajor, eMinor);
> PyObject* arglist = Py_BuildValue("()", hCall, hLine, 
> eMajor, eMinor);
>  
> // if i comment out next  line it works!
> PyEval_CallObject( def, arglist ); 
>  
> Py_XDECREF(arglist);
> }
> //---//

Wild guess because of lack of context:

It's a race condition because you haven't acquired the GIL before calling 
pyCallEventCallback.  You can do so by using PyEval_SaveThread and friends.  
You have to make sure to call PyEval_InitThreads somewhere, e.g. when embedding 
from within the interpreter initialisation boilerplate, when extending for 
instance from within the extension module initialisation.


cheers,

aa

-- 
Andreas Ames | Programmer | Comergo GmbH |
Voice:  +49 69 7505 3213 | ames AT avaya . com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NEWBIE: Tokenize command output

2006-05-12 Thread bruno at modulix
Tim Chase wrote:
>>> starLines = [line for line in p.readlines() if line.startswith("*")]
>>
>>
>> files are iterators, so no need to use readlines() (unless it's an old
>> Python version of course):
>>
>> starLines = [line for line in p if line.startswith("*")]
> 
> 
> Having started with some old Python, it's one of those things I "know",
> but my coding fingers haven't yet put into regular practice. :)

I reeducated my fingers after having troubles with huge files !-)

>>> or you may optionally want to prune of the "\n" characters in the
>>> process:
>>>
>>> starLines = [line[:-1] for line in p.readlines() if
>>> line.startswith("*")]
>>
>>
>> *please* use str.rstrip() for this:
>> starLines = [line.rstrip() for line in p if line.startswith("*")]
> 
> 
> They can yield different things, no?
> 
 s = "abc  \n"
 s[:-1]
> 'abc  '
 s.rstrip()
> 'abc'
 s.[:-1] == s.rstrip()
> False
> 
> If trailing space matters, you don't want to throw it away with rstrip().

then use rstrip('\n') - thanks for this correction.

> Otherwise, just to be informed, what advantage does rstrip() have over
> [:-1] (if the two cases are considered uneventfully the same)?

1/ if your line doesn't end with a newline, line[:-1] will still remove
the last caracter.

2/ IIRC, if you don't use universal newline and the file uses the
DOS/Windows newline convention, line[:-1] will not remove the CR - only
the LF (please someone correct me if I'm wrong here).

I know this may not be a real issue in the actual case, but using
rstrip() is still a safer way to go IMHO - think about using this same
code to iterate over a list of strings without newlines...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New tail recursion decorator

2006-05-12 Thread Tim N. van der Leeuw
Hi Michele,

I'm sorry, but you misunderstood me.

There are two definitions of the factorial() function, one given by the
OP and the other given by Duncan.

I tested both factorial() definitions with, and without the
tail_recursion decorator (the version of the OP). So I had 4
factorial-functions defined in my test-file:

@tail_recursion
def factorial(n, acc=1):
# do the stuff
pass

def factorial_r(n, acc=1):
# do the stuff
pass

@tail_recursion
def factorial2(n):
# do the stuff
pass

def factorial2_r(n):
# do the stuff
pass

All four functions give the same output for the tests I did (n=120, and
n=1000).
Using timeit, both factorial(1000) and factorial2(1000) are somewhat
faster than factorial_r(1000) respectively factorial2_r(1000).
However, factorial(1000) and factorial_r(1000) are both 10x faster than
factorial2(1000) and factorial2_r(1000).

It's the latter performance difference which I do not understand.

The other thing I do not understand, due to my limited understanding of
what is tail-recursion: factorial2 (Duncan's definition) is not proper
tail-recursion. Why not? How does it differ from 'real' tail recursion?
And if it's not proper tail-recursion and therefore should not work,
then how comes that the tests I do show it to work? And I seemed to
consistently get a slightly better performance from factorial2(1000)
than from factorial2_r(1000).


NB: Regarding the recursion limits, I don't know what would be the
stacklimit on my system (Python 2.4.3 on WinXP SP2). I already
calculated the factorial of 50 using the recursive (non-decorated)
function...


Cheers,

--Tim

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


nix logon in Python

2006-05-12 Thread Philippe Martin
Hi,

Are there any (even prototypes/proof of concept) gdm/kdm/xdm.../-style
packages written in Python ?

Regards,

Philippe

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


where do you run database scripts/where are DBs 'located'?

2006-05-12 Thread John Salerno
Ok, I've been browsing through the MySQLdb docs, and I *think* I know 
the kind of code I need to write (connect, cursor, manipulate data, 
commmit, etc. -- although I probably need to get more familiar with 
actual SQL commands too), but here's my problem: I don't know where 
these scripts are supposed to be executed, or how they are supposed to 
'find' the database.

Really, I have the same question for two different scenarios: accessing 
and working with a database that is stored locally on my PC, and the 
same with a DB that is on my web server space. I figure I already know 
the host, username, password and database name (in fact, all these 
things are spelled out as far as my web DB is concerned; I assume my 
host name for the local DB is my computer's name).

But my question is, can these DB scripts be executed anywhere, and they 
will find the DB based on the connect() parameters? Or do I need to do 
something special with them? It seems like a similar problem to when you 
don't have your PYTHONPATH variable set up properly. I've tried some DB 
stuff, but it doesn't seem to work.

If more information is needed, I will try my local DB when I get home 
later. As for the web DB, I figure there's probably more issues involved 
that I'm not aware of, since web programming is still new to me.

So without actually giving you some code and tracebacks, is there any 
general advice about how to set up these scripts? Also, is there any 
better documentation than this:
http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307

It doesn't seem too thorough, and it also doesn't cover actual SQL 
queries that you'd have to pass to the query method. Maybe I will just 
have to find that information in a MySQL tutorial.

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


Re: Decorator

2006-05-12 Thread Martin Blume
"bruno at modulix" schrieb 
> 
> What Python 2.4 adds is only syntactic sugar for decorators. 
> You can do the same - somewhat more explicitely - in 2.3.
> 
> > What is the decorator useful for?
> 
> 
> The whole things looks like this:
> 
> def deco(func):
>   print "decorating %s" % func.__name__
>   def _wrapper(*args, **kw):
> print "%s called " % func.__name__
> res = func(*args, **kw)
> print "%s returned %s" % (func.__name__, str(res))
  return res
  ^^
Shouldn't here be a return res, so that wrapper
behaves like the original function?

>   return _wrapper
> 
> # python < 2.4
> def somefunc():
>   print "in somefunc"
>   return 42
> 
> somefunc = deco(somefunc)
> 

Thanks for the explanation.


Another question: Isn't decorating / wrapping usually
done at runtime, so that the @deco notation is pretty
useless (because you'd have to change the original 
code)?
What do I miss here?

Martin


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


Re: index of an element in a numarray array

2006-05-12 Thread avharut
thanks alot!!

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


[OT] Unix Tools (was: deleting texts between patterns)

2006-05-12 Thread Dan Sommers
On Fri, 12 May 2006 07:29:54 -0500,
Tim Chase <[EMAIL PROTECTED]> wrote:

>> I wish to delete lines that are in between 'abc' and
>> 'xyz' and print the rest of the lines. Which is the best
>> way to do it?

> While this *is* the python list, you don't specify whether
> this is the end goal, or whether it's part of a larger
> program. If it *is* the end goal (namely, you just want the
> filtered output someplace), and you're not adverse to using
> other tools, you can do something like

>   sed -n -e'1,/abc/p' -e'/xyz/,$p' file.txt

Or even

awk '/abc/,/xyz/' file.txt

Excluding the abc and xyz lines is left as an exercise to the
interested reader.

Regards,
Dan

-- 
Dan Sommers

"I wish people would die in alphabetical order." -- My wife, the genealogist
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New tail recursion decorator

2006-05-12 Thread Duncan Booth
Tim N. van der Leeuw wrote:

> The other thing I do not understand, due to my limited understanding of
> what is tail-recursion: factorial2 (Duncan's definition) is not proper
> tail-recursion. Why not? How does it differ from 'real' tail recursion?

Tail recursion is when a function calls itself and then immediately returns 
the result of that call as its own result. So long as nothing except 
returning the result needs to be done it is possibly to avoid the recursive 
call altogether.

This function is tail recursive:

@tail_recursion
def factorial(n, acc=1):
"calculate a factorial"
if n == 0:
   return acc
res = factorial(n-1, n*acc)
return res

but this one isn't:

@tail_recursion
def factorial2(n):
"calculate a factorial"
if n == 0:
   return 1
return n * factorial2(n-1)

because when the inner call to factorial2() returns the function still has 
to do some work (the multiplication).

I don't understand your comments about speed differences. If you try to run 
factorial2() as defined above then it simply throws an exception: there 
are no results to compare. My guess is that when you wrote:

@tail_recursion
def factorial2(n):
# do the stuff
pass

your 'do the stuff' actually had an erroneous call to 'factorial'. If you 
are going to rename the function you have to rename the recursive calls as 
well. (At least, that's what I forgot to do when I first tried it and 
couldn't understand why it gave me an answer instead of crashing.)

The decorator also fails for functions which are tail-recursive but which 
contain other non-tail recursive calls within themselves. For example I 
would be pretty sure you couldn't write a working implementation of 
Ackermann's function using the decorator:

def Ack(M, N):
if (not M):
return( N + 1 )
if (not N):
return( Ack(M-1, 1) )
return( Ack(M-1, Ack(M, N-1)) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NEWBIE: Tokenize command output

2006-05-12 Thread Tim Chase
> I reeducated my fingers after having troubles with huge files !-)

I'll keep it in mind...the prospect of future trouble with 
large files is a good kick-in-the-pants to remember.

>>Otherwise, just to be informed, what advantage does rstrip() have over
>>[:-1] (if the two cases are considered uneventfully the same)?
> 
> 1/ if your line doesn't end with a newline, line[:-1] will still remove
> the last caracter.

Good catch.  Most *nix editors are smart about having a 
trailing NL character at the end of the file, but some 
Windows text-editors aren't so kind.

> 2/ IIRC, if you don't use universal newline and the file uses the
> DOS/Windows newline convention, line[:-1] will not remove the CR - only
> the LF (please someone correct me if I'm wrong here).

To get this behavior, I think you have to open the file in 
binary mode.  To me, opening as binary is a signal that I 
should be using read() rather than readlines() (or 
xreadlines, or the iterator, or whatever).  If you've opened 
in binary mode, you might have to use rstrip("\r\n") to get 
both possible line-ending characters.

> I know this may not be a real issue in the actual case, but using
> rstrip() is still a safer way to go IMHO - think about using this same
> code to iterate over a list of strings without newlines...

Makes sense.  Using rstrip("\r\n") has all the benefits, 
plus more gracefully handles cases where a newline might not 
be present or comprised of two (or more) characters.  Got 
it!  Thanks for the explanation.

-tkc



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


Re: New tail recursion decorator

2006-05-12 Thread Tim N. van der Leeuw

Duncan Booth wrote:
> Tim N. van der Leeuw wrote:
>
[...]
> @tail_recursion
> def factorial2(n):
> # do the stuff
> pass
>
> your 'do the stuff' actually had an erroneous call to 'factorial'. If you
> are going to rename the function you have to rename the recursive calls as
> well. (At least, that's what I forgot to do when I first tried it and
> couldn't understand why it gave me an answer instead of crashing.)
[...]

Duncan,

You're totally right. Somehow, I had managed to completely overlook
this. Oops!
My apologies! :)

--Tim

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


Re: NEWBIE: Tokenize command output

2006-05-12 Thread Duncan Booth
bruno at modulix wrote:

>> Otherwise, just to be informed, what advantage does rstrip() have over
>> [:-1] (if the two cases are considered uneventfully the same)?
> 
> 1/ if your line doesn't end with a newline, line[:-1] will still remove
> the last caracter.
> 
In particular, if the last line of the file doesn't end with a newline then 
the last line you read won't have a newline to be stripped.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads

2006-05-12 Thread Grant Edwards
On 2006-05-12, antred <[EMAIL PROTECTED]> wrote:

Nerver knew what?  Please quote for context.

> Aww shoot, I never knew that!!

http://docs.python.org/lib/QueueObjects.html

  get([block[, timeout]])

Remove and return an item from the queue. If optional args
block is true and timeout is None (the default), block if
necessary until an item is available. [...]

-- 
Grant Edwards   grante Yow!  VICARIOUSLY
  at   experience some reason
   visi.comto LIVE!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threads

2006-05-12 Thread Grant Edwards
On 2006-05-12, Sybren Stuvel <[EMAIL PROTECTED]> wrote:
> placid enlightened us with:
>>> Did you read the documentation for Queue methods?
>>
>> there is no need to be patronizing about this dude, im just learning
>> Python in my spare time, as im a Intern Software Engineer
>
> There is nothing patronizing about the question, it's merely
> an enquiry to a possible fact. If you're going to be a techie,
> you should learn stuff like that.

It's also valuable information to the maintainers of the
documentation.  If he _did_ read the documentation and still
didn't know that Queue.get() could block, then one might ask
how the documentation could be improved.

-- 
Grant Edwards   grante Yow!  Is this ANYWHERE,
  at   USA?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


listener program in Python

2006-05-12 Thread diffuser78
I want to write a simple clinet/server program that does the following.

On Windows, the program listens to the request from linux box

On Linux Box, client program send server a shutdown request and the
program at server i.e windows shuts windows sown,

I basically want to remotely shut down windows from linux and write
such a program in python.

Every help is appreciated.

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


Re: A critic of Guido's blog on Python's lambda

2006-05-12 Thread jayessay
"Michele Simionato" <[EMAIL PROTECTED]> writes:

> I was interested in a proof of concept, to show that Python can
> emulate Lisp special variables with no big effort.

OK, but the sort of "proof of concept" given here is something you can
hack up in pretty much anything.  So, I wouldn't call it especially
convincing in its effect and capability.


/Jon

-- 
'j' - a n t h o n y at romeo/charley/november com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where do you run database scripts/where are DBs 'located'?

2006-05-12 Thread CatDude
On Fri, 12 May 2006 14:01:51 +, John Salerno wrote:

> Ok, I've been browsing through the MySQLdb docs, and I *think* I know 
> the kind of code I need to write (connect, cursor, manipulate data, 
> commmit, etc. -- although I probably need to get more familiar with 
> actual SQL commands too), but here's my problem: I don't know where 
> these scripts are supposed to be executed, or how they are supposed to 
> 'find' the database.

I'm kind of a noob myself, but I'll see if I can't offer some useful info
anyhow.

When you issue your MySQLdb.connect, that determines where the database
actions occur. If you specify "host='localhost'", then you are trying to
connect to your local machine. If you specify "host='db.smurgle.net'",
you're trying to connect to my home db server. You can specify the
hostname in any format that your local machine understands; for example,
if you are on a Linux box, and your /etc/hosts file contains a line like:
10.0.0.10  myDBserver
then you can use "host='myDBserver'".

This isn't so much a web programming issue as it is using MySQL's network
interface. MySQL by default uses port 3306 (I think) to handle database
connections over the network.

> But my question is, can these DB scripts be executed anywhere, and they
> will find the DB based on the connect() parameters? Or do I need to do
> something special with them? It seems like a similar problem to when you
> don't have your PYTHONPATH variable set up properly. I've tried some DB
> stuff, but it doesn't seem to work.

Your scripts that make connections can be executed from anywhere that:
1) knows how to communicate with the specified database server, and
2) has some sort of MySQL client available.

> So without actually giving you some code and tracebacks, is there any
> general advice about how to set up these scripts? Also, is there any
> better documentation than this:
> http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307

If you are having problems, by all means post some code.

> It doesn't seem too thorough, and it also doesn't cover actual SQL
> queries that you'd have to pass to the query method. Maybe I will just
> have to find that information in a MySQL tutorial.

A couple of good MySQL tutorials would most likely be a big help. The
standard docs (the ones you pointed out) are not of a great deal of help
if you're totally new to SQL. You might want to do a Google search. This
will lead you to pages like:
http://www.kitebird.com/articles/pydbapi.html
http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/
and the like.

Dan

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


Re: listener program in Python

2006-05-12 Thread simon . hibbs
[EMAIL PROTECTED] wrote:

> I basically want to remotely shut down windows from linux and write
> such a program in python.

You probably don't need to write a service in windows for this. All you
need is to write your Linux python program with an SNMP library and
configure the Windows box to accept SNMP calls to shut down. Frankly
I'm not 100% sure how to do this. You'd have to enable the SNMP Agent
on Windows, and probably the "Force shutdown from a remote system"
system policy would have to be changed.

The O'Reilly book "Python programming on Win32" explains how to write
Windows services and do basic networking. This article explains one
way: http://tinyurl.com/ezjx7

Simon Hibbs

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


Re: find all index positions

2006-05-12 Thread vbgunz
Hello John,

Thank you very much for your pointers! I decided to redo it and try to
implement your suggestion. I think I did a fair job and because of your
suggestion have a better iterator. Thank you!

def indexer(string, substring, overlap=1):
'''indexer(string, substring, [overlap=1]) -> int

indexer takes a string and searches it to return all substring
indexes. by default indexer is set to overlap all occurrences.
to get the index to whole words only, set the overlap argument
to the length of the substring. The only pitfall to indexer is
it will return the substring whether it stansalone or not.

>>> list(indexer('ababababa', 'aba'))
[0, 2, 4, 6]

>>> list(indexer('ababababa', 'aba', len('aba')))
[0, 4]

>>> list(indexer('ababababa', 'xxx'))
[]

>>> list(indexer('show chow', 'how'))
[1, 6]
'''

index = string.find(substring)
if index != -1:
yield index

while index != -1:
index = string.find(substring, index + overlap)
if index == -1: continue
yield index

if __name__ == '__main__':
print list(indexer('ababababa', 'aba'))  # -> [0, 2, 4, 6]
print list(indexer('ababababa', 'aba', len('aba')))  # -> [0, 4]
print list(indexer('ababababa', 'xxx'))  # -> []
print list(indexer('show chow', 'how'))  # -> [1, 6]

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


Re: where do you run database scripts/where are DBs 'located'?

2006-05-12 Thread John Salerno
CatDude wrote:
> On Fri, 12 May 2006 14:01:51 +, John Salerno wrote:
> 
>> Ok, I've been browsing through the MySQLdb docs, and I *think* I know 
>> the kind of code I need to write (connect, cursor, manipulate data, 
>> commmit, etc. -- although I probably need to get more familiar with 
>> actual SQL commands too), but here's my problem: I don't know where 
>> these scripts are supposed to be executed, or how they are supposed to 
>> 'find' the database.
> 
> I'm kind of a noob myself, but I'll see if I can't offer some useful info
> anyhow.

Thanks very much for the info! I'll give the 'localhost' a try again and 
see if I was creating problems elsewhere, perhaps with the commands 
themselves. (All I know for sure is that I created a MySQL database and 
filled it with baseball statistics, so I know *that* exists, at least! 
But it was created from the MySQL prompt itself, not using Python.)

I'll also read over those links, they seem like the kind of thing I need 
to really get going with it. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find all index positions

2006-05-12 Thread vbgunz
I forgot to explain my reason for over shadowing the 'string' built-in
within my iterator. To me, it doesn't matter because the string
identifier is temporary within the function and dies when the function
dies. Also, I personally don't use the string function and prefer
''.join('hi'), etc. Also, at least for me just starting out in Python,
I find 'string' to be as readable as possible :)

what do you think about that?

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


Re: Decorator

2006-05-12 Thread Sybren Stuvel
Martin Blume enlightened us with:
> Another question: Isn't decorating / wrapping usually done at
> runtime, so that the @deco notation is pretty useless (because you'd
> have to change the original code)?

Please explain why that would make the @deco notation pretty useless.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time to bundle PythonWin

2006-05-12 Thread Dave Benjamin
On Thu, 11 May 2006, Alex Martelli wrote:

> Dave Benjamin <[EMAIL PROTECTED]> wrote:
>   ...
>> It's time to bundle PythonWin.
>
> No: the Python Standard Distribution, in 2.5, includes instead ctypes,
> which is lower-level than PythonWin but more general (exists for other
> platforms, lets you call other DLLs on Windows and not just those
> wrapped for you by the author).

I didn't realize you could do COM with ctypes. Thanks for the tip! Are 
there any caveats to this approach?

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


Re: Decorator

2006-05-12 Thread bruno at modulix
Martin Blume wrote:
> "bruno at modulix" schrieb 
> 
(snip)
>>def deco(func):
>>  print "decorating %s" % func.__name__
>>  def _wrapper(*args, **kw):
>>print "%s called " % func.__name__
>>res = func(*args, **kw)
>>print "%s returned %s" % (func.__name__, str(res))
> 
>   return res
>   ^^
> Shouldn't here be a return res, so that wrapper
> behaves like the original function?

oops, my bad :(
And yes, of course.

> 
>>  return _wrapper
>>
>># python < 2.4
>>def somefunc():
>>  print "in somefunc"
>>  return 42
>>
>>somefunc = deco(somefunc)
>>
> 
> Thanks for the explanation.
> 
> 
> Another question: Isn't decorating / wrapping usually
> done at runtime,

It is. I mean, using decorator syntax, this is done during import, which
happens at runtime.

> so that the @deco notation is pretty
> useless (because you'd have to change the original 
> code)?

I don't understand your question.

> What do I miss here?

Ok, I get it (well, I think...).

The use case for @decorator is for wrapping functions or method *in the
module/class itself*. It's not for module client code (but this of
course doesn't prevent client code to dynamically add other wrappers...)

One of the primary use case makes this pretty clear IHMO : classmethod
and staticmethod :

# python < 2.4:
class Cleese(object):
  def doSillyWalk(cls):
 pass
  doSillyWalk = classmethod(doSillyWalk)

# python >= 2.4:
class Cleese(object):
  @classmethod
  def doSillyWalk(cls):
 pass

Another example : CherryPy uses decorators to mark methods which are
'published' (ie: are action controllers responding to a given URL)


HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NEWBIE: Tokenize command output

2006-05-12 Thread bruno at modulix
Duncan Booth wrote:
> bruno at modulix wrote:
> 
> 
>>>Otherwise, just to be informed, what advantage does rstrip() have over
>>>[:-1] (if the two cases are considered uneventfully the same)?
>>
>>1/ if your line doesn't end with a newline, line[:-1] will still remove
>>the last caracter.
>>
> 
> In particular, if the last line of the file doesn't end with a newline then 
> the last line you read won't have a newline to be stripped.

Thanks - I knew there was a corner case for files, but couldn't remember
it exactly.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: listener program in Python

2006-05-12 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> 
> 
>>I basically want to remotely shut down windows from linux and write
>>such a program in python.
> 
FWIW, s/from linux/from another machine/

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which windows python to use?

2006-05-12 Thread Robert Kern
Robert Kern wrote:
> James Stroud wrote:
> 
>>Robert Kern wrote:
>>
>>>James Stroud wrote:
>>>
Enthought does not play well with cygwin, I've noticed.
>>>
>>>In what way? Does the mingw gcc that we distribute interfere with Cygwin's 
>>>gcc?
>>
>>One can not run the enthought python interactive interpreter from a 
>>cygwin x-window session, it locks up.
> 
> Interesting. I've seen the same thing with MSYS's rxvt ("native", not X). I
> presumed it was a strange interaction between bash and (any) Python. Looks 
> like
> it may just be our Python, then. I'll enter a ticket on our Trac. Thank you!

My officemate notes that we ship readline. It is possible that readline is
expecting CMD.EXE not a decent terminal.

-- 
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: Replace

2006-05-12 Thread Anthra Norell
se = SE.SE (r' "~=.~=\=#')
>>> se ('tyrtrbd =ffgtyuf == =tyryr =u=p ff')
'tyrtrbd =#fgtyuf =# =#yryr =#=# ff'


I am in the final stages of documenting my stream editor SE. There are quite
a few problems raised on this list which SE would handle elegantly. Where do
I propose it for distribution?

Frederic


- Original Message -
From: "Eric" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: 
Sent: Sunday, May 07, 2006 1:35 AM
Subject: Re: Replace


> On 2006-05-06, Dennis Lee Bieber wrote:
> > On Sat, 06 May 2006 19:55:35 GMT, Dennis Lee Bieber
> ><[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> >
> >
> >> splits = encData.split("#", 1)
> >
> > Whoops # => =
> >
> > Since there are only what, five, escaped characters, the use of a
> > translate table seems somewhat overkill... A simple dictionary can be
> > used...
> >
> > #   pseudo-yENC decoder
> > #   ignores all of the protocol except for the
> > #   data portion decode
> >
> > d42 = "".join([chr((x - 42) % 256) for x in range(256)])
> > d64 = { "@" : "\0",
> > "I" : "\t",
> > "J" : "\n",
> > "M" : "\r",
> > "}" : "="   }
> > e42 = "".join([chr((x + 42) % 256) for x in range(256)])
> > e64 = { "\0" : "=@",
> > "\t" : "=I",
> > "\n" : "=J",
> > "\r" : "=M",
> > "=" : "=}"  }
> >
> > def decode(encData):
> > segments = []
> > while True:
> > splits = encData.split("=", 1)
> > segments.append(splits[0])
> > if len(splits) == 1:break
> > segments.append(d64[splits[1][0]])
> > encData = splits[1][1:]
> >
> > decData = "".join(segments).translate(d42)
> > return decData
> >
> > def encode(decData):
> > segments = []
> > encData = decData.translate(e42)
> > while encData:
> > pos = len(encData)
> >
> > nl = encData.find("\0")
> > tb = encData.find("\t")
> > lf = encData.find("\n")
> > cr = encData.find("\r")
> > eq = encData.find("=")
> >
> > if nl != -1:
> > pos = min(pos, nl)
> > if tb != -1:
> > pos = min(pos, tb)
> > if lf != -1:
> > pos = min(pos, lf)
> > if cr != -1:
> > pos = min(pos, cr)
> > if eq != -1:
> > pos = min(pos, eq)
> >
> > segments.append(encData[:pos])
> >
> > if pos < len(encData):
> > segments.append(e64[encData[pos]])
> > encData = encData[pos+1:]
> >
> > return "".join(segments)
> >
> >
> > if __name__ == "__main__":
> > junk = """This is not
> > the end of the silliness
> > being inflicted upon the world of 183743ljf8734jflu807ur32"""
> >
> > morejunk = encode(junk)
> > print morejunk
> >
> > print decode(morejunk)
> > print
> >
> > tbl = "".join([chr(x) for x in range(256)])
> >
> > print repr(tbl)
> > print
> > yetmore = encode(tbl)
> > print repr(yetmore)
> > print
> > print repr(decode(yetmore))
>
> I think you right about the d64 translation thing, it does seem like
overkill.
> I've been playin with sting.split(), came up with...
>
> def decode(encData):
>   segments = []
>   splits = encData.split("=")
>   for i in range(len(splits)):
> if i == 0:
>   segments.append(splits[0].translate(d42))
> else:
>   segments.append(splits[i][0].translate(d64) +
splits[i][1:].translate(d42
> ))
>
>   decoded = ''.join(segments)
>   return decoded
>
> string.split might be the way to go, this function almost decodes the test
file
> from the ydec site correctly.
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: New tail recursion decorator

2006-05-12 Thread Kay Schluehr
Duncan Booth wrote:

> The decorator also fails for functions which are tail-recursive but which
> contain other non-tail recursive calls within themselves. For example I
> would be pretty sure you couldn't write a working implementation of
> Ackermann's function using the decorator:
>
> def Ack(M, N):
> if (not M):
> return( N + 1 )
> if (not N):
> return( Ack(M-1, 1) )
> return( Ack(M-1, Ack(M, N-1)) )

Definitely. The translation into a proper tail-recursive form is
non-trivial but nevertheless possible as demonstrated by the following
Ackermann implementation:

@tail_recursion
def ack(m,n,s=[0]):   # use a stack-variable s as "accumulator"
if m==0:
if s[0] == 1:
return ack(s[1]-1,n+1,s[2])
elif s[0] == 0:
return n+1
elif n==0:
return ack(m-1,1,s)
else:
return ack(m,n-1,[1,m,s])

Regards,
Kay

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


Re: which windows python to use?

2006-05-12 Thread Robert Kern
Don Taylor wrote:
> Robert Kern wrote:
> 
>>In what way? Does the mingw gcc that we distribute interfere with Cygwin's 
>>gcc?
> 
> Robert:
> 
> Which C compiler will you be using for the Enthought 2.4 Windows release?

Define "using". We build Python with whatever compiler the official build is
compiled with. In this case, MSVC 7., I think . For this release, we
will ship the latest available gcc available for mingw. Some of the extension
modules will be built with this gcc.

-- 
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: A critic of Guido's blog on Python's lambda

2006-05-12 Thread Alexander Schmolck
jayessay <[EMAIL PROTECTED]> writes:

> "Michele Simionato" <[EMAIL PROTECTED]> writes:
> 
> > I was interested in a proof of concept, to show that Python can
> > emulate Lisp special variables with no big effort.
> 
> OK, but the sort of "proof of concept" given here is something you can
> hack up in pretty much anything. 

Care to provide e.g. a java equivalent?

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


TkTable for info gathering

2006-05-12 Thread Gary Wessle
Hi

I just finished with 1.5 tutorials about Tkinter, my thought is to use
a table "maybe TkTable" to gather info from the user as to what file
to chart data from, as well as info provided by the TkTable
properties. 
each cell of the table will be either empty or contains a file path,
let x=1  be the x-index of the cells on the first col and y=1 be the
y-index of the cells on the first row. the position of the cell with
the max-x and max-y will determine how many frames will be displayed,
grid with x columns corresponding to max-x and x rows corresponding to
max-y.

i.e, the look of the table will resemble the gui, empty cell -> empty
frame, cell with filepth -> frame with canvas. 

is TkTable or NovaGrid suitable for this?

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


Re: New tail recursion decorator

2006-05-12 Thread Alexander Schmolck
Duncan Booth <[EMAIL PROTECTED]> writes:

> Tim N. van der Leeuw wrote:
> 
> > The other thing I do not understand, due to my limited understanding of
> > what is tail-recursion: factorial2 (Duncan's definition) is not proper
> > tail-recursion. Why not? How does it differ from 'real' tail recursion?
> 
> Tail recursion is when a function calls itself and then immediately returns 
> the result of that call as its own result. 

I think the definition is broader than that so that these two functions would
also be tail-recursive (i.e. the tail call doesn't have to be a self-tail
call; I might be mistaken, don't have a good reference at hand; however
"properly tail recursive" certainly refers to being able to do the below
without exhausting the stack even for large n, not just transforming self-tail
calls to a loop, which is sort of limited usefulness anyway):

def even(n):
return n == 0 or not odd(n-1)

def odd(n):
return n == 1 or not even(n-1)

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


Re: Reg Ex help

2006-05-12 Thread Anthra Norell
>>> se = SE.SE (' "~/[A-Za-z0-9_]+/CHECKEDOUT~==" | /= CHECKEDOUT=')
>>> se
('/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT')
'dbg_for_python'

If I understand your problem, this might be a solution. It is a stream
editor I devised on the impression that it could handle in a simple manner a
number of relatively simple problems on this list for which no
commensurately simple methodologies seem to exist. I intend to propose it to
the group when I finish the doc. Meantime who do I propose it to?

Frederic


- Original Message -
From: "don" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: 
Sent: Thursday, May 11, 2006 7:39 PM
Subject: Reg Ex help


> I have a string  from a clearcase cleartool ls command.
>
> /main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT
> from /main/parallel_branch_1/release_branch_1.0/4
>
> I want to write a regex that gives me the branch the file was
> checkedout on ,in this case - 'dbg_for_python'
>
> Also if there is a better way than using regex, please let me know.
>
> Thanks in advance,
> Don
>
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Best Mobile Devices for Python

2006-05-12 Thread Jeremy Winters
I have a project where I need to remote control one computer through a wireless tcp/ip connection in my home through a linksys router.I know there are versions of python that have been ported to mobile devices... but the whole arena of mobile devices is kind of intimidating... as it's hard to get to know the true usability of a device... as well as the ease of development for it... unless you actually have one.I don't need a GUI... a text based interface is fine for what I'm doing.Any suggestions for devices?  Anybody ever done something similar?Thanks!Jeremy
		New Yahoo! Messenger with Voice. Call regular phones from your PC and save big.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Decorator

2006-05-12 Thread Martin Blume
"Sybren Stuvel" schrieb
> Martin Blume enlightened us with:
Don't know if I enlightened anybody ... :-)

> > Another question: Isn't decorating / wrapping
> >  usually done at runtime, so that the @deco 
> > notation is pretty useless (because you'd
> > have to change the original code)?
> 
> Please explain why that would make the @deco 
> notation pretty useless.
> 
Well, if you're changing the original module, you
might as well insert the needed functionality in
the original function, no?
Or rename the original function, write a function
having this original name and calling from it the
original functionality?

Isn't the point of a decorator to change the 
behavior externally, at runtime, possibly changing
it in different ways at different places at different
times?

So why this @deco notation? Can you apply it externally?
Meaning to 
import module
first, then
@deco(module.func)
somewhere later?


Martin



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


Re: Decorator

2006-05-12 Thread Martin Blume
"bruno at modulix" schrieb 
> 
> [snip]
>
> The use case for @decorator is for wrapping functions
> or method *in the module/class itself*. 
That was the question. What's the use of doing it 
like that in the module *itself* (I mean, you change
directly the original function)?

> It's not for module client code (but this of
> course doesn't prevent client code to dynamically 
> add other wrappers...)
> 
How do the clients it? The "oldfashioned"
deco(doSillyWalk)
way?

Martin




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


Re: Decorator

2006-05-12 Thread bruno at modulix
Martin Blume wrote:
> "Sybren Stuvel" schrieb
> 
>>Martin Blume enlightened us with:
> 
> Don't know if I enlightened anybody ... :-)

Not sure...

But let's hope someone else having doubts about @decorator will find
this thread, so we won't have to point him/her to the documentation.

>>>Another question: Isn't decorating / wrapping
>>> usually done at runtime, so that the @deco 
>>>notation is pretty useless (because you'd
>>>have to change the original code)?
>>
>>Please explain why that would make the @deco 
>>notation pretty useless.
>>
> 
> Well, if you're changing the original module,

Who's talking about "changing the original module" ?

> you
> might as well insert the needed functionality in
> the original function, no?

higher order functions allow to keep orthogonal responsabilities
separated.

(snip)

> Isn't the point of a decorator to change the 
> behavior externally, at runtime, possibly changing
> it in different ways at different places at different
> times?

You're confusing the python specific @decorator syntax with the OO
design pattern by the same name. This syntax is purely syntactic sugar
for a specific use case of higher order functions.

> So why this @deco notation? 

To improve readability.

@decorator
def my_one_hundred_locs_func():
  ...

is much more readable than:
def my_one_hundred_locs_func():
  ...
  # 100 LOCS later
my_one_hundred_locs_func = decorator(my_one_hundred_locs_func)

> Can you apply it externally?

No. It doesn't make sens to replace:
  mymodule.func = decorator(mymodule.myfunc)
with
  @decorator
  mymodule.func

Note that all this should be clear for anyone having read the doc...

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Discussion: Python and OpenMP

2006-05-12 Thread Carl J. Van Arsdall
Hey everyone,

I know I've posted several questions regarding python and python's 
parallel capabilities so bear with me as I've never attempted to incite 
discussion.  However, today I'm interested in sparking discussion over 
having an OpenMP style of interface in python.

For those of you familiar with OpenMP, its a pragmatic api for 
parallelizing software.  For more information I invite anyone to do some 
google searches, there's a plethora of information available. Just to 
give a simple example of what i'm talking about, in OpenMP you would 
insert a pragma above a section of code you want to parallelize.

In C it might look something like:

int main(int argc, char* argv[])
{
  #pragma omp parallel  
  printf("Hello, world.\n");
  return 0;
}

In which case threads are spawn and handled.  OpenMP of course has more 
than this available for developers, but I'm just trying to paint a 
picture before I start asking questions. 

Anyhow, onto the meat of the discussion.  Would the python community be 
interested in parallel programming this way?  Although I understand 
python already supports threading I thought that this was a real 
interesting (and easy) way of writing parallel code. 

For example, new keywords could be added to the python interpreter, such 
as parallel:

Ex:
###
#!usr/bin/python

parallel:
  print "I am a thread"

###


Taking this a step further, OpenMP or an OpenMP style implementation 
could be added to python.  In addition easy to use/read, one possible 
benefit I could see of writing parallel python code this way would be 
providing a layer of abstraction between parallel code and threading 
constructs.  For example, as a developer or community standards change 
threading in python code would not have to be re-written.  Developers 
would create an interface between python's OpenMP style code and 
whatever their new threading libraries may be (this is one of many ways 
it could happen).  Ultimately providing more code portability between 
people using different threading standards (should they ever become 
available).  I see other use cases as well, but I just wanted to throw a 
couple ideas to see if this was worth thinking about further.

Thanks for reading this one, I know it was long but I'd really 
appreciate your comments!



-Carl


-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: How to get a part of string which follows a particular pattern usingshell script

2006-05-12 Thread Anthra Norell
This is the third problem today which I propose to solve with my stream
editor SE. If the group thinks it could be useful I would submit it the
moment I'm done with the doc, which is in the final stage.

Frederic

>>> se = SE.SE (' ~addr=[0-9.]+~==(10) | addr\== ')
>>> string = """(a)test="192.168.1.17:/home/ankur/nios_fson/mnt/tmptype
> nfs(rw,addr=192.168.1.17)"
> b)test="/dev/root on / typr nfs
> (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93)")""")
>>> print se (string)
192.168.1.17
192.168.1.93


- Original Message -
From: "Hari" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: 
Sent: Monday, May 08, 2006 12:18 PM
Subject: How to get a part of string which follows a particular pattern
usingshell script


> Hi all,
>
> I need to get a part of string which follows a pattern 'addr='
>
>
> For example:
>
>
> a)test="192.168.1.17:/home/ankur/nios_fson/mnt/tmptype
> nfs(rw,addr=192.168.1.17)"
> b)test="/dev/root on / typr nfs
> (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93)"
>
>
> I need to get the ipaddress from the above two strings a and b which
> follows 'addr='. I tried to use cut, but it accepts only single charter
>
> as delimiter. If I give delimiter as 'addr=' for cut command it gives
> me a error.
>
>
> So please help me.
>
>
> A bunch of thanks in advance.
>
>
> Regards,
> P.R.Hariram
>
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: which is better, string concatentation or substitution?

2006-05-12 Thread bruno at modulix
Ted wrote:
> Thank you Roy.
> 
> It seems if you lurk here long enough you eventually get all you
> questions answered without even asking!
> ;-)
> 
+1 QOTW


please avoid top-posting, and please avoid posting back a long message
just to add three lines.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator

2006-05-12 Thread Martin Blume
"bruno at modulix"  schrieb 
> > 
> > Well, if you're changing the original module,
> Who's talking about "changing the original module" ?
> 
Well, you have to apply @deco in the module where
func_to_decorated is placed.

>
> > Isn't the point of a decorator to change the 
> > behavior externally, at runtime, possibly changing
> > it in different ways at different places at 
> > different times?
> 
> You're confusing the python specific @decorator 
> syntax with the OO design pattern by the same name. 
> This syntax is purely syntactic sugar
> for a specific use case of higher order functions.
>
Yes, that explains my confusion.

> 
> > So why this @deco notation? 
> 
> To improve readability.
> 
> @decorator
> def my_one_hundred_locs_func():
>   ...
> 
> is much more readable than:
> def my_one_hundred_locs_func():
>   ...
>   # 100 LOCS later
> my_one_hundred_locs_func = decorator (my_one_hundred_locs_func)
>
That makes sense.

> 
> Note that all this should be clear for anyone having 
> read the doc...
> 

Errm, yes, you're so right.

Thanks for reading the documentation to me 
and clearing this up :-)

Martin


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


Re: which windows python to use?

2006-05-12 Thread Robert Kern
James Stroud wrote:
> Robert Kern wrote:
> 
>>James Stroud wrote:
>>
>>>Enthought does not play well with cygwin, I've noticed.
>>
>>In what way? Does the mingw gcc that we distribute interfere with Cygwin's 
>>gcc?
> 
> One can not run the enthought python interactive interpreter from a 
> cygwin x-window session, it locks up.

Our build person tells me that he sees the same problem with the standard build
of Python.

http://svn.enthought.com/enthought/ticket/715

-- 
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


Wrong args when issuing a SIGUSR1 signal

2006-05-12 Thread Sori Schwimmer
Hi All,

Say I launch a shell under KDE and start typing:


$ python
Python 2.4.2 (#10, Feb 16 2006, 17:44:37)
[GCC 3.3.5-20050130 (Gentoo 3.3.5.20050130-r1,
ssp-3.3.5.20050130-1, pie-8.7.7. on linux2
Type "help", "copyright", "credits" or "license" for
more information.
>>> def fn(a=0,b=0):
...   print 'Arguments:',a,b
...
>>> from signal import *
>>> signal(SIGUSR1,fn)


Now, suppose I'm launching a second shell, and typing:


$ ps ax
 ... (cut for brevity) ...
 5780 pts/2S+ 0:00 python
 5781 pts/1R+ 0:00 ps ax
$ python
Python 2.4.2 (#10, Feb 16 2006, 17:44:37)
[GCC 3.3.5-20050130 (Gentoo 3.3.5.20050130-r1,
ssp-3.3.5.20050130-1, pie-8.7.7. on linux2
Type "help", "copyright", "credits" or "license" for
more information.
>>> from signal import *
>>> import os
>>> os.kill(5780,SIGUSR1)
>>>


Now, back in the first shell, after pressing 
once, I get:


Arguments: 10 


Obviously, I put the two args after experimenting
without them, and receiving an error:


TypeError: fn() takes no arguments (2 given)


What is going on here? How should I handle this?

Thanks,
Sorin Schwimmer

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Unix Tools (was: deleting texts between patterns)

2006-05-12 Thread Edward Elliott
Dan Sommers wrote:
> Or even
> 
> awk '/abc/,/xyz/' file.txt
> 
> Excluding the abc and xyz lines is left as an exercise to the
> interested reader.

Once again, us completely disinterested readers get the short end of the
stick. :)

-- 
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator

2006-05-12 Thread bruno at modulix
Martin Blume wrote:
> "bruno at modulix" schrieb 
> 
>>[snip]
>>
>>The use case for @decorator is for wrapping functions
>>or method *in the module/class itself*. 
> 
> That was the question. What's the use of doing it 
> like that in the module *itself* 
Readability.

Since the decoration (in the module) is somehow part of the function
definition, it's more obvious to have it expressed with a modifier-like
syntax at the top of the def statement than expressed as a function call
and rebinding after the end of def block. When reading the code, with
the @decorator syntax, the use of the decorator is pretty evident.

Once again, this is nothing more than syntactic sugar - but syntactic
sugar counts. FWIW, function decorators seems to be *much* more used
since the introduction of the @decorator syntax, when you could do the
same thing since the introduction of nested scopes and closures in
Python (dont remember the version, but this is not really new).

> (I mean, you change
> directly the original function)?

If you mean that the code added by the decorator could be injected
directly in the function, that's not always true (ie: classmethod and
staticmethod for example), and it just plain sucks anyway - you don't
write a decorator for a single function, you write it to separate
orthogonal concerns, like tracing, handling auth, partial application of
function, etc...

>>It's not for module client code (but this of
>>course doesn't prevent client code to dynamically 
>>add other wrappers...)
>>
> 
> How do the clients it? 

Like it did since there are nested scopes and closures in Python. Higher
order functions are not really something new, you know - Lisp had them
way back in 1958 !-)

> The "oldfashioned"
> deco(doSillyWalk)
> way?

from monty.python import Cleese
Cleese.doSillyWalk = deco(Cleese.doSillyWalk)

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter: ability to delete widgets from Text and then re-add them

2006-05-12 Thread nholtz
Is there any way to delete a widget (window) from a Text widget, and
then add it back
to the Text, without re-creating the original widget.  For example, I
think I would like to do
something like the following:
##
from Tkinter import *

root = Tk()

textWidget = Text( root )
textWidget.pack()

 create some widgets
widgets = [ Label( textWidget, text=" Hello World #%d! " % (i,) ) \
for i in range(3) ]

 add all of them to Text
for widget in widgets:
posn = textWidget.index(INSERT)
textWidget.window_create( posn, window=widget )

 delete the last one from Text
widget - widgets[-1]
textWidget.delete( posn )  # doesn't delete from children of Text
widget.destroy()  # this doesn't seem to make any diff, but it does
delete from children

 try to add it again
textWidget.window_create( posn, window=widget )   FAILS !!!

root.mainloop()
###

That last window_create fails with:

_tkinter.TclError: bad window path name ".1076792812.1076865452"

I woule like to create a number of widget objects, then add / subtract
/ re-add them in
a predicatable order (stack-like)

I'm trying to implement 'Wizard-like' behaviour, but in a single Text
window, where
you step through in small chunks, adding new widgets, but are able to
step backwards
by deleteing them.  I was hoping not to have to re-create the widgets
again when
moving forwards, as I was hoping for an easy way to maintain the state.

thanks
neal

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


How to pass variables between scripts?

2006-05-12 Thread Gross, Dorit (SDRN)
Title: How to pass variables between scripts?







Dear list,


I am an absolute newbie to python and would appreciate your help very much  :)


I am trying to write a little python script that wraps a set of external scripts. The external scripts are either also written in python or are simple bash scripts. My wrapping script should be able to send an argument to the first script, to execute it, to read its results and to send them then as arguments into the next script.

This is the first part that I have written so far: 


#! /usr/local/bin/python

# test_exec.py


import os, sys, glob


fileList = glob.glob('/data/*.ZIP')


for f in fileList:

    try: 

        globvars = {'infile' : f}

        locvars = {}

        execfile('/scripts/second.py', globvars(), locvars)

    except IOError:

        exit(0)

    print locvars



And this is what happens when calling test_exec.py


 ./test_exec.py 

Traceback (most recent call last):

  File "./test_exec.py", line 19, in ?

    execfile('/scripts/second.py', vars(), results)

TypeError: 'dict' object is not callable



I tried already to modify the script in different ways but wasn't successful so far to make it running. Could you maybe help what I am missing? Further, I am not sure how the second python has to look like to actually read what is given in "globvars" and to sent its results into "locvars". 

Or might os.popen* be a better option?  




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

  1   2   >