Re: round function problem

2005-09-06 Thread Bengt Richter
On Tue, 06 Sep 2005 09:27:48 +0200, mg <[EMAIL PROTECTED]> wrote:

>Hi everybody...
>
>We try to white scripts with Pyrhon 2.4 for an acoustic simulation and 
>we wrote these follow lines :
>
>
>c = 340
340 is an integer, which is different from 340.
>i =j=k= 1
>sum_ = 23
also an integer
>table = []
>freq = round((c/2*(sum_)**0.5),2)
c/2 is integer/integer, which is not the same as c/2.0
rules all-integer arimetic generally produces integer results,
so (unless you import division from __future__) pay attention or
write your constants with decimal points even if the values are exact integers.
note:
 >>> 5/2
 2
 >>> from __future__ import division
 >>> 5/2
 2.5

>print freq
>table.append([freq,(i,j,k)])
>print i,j,k,' freq',freq
>for item in table: print item
>
>
>The problem is simple. The function 'round' allow to obtain the value 
>with the specified number of digits after the ",". Then, when the 
>variable 'freq' is printed, there is no problem; but when freq is set in 
>the table and the table printed, all the digits are come back.
>
>Is it a bug or a control behavour ? I don't understand ?!?!?!?!...
>
Others have pointed out the output formatting and binary representation
problems behind your question, but I thought you might not realize the above.

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


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Simo Melenius
Paul Rubin  writes:

> Sybren Stuvel <[EMAIL PROTECTED]> writes:
> > An example:
> > 
> > def generate_randomizer(n, m):
> > randomizer = def(x):
> > return x ** n % m
> > 
> > return randomizer
> 
> You're a little bit confused; "name" doesn't necessarily mean "persistent
> name".  You could write the above as:
>
>   def generate_randomizer (n, m):
>  def randomizer(x):
> return pow(x, n, m)
>  return randomizer

But if you could do anonymous blocks, you could just write something
like:

def generate_randomizer (n, m):
return def (x):
return pow (x, n, m)

Personally, I don't mind naming local functions in practice (and
Python syntax doesn't lend itself very well to anonymous blocks) but
rather, the nuisance is that I feel there's just plain something wrong
with it. It's less beautiful than it could be.

Luckily, the last time I followed the discussion on this topic in
c.l.p, some bright mind whose name escapes me now pointed out the
craziness of _having to_ name functions by comparing it to the
situation where you'd have to bind any literal objects to symbols
before you could use them. Like:

def return_fixed_number ():
res = 42
return res

or:

arg1 = "foo"
arg2 = 42
arg3 = baz ()
myfunction (arg1, arg2, arg3.xyzzy ())

Sure, you don't lose any expressiveness in that: if you had to name
any object before using it, you could write all the same programs that
you can in the current Python. But it's the expressiveness of your
mind that gets harpooned: you'll have to keep part of your focus on
these extraneous local variables instead of thinking only in terms
of values where only values matter.


-- 
[EMAIL PROTECTED] -- Today is the car of the cdr of your life.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ode to python

2005-09-06 Thread Gregory Bond
Hmmm... OK...  you forced me into it.

Python uses whitespace
Where C++ uses a brace
New users fret,
But old pros forget -
it quickly all falls into place.

I could go on..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe uses __init__ for class names when logging

2005-09-06 Thread flupke
Thomas Heller wrote:


> This has been discussed on the py2exe-users lists, and a fix was found
> by David Hess.  Fortunately he added it to the wiki:
> 
> http://starship.python.net/crew/theller/moin.cgi/LoggingModule
> 
> Thomas

Cool, thanks Thomas, i'll give that a whirl

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


Re: py2exe 0.6.1 released

2005-09-06 Thread Bengt Richter
On Tue, 06 Sep 2005 11:12:46 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:

>"Giovanni Bajo" <[EMAIL PROTECTED]> writes:
>
>> Thomas Heller wrote:
>>
>>> * py2exe can now bundle binary extensions and dlls into the
>>>   library-archive or the executable itself.  This allows to
>>>   finally build real single-file executables.
>>>
>>>   The bundled dlls and pyds are loaded at runtime by some special
>>>   code that emulates the Windows LoadLibrary function - they are
>>>   never unpacked to the file system.
>>
>>
>> Cute!
>>
>> I tried it using the wx singlefile example, but unfortunately the resulting
>> executable segfaults at startup (using Python 2.3.3 on Windows 2000, with
>> latest wxWindows).
>
>Yes, I can reproduce that.  I'm still using wxPython 2.4.2.4 for Python
>2.3.5, and that combo works.  I have done a few tests, and wxPython
>2.5.1.5 also works, while 2.5.5.1 crashes.
>
>> How can I debug it?
>
>I'll assume that's a serious question.
>There is no simple answer.  First, the py2exe'd app responds to a
>PY2EXE_VERBOSE environment variable, if you set it to '1', the exe will
>reports imports (just as PYTHONVERBOSE does for python scripts).  Of
>course you have to change the sample so that it is built as console app
>to be able to see the messages.
If you have a place in the program where output should never happen
except when you would want a console window to see it in, you can
call AllocConsole [1] safely even in multiple such places, just before
the printing, and the first such call will create the console and hook
up stdout and stderr ready to print. Subsequent calls to AllocConsole
are effectively ignored, so all the output goes to the same console
no matter which code section executed first. IMO this should be
built into at least the windows wpython to trigger at the first
attempt at stdout or stderr output. There could be an option to
override that default and thus ignore stdout/stderr output, but I
think it would be a useful default. Plus it would tell people early
that they had usesless prints going in their wpython programs.

>
>Then, you can throw some additional prints into
>lib\site-packages\zipextimporter.py, to see what it does.
>
>I've done all this, and it seems it is crashing when trying to import
>_gdi.pyd.  Next would be to debug through _memimported.pyd, but I don't
>have a debug build of wxPython.
>
>That's all I can say now.
>
>I'll ask on the wxPython mailing list if they have an idea.
>
>Thomas

[1]

The AllocConsole function allocates a new console for the
calling process.

BOOL AllocConsole(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE. If the
function fails, the return value is FALSE. To get extended
error information, call GetLastError.

Remarks

A process can only be associated with one console, so
AllocConsole fails if the calling process already has a
console. A process can use the FreeConsole function to
detach itself from its current console, and then it can call
AllocConsole to create a new console. If the calling process
creates a child process, the child inherits the new console.
AllocConsole also sets up standard input, standard output,
and standard error handles for the new console. The standard
input handle is a handle to the console's input buffer, and
the standard output and standard error handles are handles
to the console's screen buffer. To retrieve these handles,
use the GetStdHandle function.

This function is primarily used by graphics applications to
create a console window. Graphics applications are
initialized without a console. Console applications are
normally initialized with a console, unless they are created
as detached processes (by calling the CreateProcess function
with the DETACHED_PROCESS flag).

See Also

CreateProcess, FreeConsole, GetStdHandle

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


Re: os.system(r"ls") prints to screen??

2005-09-06 Thread Xah Lee
Xah Lee wrote:
> does anyone know why the folllowing prints to the screen?
> # python
> import os
> os.system(r"ls")

Steve Holden wrote:
> It only prints to the screen when standard output of the invoking
> process is the screen. The sub-process forked by os.system inherits
> stdin stdout and stderr from the invoking process.

Thanks.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Possible improvement to slice opperations.

2005-09-06 Thread Bengt Richter
On Tue, 06 Sep 2005 18:34:13 +0200, Magnus Lycka <[EMAIL PROTECTED]> wrote:
[...]
>
>Then you need to view it more in the mathematical way of
>half-open (or half-closed if you prefer) intervals.
>
>[a,b) = { x | a <= x < b }
>
Funny, I just posted with the same thought (and some additional considerations)
I hadn't read yours yet, or I would have mentioned it ;-)

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


Re: Possible improvement to slice opperations.

2005-09-06 Thread Bengt Richter
On Tue, 06 Sep 2005 10:31:33 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:
>Steve Holden wrote:
[...]
>
>> My point was that you can make those changes in your own code, leaving 
>> others to accept the situation as it is.
>
>It's only a suggestion and an interesting idea I thought I would share 
>and see if anyone would like to discuss. I did title this as a 'possible 
>improvement', and not as proposed improvement.
>
>
>> Right, I wasn't trying to suggest that you didn't know what you were 
>> talking about - or even that you didn't understand general relativity 
>> (on which my grasp could be said to be tenuous) - merely that some 
>> things are inherently difficult, and no matter how you twist the 
>> implementations about, the difficulties will remain.
>
>But shouldn't we try to make things easier when possible?
>
Sure ;-)

It occurs to me that maybe this discussion of slicing has a parallel
in mathematical intervals, and we might usefully check if it makes sense there.

IOW, let's compare [a, b] vs [a, b) vs (a, b] vs (a,b)

ISTM the python range model corresponds to [a, b) in terms of integers. The 
step thing
modifies that, but leave that aside to concetrate on the main issue.

For math, I think the notation requires a<=b, but for programming, python has a 
convention
for specifying related intervals and a subsetting function, with similar 
notation adding step.

Leaving aside abs(step)!=1 which specifies subsetting, we could say that

 [a:b:1]
is
 [a, b)
and
 [a:b,-1]
is
 (a, b]

but the latter returned in reverse order.

If we factor out the issues of reversing and subsetting, we just have
the indication of which kind of interval: half-open to the right or left.

That we could do by
[a:b] => [a, b)
and
.[a:b] => (a, b]

Then the question is, do we need sugar for reversed(x.[a:b])
or list(reversed(x.[a:b])) for the right hand side of a statement,
and do we want to to use both kinds of intervals in slice assignment?
(maybe and yes ;-)

The reason for yes is that it solves the which-gap problem in assigning to [a:a]
if you define [a, a) as an empty interval to the left of a and (a, a] as an 
empty
interval to the right of a, sort of like +0 and -0 in half-open intervals ;-)
Replacing the empty interval does the insertion on the side you want ;-)

I am choosing the convention to stay compatible with python's current behaviour,
even though I'm not sure what the math world says about ahttp://mail.python.org/mailman/listinfo/python-list


Re: Do int.__lt__/__gt__/etc. exist?

2005-09-06 Thread Terry Reedy

"Chris Dutton" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I'm just curious.  I've been trying to demonstrate functional thinking
> in Python, but I can't find these methods for int objects.  It would be
> immensely helpful for something like:
>
> filter(4 .__lt__, range(10))

Do dir(int) and you will find that int has .__cmp__ but not the individual 
compares (at least in 2.2).

tjr



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


Re: Language Work Benches in Py

2005-09-06 Thread yoda
I realize that I forgot to post the sample code:). Below is my
implementation:

#DSL data
#123456789012345678901234567890123456789012345678901234567890,

dsldata=(
'SVCLFOWLER 10101MS0120050313.',
'SVCLHOHPE  10201DX0320050315',
'SVCLTWO   x10301MRP220050329..',
'USGE10301TWO  x50214..7050329...')

#Class mappings
Mappings={'svcl':{
(4,18):'CustomerName',
 (19,23):'CustomerID',
 (24,27) :'CallTypeCode',
 (28,35) : 'DateOfCallString'},
 'usge':{(4,8) :'CustomerID',
  (9,22):'CustomerName',
  (30,30):'Cycle',
  (31,36): 'ReadDate'}}


def generateClass(data):
'generate the class and instance with attributes'

className = data[:4].lower() #1)
mappingData= Mappings[className]#2)
class Klass:pass   #3)
Klass. __name__=className  #4)
#print Klass

for key in mappingData.keys():   #5)
fielddata=data[key[0]:key[1]]
print 'actual data->',fielddata
setattr(Klass,mappingData[key],fielddata) #6)
return Klass


def parseData():
'parse the data and generate a list of objects'
classes= [generateClass(item) for item in dsldata]
return classes

def printKlassData(Klass):
print Klass
for key in Klass.__dict__:
print ('attr->%s value->%s')%(key,Klass.__dict__[key])

if __name__=='__main__':
for Klass in parseData():
printKlassData (Klass)

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


Re: assign dict by value to list

2005-09-06 Thread Terry Reedy

"Phill Atwood" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> def csv_it():
> db = []  # the entire database of records
> rec = {} # a single rec: a dictionary of field names and data pairs

Move this line

> fields = [] # list of field names collected so far for current record
> for line in open(inputfile):

to here

> kword = getkeyword(line) # get keyword (or field name)
...
> # Now clear current record
> fields = []
> rec.clear()

and delete this

> dummylist = []

and I think you will have what you want (or close).
The initial fields = [] line could be moved also, I believe, without 
thoroughly reading your code.

Terry J. Reedy 



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


Re: Ode to python

2005-09-06 Thread [EMAIL PROTECTED]

Python the programming language
is reviled for its indentage.
Although it's the norm,
to code in free form
makes sources no better than garbage.

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


Re: [Jython-users] ANN: PyDev 0.9.8.1 released

2005-09-06 Thread could ildg
Thanks.
pydev is so alive.On 9/7/05, Fabio Zadrozny <[EMAIL PROTECTED]> wrote:
Hi All,PyDev - Python IDE (Python Development Enviroment for Eclipse) version0.9.8.1 has been released.Check the homepage (http://pydev.sourceforge.net/
) for more details.Details for Release: 0.9.8.1Major highlights:---* Java 1.4 support reintroduced.* Styles added for syntax highlighting (bold and italic),
contributed by Gerhard Kalab.Others that are new and noteworthy:-* zombie process after exiting eclipse should not happen anymore* paths with '.' are accepted for the pythonpath (unless they start
with a '.', because it may not accept relative paths).* relative imports are added to code-completion* local imports are taken into consideration when doing code completion* debugger has 'change support', so, changed variables in a scope
appear redCheers,Fabio--Fabio Zadrozny--Software DeveloperESSS - Engineering Simulation and Scientific Software
www.esss.com.brPyDev - Python Development Enviroment for Eclipsepydev.sf.netpydev.blogspot.com---
SF.Net email is Sponsored by the Better Software Conference & EXPOSeptember 19-22, 2005 * San Francisco, CA * Development Lifecycle PracticesAgile & Plan-Driven Development * Managing Projects & Teams * Testing & QA
Security * Process Improvement & Measurement * http://www.sqe.com/bsce5sf___Jython-users mailing list
[EMAIL PROTECTED]https://lists.sourceforge.net/lists/listinfo/jython-users
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: ~ after script filename?

2005-09-06 Thread presentt
Huh, no ~ on other files when I edit them, but at least I don't have to
worry about it.  Thanks Aldo.

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


Re: Ode to python

2005-09-06 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> Python or C? C is simply a pawn.
> Venomous problem? Pythons squeeze and constrict, until the problem is
> gone.

Don't quit your day job.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function returns a function

2005-09-06 Thread Paul Rubin
Aldo Cortesi <[EMAIL PROTECTED]> writes:
> The lexical scope within which a function is declared is
> made available to the function when it is run. This is done
> by storing the values of free variables within the declared
> function in the func_closure attribute of the created
> function object.

Actually not quite right:

   a = []
   for i in range(5):
  a.append(lambda: i)   # i is free in the lambda
   print [f() for f in a]

prints [4,4,4,4,4] instead of [0,1,2,3,4].  The value of i has not
been copied into the closure.  Rather, the closure has a cell bound to
the same place that i is bound.  So:

   for i in range(5):
  def f():
 j = i   # bind a new variable "j" and assign the value from i
 return lambda: j  # j is free and its value doesn't change
  a.append(f())
   print [f() for f in a]

prints [0,1,2,3,4].  There's a Pythonic idiom using default args:

   a = []
   for i in range(5):
  a.append(lambda i=i: i)   # the "inner" i is free in the lambda
   print [f() for f in a]
   
Closures like may look a little surprising in Python but they're a
standard technique in Scheme.  The classic textbook "Structure and
Interpretation of Computer Programming" explains it all.  Full text is
online at:

   http://mitpress.mit.edu/sicp/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ~ after script filename?

2005-09-06 Thread Aldo Cortesi
Thus spake presentt ([EMAIL PROTECTED]): 

> Hello all,
>
> I just wrote a really simple script and named it
> helloworld.py.  Inside was only:
>
> #!/usr/bin/env print "Hello, world"
>
> I used chmod to set the permissions, and ran it to see
> what happened (I just started learning Python, if you
> couldn't guess)
>
> Then, I typed ls in the directory to see what was there,
> and I noticed a new file, namely helloworld.py~ .  What is
> that file (its contents are identicle to helloworld.py)?
> Why the ~?
>
> Thanks a lot.  I'm using Ubuntu Linux 5.04 (Hoary), and
> wrote the script with gedit.

It doesn't have anything to do with Python. I'm pretty sure
you'll find that the file is created by your editor as a
backup or a running store of some kind. Try just editing a
random non-python file with the same editor, and see if you
find the same thing...


Cheers,


Aldo



--
Aldo Cortesi
[EMAIL PROTECTED]
http://www.nullcube.com
Off: (02) 9283 1131
Mob: 0419 492 863
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function returns a function

2005-09-06 Thread Aldo Cortesi
Thus spake Gregory Bond ([EMAIL PROTECTED]):

> Paul Rubin wrote:
>
> >
> > def FunctionMaker(avar, func, label):
> >def callback():
> >   avar.set(label)
> >   func()
> >return callback
>
> I've seen this idiom a lot and I know _what_ it does.
> but I can't
> work _how_ it does it.  How does the name binding work so
> that "avar" in
> the returned function still references the object passed
> into the
> (long-distant!) FunctionMaker() call?
>
> Web pages / turotial ptrs etc gladly accepted.

The lexical scope within which a function is declared is
made available to the function when it is run. This is done
by storing the values of free variables within the declared
function in the func_closure attribute of the created
function object.

If you want to read more, the keyword you're looking for is
"closure" - a quick search on Google for "python closure"
should satisfy your curiosity handily. There is also a neat
recipe for inspecting the values kept in the func_closure
attribute of function objects directly:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439096






Cheers,


Aldo



--
Aldo Cortesi
[EMAIL PROTECTED]
http://www.nullcube.com
Off: (02) 9283 1131
Mob: 0419 492 863

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


~ after script filename?

2005-09-06 Thread presentt
Hello all,

I just wrote a really simple script and named it helloworld.py.  Inside
was only:

#!/usr/bin/env
print "Hello, world"

I used chmod to set the permissions, and ran it to see what happened (I
just started learning Python, if you couldn't guess)

Then, I typed ls in the directory to see what was there, and I noticed
a new file, namely helloworld.py~ .  What is that file (its contents
are identicle to helloworld.py)?  Why the ~?

Thanks a lot.  I'm using Ubuntu Linux 5.04 (Hoary), and wrote the
script with gedit.

~~Ted Present

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


Re: Python executable

2005-09-06 Thread presentt
Thanks everyone!  I think I'm going to stick with Python; at least I
know there are some people here willing to help.

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


Re: assign dict by value to list

2005-09-06 Thread Steve Holden
Phill Atwood wrote:
> Newbie question:
> 
> I have a dictionary called "rec".  And a list called "db". db is my 
> database. rec are to be records in the database. In a loop I'm trying to 
> create a record and add it to my database.  The key stmt is
> 
> db.append( rec )
> 
> This works initially but it seems that instead of copying the values in 
> rec and adding it to db, only a reference of rec is added to db.  Thus
> when I reassign rec with new data and then do another append I end up
> with two records in my database but now the both contain the same data, 
> namely the latest version or rec.
> 
> So how do I add a dictionary into a list by value rather than by reference?
> 
> The complete code is here:
> 
[code snipped]

I see you do a rec.clear() to clear out the contents of one record 
before creating a new one. Python only *ever* uses references, so why 
not just use

 rec = {}

instead of rec.clear()?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: Proposal: add sys to __builtins__

2005-09-06 Thread Rick Wotnaz
"Michael J. Fromberger"
<[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> In article <[EMAIL PROTECTED]>,
>  Rick Wotnaz <[EMAIL PROTECTED]> wrote:
> 
>> You're right that there is no necessity for such a change. I
>> was not actually talking about importing *any* module in every
>> case, but rather about importing, say, 'sys' when, for example,
>> sys.argv appeared in the code and no import had been specified.
> 
> I think I must have missed that post; I will go back and look at
> it.  However, while I'm here, how would your proposal deal with
> code like this:
> 
>import foobar
> 
># ... some while later ...
>def f( ... ):
>   ...
>   global foobar, sys
>   sys = foobar
>   ...
> 
># ... some while even later ...
>f( ... )
>sys.wallaby("Fear and loathing!")
> 
> In particular, we have no import of sys, but the name "sys" is 
> meaningful as a local alias for a different module.  I'm not
> saying you couldn't deal with this, but it rules out some of the
> more obvious ways of detecting and automatically handling this
> kind of substitution. 
> 
> Naturally, you might well ask, "why would you do such a fool
> thing?"  To this I can only respond:  "Never underestimate the
> ingenuity of fools." 
> 

I don't know that this would cause any particular problem with the 
[not exactly-]proposed method. The automagic lookup would not be 
triggered until a NameError occurred, which would not happen in this 
case. As you say, why would anyone -- at least anyone who wanted to 
rely on sys.xxx being automatically resolved -- do such a thing? Even 
under the current scheme, occluding 'sys' would prevent correct 
interpretation of sys.argv. An error is an error in either case.

Now, if 'wallaby' is not part of the foobar namespace, the automagic 
system would kick in an incorrectly import sys, and on retry would 
still not find 'wallaby' in the namespace. Much merriment would 
ensue, I'm sure. At that point, I'd want such a system to have a 
nervous breakdown and allow the debugging to begin. Whether I hand-
entered an import statement or not wouldn't change that.

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


Re: Do int.__lt__/__gt__/etc. exist?

2005-09-06 Thread en.karpachov
On Wed, 07 Sep 2005 00:02:49 GMT
Chris Dutton wrote:

> I'm just curious.  I've been trying to demonstrate functional thinking 
> in Python, but I can't find these methods for int objects.  It would be 
> immensely helpful for something like:
> 
> filter(4 .__lt__, range(10))
> 
> As opposed to:
> 
> filter(lambda a: 4 < a, range(10))

Python is neither pure object nor pure functional language. There is an 
"operator" module, with its operator.lt, but it is not exactly what you need.
You still need lambda with it.

The recommended way to do what you want is

result = [x for x in xrange(10) if 4 < x]

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


Ode to python

2005-09-06 Thread liquidbinary
*Organized Chaos*

I crafted your purpose one line at a time.
No other creation shall be like your kind.

Boolean values fire connections.
High level logic from your inception.

I partitioned your system into functions of selfdom.
Artificial neurons thread together to bond them.

Not one routine shall be introspectively seen by another.
For I tell you, only a value shall be returned from its brother.

I encapsulate your fate into objects of state.
Confused? Wait. I've flow charts to show how they relate.

Abolish all globals, and all mutinous variables.
Embed precious methods in organized crucibles.

Polymorphism provides an element of evolution.
Shifting and shaping to evolve a solution.

Drink java? Good, maintain your work flow.
Use java? Get burned like lava, for it moves just as slow.

Python or C? C is simply a pawn.
Venomous problem? Pythons squeeze and constrict, until the problem is
gone.

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


Re: improvements for the logging package

2005-09-06 Thread skip

>> while working on something in my current project I have made several
>> improvements to the logging package in Python, two of them are worth
>> mentioning:
...
Trent> Cool. Your additions sound useful.

Perhaps so, but the logging module seems like such an unpythonic beast to
me.  How about cleaning it up (*) before we add more to it?  Stuff like
colorizing seems like it belongs in its own module (presuming a reasonably
general markup scheme can be agreed upon) so it can be used outside the
logging package.

(*) Stuff that seems very odd to me:

- It's a package, but contrary to any other package I've ever seen, most
  of its functionality is implemented in __init__.py.  __init__.py is
  roughly four times larger than the next largest (bsddb, which is a
  beast because BerkDB has gotten so big over the years and the
  module/package has strived to remain backwards-compatible).

- It's still too hard to use.  The obvious 'hello world' example

import logging
logging.info('hello world')

  ought to just work (implicitly add a stream handler connected to
  stderr to the root logger).

- Its functionality is partitioned in sometimes odd ways.  For example,
  it has a handlers module, but what I presume would be the most
  commonly used handler (StreamHandler) is not defined there.  It's in
  (you have three guesses and the first two don't count) __init__.py
  instead of in logging.handlers.  Consequently, browsing in the obvious
  way fails to find the StreamHandler class.

- It doesn't use PEP 8 style as far as naming is concerned, instead
  doing some sort of Java or C++ or Perl camelCase thing.  Eschewing PEP
  8 is fine for other stuff, but code in the Python core (especially new
  code like the logging module) should strive to adhere to PEP 8, since
  many people will use the core code as a pattern for their own code.

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


Re: infinite loop

2005-09-06 Thread Mike Meyer
"LOPEZ GARCIA DE LOMANA, ADRIAN" <[EMAIL PROTECTED]> writes:

> Hi all, 
>
> I have a question with some code I'm writting:
>
>
> def main():
> if option == 1:
> function_a()
> elif option == 2:
> function_b()
> else:
> raise 'option has to be either 1 or 2'
> if iteration == True:
> main()
[...]
> I want an infinite loop, but after some iterations (996) it breaks:

Since no one else mentioend it: this is only iteration in languages
which mandate tail recursion elimination. Languages that don't do that
are free to do the recursion, which will eventually run you out of
stack. Python is in the latter category, and that's what you ran into.

Thinking about iteration this way is elegant - but it doesn't work
everywhere. Sorry.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


assign dict by value to list

2005-09-06 Thread Phill Atwood

Newbie question:

I have a dictionary called "rec".  And a list called "db". db is my 
database. rec are to be records in the database. In a loop I'm trying to 
create a record and add it to my database.  The key stmt is

db.append( rec )

This works initially but it seems that instead of copying the values in 
rec and adding it to db, only a reference of rec is added to db.  Thus
when I reassign rec with new data and then do another append I end up
with two records in my database but now the both contain the same data, 
namely the latest version or rec.

So how do I add a dictionary into a list by value rather than by reference?

The complete code is here:

=
#!/usr/bin/python

import sys

inputfile = sys.argv[1]

keywords = [ 'place-name=',
'addr-line1=',
'addr-line2=',
'addr-city=',
'addr-state=',
'addr-country=',
'addr-postalcode=',
'mailaddr-line1=',
'mailaddr-line2=',
'mailaddr-city=',
'mailaddr-state=',
'mailaddr-country=',
'mailaddr-postalcode=',
'place-phone1=',
'place-phone2=',
'place-fax=',
'place-email1=',
'place-email2=' ]

def csv_it():
 db = []  # the entire database of records
 rec = {} # a single rec: a dictionary of field names and data pairs
 fields = [] # list of field names collected so far for current record
 for line in open(inputfile):
 kword = getkeyword(line) # get keyword (or field name)
 if kword:
 # We've got a line with a keyword in it
 if kword == keywords[0]:
 # Starting a new record, so save current record
 db.append( rec )
 printdb(db, "stage 1")

 # Now clear current record
 fields = []
 rec.clear()
 dummylist = []
 for i in range(1,len(keywords)+1):
 dummylist.append('')
 for k,d in zip(keywords,dummylist):
 rec[k] = d
 printdb(db, "stage 2")

 # make sure we are not encountering a duplicate key word
 if kword in fields:
 print "Record contains duplicate field"
 print line,
 sys.exit()
 fields.append(kword)
 # collect our data and store it in the current record
 data = line[line.find('=')+1:]
 datalstrip = data.lstrip()
 datarstrip = datalstrip.rstrip()
 rec[kword] = datarstrip

 printdb(db,"stage 3")
 db.append( rec ) # don't forget whatever we have in our last record

 # dump the database in comma separated value form
 outstring = ''
 for k in keywords:
 outstring += '"'
 outstring += k
 outstring += '"'
 outstring += ','
 print outstring
 for r in db:
 outstring = ''
 for k in keywords:
 if r[k]:
 outstring += '"'
 outstring += r[k]
 outstring += '"'
 outstring += ','
 print outstring


def getkeyword(line):
 equal_index = line.find('=')
 if equal_index >= 0:
 kword = line[0:equal_index+1]
 if kword in keywords:
 return kword
 else:
 print "Invalid keyword at line:"
 print line
 sys.exit()
 return None

def printdb( db, text ):
 print " "
 print "db %s = " % text
 print db
 print " "



if __name__ == '__main__':
 csv_it()



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


Re: Function returns a function

2005-09-06 Thread Gregory Bond
Paul Rubin wrote:

> 
> def FunctionMaker(avar, func, label):
>def callback():
>   avar.set(label)
>   func()
>return callback

I've seen this idiom a lot and I know _what_ it does. but I can't 
work _how_ it does it.  How does the name binding work so that "avar" in 
the returned function still references the object passed into the 
(long-distant!) FunctionMaker() call?

Web pages / turotial ptrs etc gladly accepted.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Optional algol syntax style

2005-09-06 Thread Mike Meyer
"Christoph Rackwitz" <[EMAIL PROTECTED]> writes:
> You didn't quite get the OP's intention, I guess.
>
> The OP wanted Python to be a bit more freeform by adding "end" tags.
> That might be an improvement for web scripting, but I haven't seen the
> solutions of the existing frameworks and won't dare to compare.

Existing frameworks (the one's I've looked at anyway) tend to replace
indents with end tags of some kind. Doing anything else tends to get
ugly unless the language you are templating for treats whitespace the
same way Python does.

I'd argue that you're better off using a real templating system than
trying to mangle Python into becoming a more acceptable templating
system. For templates, you tend to want to access multiple different
names spaces that are only vaguelly related to the Python contextual
name spaces. For example, you may want CGI (or whatever variables)
available directly in the template, rather than as
CGI["foobar"].value. However, you don't want them showing up in front
of your templat variables; you want to be able to say "add CGI
variables foo, bar and foobar to the current name space" in a short
manner.

Templating systems (well, the better ones, anyway) let you manipulate
those name spaces in ways you can't do in python. Cheeta and
ClearSilver come to mind as systems that will let you do this.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal: add sys to __builtins__

2005-09-06 Thread Patrick Maupin
Sybren Stuvel wrote:

> A programming language should not be ambiguous. The choice
> between importing a module and calling a function should not
> depend on the availability of a (local) variable.

Yeah, this behavior would be as ambiguous as if we had a system-defined
search-path for modules, where you might get one module or another
depending on the path order.  Oh, wait -- we have one of those.

> The question is not if it's possible or not - in principle, everything
> is possible. The question is if it is desirable.

Exactly.  So it pays to try to understand what the payoff might be, and
I always try to be open-minded about that (although I sometimes fail
miserably in this goal).  In the case of sys.path, the payoff is that a
Python application has a small chance of running on a completely
different system.  In the case of automagic importation, the only
payoff I have seen discussed is that some people would be happier with
a little less typing.

The thing I always find baffling is that people who find it hard to
type "import sys" seem to find it quite easy to write eight paragraphs
explaining why it's bad to have to type "import sys."

Regards,
Pat

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


Re: dual processor

2005-09-06 Thread Mike Meyer
Jeremy Jones <[EMAIL PROTECTED]> writes:
> 1) find a good clean way to utilize muti-CPU machines and

I like SCOOP. But I'm still looking for alternatives.

> 2) come up with a simple, consistent, Pythonic concurrency paradigm.

That's the hard part. SCOOP attaches attributes to *variables*. It
also changes the semantics of function calls based on the values of
those attributes. Part of the power of using SCOOP comes from the
processor detecting when a variable has been declared as having an
attribute is used to reference objects for which the attribute doesn't
apply.

I'm not sure how Pythonic that can be made.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dual processor

2005-09-06 Thread Mike Meyer
Jorgen Grahn <[EMAIL PROTECTED]> writes:
> But it's interesting that the Unix pipeline Just Works (TM) with so little
> effort.

Yes it is. That's a result of two things:

1) The people who invented pipes were *very* smart (but not smart
   enough to invent stderr at the same time :-).

2) Pipes use a dead simple concurrency model. It isn't even as
   powerful as CSP. No shared memory. No synchronization primitives. Data
   flows in one direction, and one direction only.

Basically, each element of a pipe can be programmed ignoring
concurrency. It doesn't get much simpler than that.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal: add sys to __builtins__

2005-09-06 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 Rick Wotnaz <[EMAIL PROTECTED]> wrote:

> You're right that there is no necessity for such a change. I was 
> not actually talking about importing *any* module in every case, 
> but rather about importing, say, 'sys' when, for example, sys.argv 
> appeared in the code and no import had been specified.

I think I must have missed that post; I will go back and look at it.  
However, while I'm here, how would your proposal deal with code like 
this:

   import foobar

   # ... some while later ...
   def f( ... ):
  ...
  global foobar, sys
  sys = foobar
  ...

   # ... some while even later ...
   f( ... )
   sys.wallaby("Fear and loathing!")

In particular, we have no import of sys, but the name "sys" is 
meaningful as a local alias for a different module.  I'm not saying you 
couldn't deal with this, but it rules out some of the more obvious ways 
of detecting and automatically handling this kind of substitution.

Naturally, you might well ask, "why would you do such a fool thing?"  To 
this I can only respond:  "Never underestimate the ingenuity of fools."

-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python xml.dom, help reading attribute data

2005-09-06 Thread Giovanni Bajo
Thierry Lam wrote:

> Let's say I have the following xml tag:
>
> 1
>
> I can't figure out what kind of python xml.dom codes I should invoke
> to read the data 1? Any help please?
>
> Thanks
> Thierry


If you use elementtree:

>>> from elementtree import ElementTree
>>> node = ElementTree.fromstring("""1""")
>>> node.text
'1'
>>> node.attrib["role"]
'success'
-- 
Giovanni Bajo


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


Re: Last mod date

2005-09-06 Thread Andrew McNamara
>This is my first post--I'm a Java developer trying to expand my 
>horizons.  I'm trying to figure out how to find out the last 
>modification date/time for a file.  I've found a reference to 
>*PyOS_GetLastModificationTime *as an Operating System Utility, but I 
>can't figure out which module I need to import to access it.

Look at the "os" module.

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Last mod date

2005-09-06 Thread Robert Kern
Webmaster - Fidelity Lodge #113 wrote:
> This is my first post--I'm a Java developer trying to expand my 
> horizons.  I'm trying to figure out how to find out the last 
> modification date/time for a file.  I've found a reference to 
> *PyOS_GetLastModificationTime *as an Operating System Utility, but I 
> can't figure out which module I need to import to access it.

os.path.getmtime(filename)

http://docs.python.org/lib/module-os.path.html

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Last mod date

2005-09-06 Thread Webmaster - Fidelity Lodge #113
This is my first post--I'm a Java developer trying to expand my 
horizons.  I'm trying to figure out how to find out the last 
modification date/time for a file.  I've found a reference to 
*PyOS_GetLastModificationTime *as an Operating System Utility, but I 
can't figure out which module I need to import to access it.

I'm using Python version 2.4.1 on a box running Windows  (it works, and 
nobody else in the house wants to use it).

Thanks in advance,

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


Re: py2exe 0.6.1 released

2005-09-06 Thread Giovanni Bajo
Thomas Heller wrote:

>> I tried it using the wx singlefile example, but unfortunately the
>> resulting executable segfaults at startup (using Python 2.3.3 on
>> Windows 2000, with latest wxWindows).
>
> Yes, I can reproduce that.  I'm still using wxPython 2.4.2.4 for
> Python
> 2.3.5, and that combo works.  I have done a few tests, and wxPython
> 2.5.1.5 also works, while 2.5.5.1 crashes.

Ah that's fine, then. I thought it was one of those "only in my computer" kind
of issue :)

>> How can I debug it?
>
> I'll assume that's a serious question.

Of course it was, I'm not sure why you should doubt it. I was just trying to
being helpful to you, thinking that it could have been hard to reproduce.
Luckily, you can look into it yourself.

> I've done all this, and it seems it is crashing when trying to import
> _gdi.pyd.  Next would be to debug through _memimported.pyd, but I
> don't have a debug build of wxPython.

OK. Do you believe that _memimported.pyd can eventually converge to something
stable? Emulating LoadLibrary for all versions of Windows is not an easy task
after all. Wine might provide some insights.
-- 
Giovanni Bajo


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


Do int.__lt__/__gt__/etc. exist?

2005-09-06 Thread Chris Dutton
I'm just curious.  I've been trying to demonstrate functional thinking 
in Python, but I can't find these methods for int objects.  It would be 
immensely helpful for something like:

filter(4 .__lt__, range(10))

As opposed to:

filter(lambda a: 4 < a, range(10))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyInstaller 1.0 in the works: package your Python app into asingle-file executable

2005-09-06 Thread Trent Mick
[Giovanni Bajo wrote]
> Trent Mick wrote:
> 
> > I notice that the release notes for py2exe 0.6.1 mention that it
> > finally *can* make a single file executable. I'm not involved in
> > developing it
> > nor am I that experienced with it. Just an FYI.
> 
> Yes, I noticed it. You'll have noticed also that the announcement happened
> after my mail was already posted. I'll update PyInstaller's website ASAP to 
> fix
> the now incorrect information in there.

Yah. I read about the py2exe release on python-announce first and then
your announcement on python-list and then the py2exe announcement on
python-list.  Sorry for jumping the gun.

Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyInstaller 1.0 in the works: package your Python app into asingle-file executable

2005-09-06 Thread Giovanni Bajo
Trent Mick wrote:

> I notice that the release notes for py2exe 0.6.1 mention that it
> finally *can* make a single file executable. I'm not involved in
> developing it
> nor am I that experienced with it. Just an FYI.

Yes, I noticed it. You'll have noticed also that the announcement happened
after my mail was already posted. I'll update PyInstaller's website ASAP to fix
the now incorrect information in there.

Thanks,
-- 
Giovanni Bajo


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


Re: Possible improvement to slice opperations.

2005-09-06 Thread Ron Adam
Magnus Lycka wrote:

> Ron Adam wrote:
> 
>> Ok, lets see...  This shows the problem with using the gap indexing 
>> model.
>>
>> L = range(10)
>>
>> [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9  ]   # elements
>> 0   1   2   3   4   5   6   7   8   9   10   # index's
>>
>> L[3::1]  -> [3, 4, 5, 6, 7, 8, 9]  3rd index to end...  ok
>> L[3:6:1] -> [3, 4, 5]  3rd index to 6th index... ok
>>
>> L[3::-1] -> [3, 2, 1, 0]  4th index to beginning... umm
>> L[6:3:-1] -> [6, 5, 4]  7th index to 4th index... ?
>>
>> So negative strides use a different index position?
>>
>>  [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9  ]   # elements
>> -1   0   1   2   3   4   5   6   7   8   9# index's
>>
>> L[3::-1]  -> [3, 2, 1, 0]   3rd index to beginning... ok
>> L[6:3:-1] -> [6, 5, 4]   6th index to 3rd index... ok
> 
> 
> Ok, I see what you mean. The "view slices as indices standing
> between the items in the sequence" model actually breaks down
> with negative strides.

Yes, that and the edge case's is why I this topic keeps coming up.  Then 
there's the 'None' default values that depend on both the stride sign, 
and the index signs.  These are all features in some context, and can be 
annoyances in others.  As long as you stick with positive stride values, 
it's not much of a problem though, so an alternate solution will have to 
be really good.


> Then you need to view it more in the mathematical way of
> half-open (or half-closed if you prefer) intervals.
> 
> [a,b) = { x | a <= x < b }
> 
> See http://en.wikipedia.org/wiki/Half-closed_interval

Interesting...  Maybe just a different syntax that designates the stop 
as being inclusive would work?

   [a,b] = { x | a <= x <= b }

   L[a;;b]   a+1 to b
   L[a>;;]


> I still think the current sematics are the least surprising
> though. For instance, if we want to implement a ring class
> looking something like the one below, the logical way to do
> that would allow it to be used as if it was a list.
> 
> Actually, such a ring class (extented to handle extended slices
> correctly) would (I think) solve the tricky cases with things
> such as l[0:-0] or l[9:-1:-1].
> 
> The complete implementation is left as an exercise to the
> reader, although there's probably something like it in the
> Python cookbook already.
> 
> class Ring(list):
> def __init__(self, size):
> self.size = size
> def __setitem__(self, i,v):
> return list.__setitem__(self, i%self.size, v)
> def __getitem__(self, i):
> return list.__getitem__(self, i%self.size)
> def __setslice__(self, i, j, v):
> return list.__setslice__(self, i%self.size, j%self.size,v)
> def __getslice__(self, i, j):
> return list.__getslice__(self, i%self.size, j%self.size)

This is nice.  I might even find a use for it. ;-)

Cheers,
Ron






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


Re: dual processor

2005-09-06 Thread Paul Rubin
[EMAIL PROTECTED] (Bengt Richter) writes:
> >And I'm fairly certain that 'sort' won't start spending CPU time
> >until it has collected all its input, so you won't gain much
> >there either.
> >
> Why wouldn't a large sequence sort be internally broken down into parallel
> sub-sequence sorts and merges that separate processors can work on?

Usually the input would be split into runs that would get sorted in
memory.  Conventional wisdom says that the most important factor in
speeding up those sorts is making the runs as long as possible.
Depending on how complicated comparing two elements is, it's not clear
whether increased cache pressure from parallel processors hitting
different regions of memory would slow down the sort more than
parallelism would speed it up.  Certainly any sorting utility that
tried to use parallel processors should use algorithms carefully
chosen and tuned around such issues.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dual processor

2005-09-06 Thread Bengt Richter
On Tue, 6 Sep 2005 19:35:49 + (UTC), Thomas Bellman <[EMAIL PROTECTED]> 
wrote:

>Michael Sparks <[EMAIL PROTECTED]> writes:
>
>> Similarly, from
>> a unix command line perspective, the following will automatically take
>> advantage of all the CPU's I have available:
>
>>(find |while read i; do md5sum $i; done|cut -b-32) 2>/dev/null |sort
>
>No, it won't.  At the most, it will use four CPU:s for user code.
>
>Even so, the vast majority of CPU time in the above pipeline will
>be spent in 'md5sum', but those calls will be run in series, not
>in parallell.  The very small CPU bursts used by 'find' and 'cut'
>are negligable in comparison, and would likely fit within the
>slots when 'md5sum' is waiting for I/O even on a single-CPU
>system.
>
>And I'm fairly certain that 'sort' won't start spending CPU time
>until it has collected all its input, so you won't gain much
>there either.
>
Why wouldn't a large sequence sort be internally broken down into parallel
sub-sequence sorts and merges that separate processors can work on?

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


Re: infinite loop

2005-09-06 Thread James
Devan L wrote:
> LOPEZ GARCIA DE LOMANA, ADRIAN wrote:
> > Hi all,
> >
> > I have a question with some code I'm writting:
> >
> >
> > def main():
> >
> > if option == 1:
> >
> > function_a()
> >
> > elif option == 2:
> >
> > function_b()
> >
> > else:
> >
> > raise 'option has to be either 1 or 2'
> >
> > if iteration == True:
> >
> > main()
> >
> > def function_a():
> >
> > print 'hello from function a'
> >
> > return None
> >
> > def function_b():
> >
> > print 'hello from function b'
> >
> > return None
> >
> > iteration = True
> >
> > option = 1
> >
> > main()
> >
> >
> > I want an infinite loop, but after some iterations (996) it breaks:
> >
> >
> > [EMAIL PROTECTED] tmp]$ python test.py
> > hello from function a
> > hello from function a
> > hello from function a
> > .
> > .
> > .
> > hello from function a
> > hello from function a
> > Traceback (most recent call last):
> >   File "test.py", line 35, in ?
> > main()
> >   File "test.py", line 17, in main
> > main()
> >   File "test.py", line 17, in main
> >
> > .
> > .
> > .
> > .
> >   File "test.py", line 17, in main
> > main()
> >   File "test.py", line 17, in main
> > main()
> >   File "test.py", line 5, in main
> > function_a()
> > RuntimeError: maximum recursion depth exceeded
> >
> >
> > I don't understand it. Why am I not allowed to iterate infinitely? 
> > Something about the functions? What should I do for having an infinite loop?
> >
> > Thanks in advance for your help,
> >
> > Adrián.
>
> You've written a recursive function-you're not iterating. The recursion
> limit is there to keep you from making something which will do
> something bad, like recurse cyclically.

What you need is probably this...

def main():
while iteration:
if option == 1:
function_a()
elif option == 2:
function_b()
else:
raise 'option has to be either 1 or 2'

def function_a():
print 'hello from function a'

def function_b():
print 'hello from function b'

iteration = True
option = 1
main()

As a side note, note that you don't really need to return a None.

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


Re: infinite loop

2005-09-06 Thread Scott David Daniels
LOPEZ GARCIA DE LOMANA, ADRIAN wrote:
> Hi all, 
> 
> I have a question with some code I'm writting:
> 
> 
> def main():
> if option == 1:
> function_a()
> elif option == 2:
> function_b()
> else:
> raise 'option has to be either 1 or 2'
> if iteration == True:
> main()
> ... I want an infinite loop, but after some iterations (996) it breaks:
> ... RuntimeError: maximum recursion depth exceeded
> 
> 
> I don't understand it. Why am I not allowed to iterate infinitely? 
> Something about the functions? What should I do for having an infinite loop?

You are asking in your code for infinite recursive regress.
Eventually the stack overflows.

An infinite loop would look like:

def main():
 if option == 1:
 function_a()
 elif option == 2:
 function_b()
 else:
 raise 'option has to be either 1 or 2'
 while iteration:
 if option == 1:
 function_a()
 elif option == 2:
 function_b()
 else:
 raise 'option has to be either 1 or 2'

Which you might want to rewrite as:
def main():
 choices = {1: function_a, 2:function_b}
 choices[option]()
 while iteration:
 choices[option]()

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


Re: infinite loop

2005-09-06 Thread Devan L

LOPEZ GARCIA DE LOMANA, ADRIAN wrote:
> Hi all,
>
> I have a question with some code I'm writting:
>
>
> def main():
>
> if option == 1:
>
> function_a()
>
> elif option == 2:
>
> function_b()
>
> else:
>
> raise 'option has to be either 1 or 2'
>
> if iteration == True:
>
> main()
>
> def function_a():
>
> print 'hello from function a'
>
> return None
>
> def function_b():
>
> print 'hello from function b'
>
> return None
>
> iteration = True
>
> option = 1
>
> main()
>
>
> I want an infinite loop, but after some iterations (996) it breaks:
>
>
> [EMAIL PROTECTED] tmp]$ python test.py
> hello from function a
> hello from function a
> hello from function a
> .
> .
> .
> hello from function a
> hello from function a
> Traceback (most recent call last):
>   File "test.py", line 35, in ?
> main()
>   File "test.py", line 17, in main
> main()
>   File "test.py", line 17, in main
>
> .
> .
> .
> .
>   File "test.py", line 17, in main
> main()
>   File "test.py", line 17, in main
> main()
>   File "test.py", line 5, in main
> function_a()
> RuntimeError: maximum recursion depth exceeded
>
>
> I don't understand it. Why am I not allowed to iterate infinitely? Something 
> about the functions? What should I do for having an infinite loop?
>
> Thanks in advance for your help,
>
> Adrián.

You've written a recursive function-you're not iterating. The recursion
limit is there to keep you from making something which will do
something bad, like recurse cyclically.

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


infinite loop

2005-09-06 Thread LOPEZ GARCIA DE LOMANA, ADRIAN

Hi all, 

I have a question with some code I'm writting:


def main():

if option == 1:

function_a()

elif option == 2:

function_b()

else:

raise 'option has to be either 1 or 2'

if iteration == True:

main()

def function_a():

print 'hello from function a'

return None

def function_b():

print 'hello from function b'

return None

iteration = True

option = 1

main()


I want an infinite loop, but after some iterations (996) it breaks:


[EMAIL PROTECTED] tmp]$ python test.py
hello from function a
hello from function a
hello from function a
.
.
.
hello from function a
hello from function a
Traceback (most recent call last):
  File "test.py", line 35, in ?
main()
  File "test.py", line 17, in main
main()
  File "test.py", line 17, in main

.
.
.
.
  File "test.py", line 17, in main
main()
  File "test.py", line 17, in main
main()
  File "test.py", line 5, in main
function_a()
RuntimeError: maximum recursion depth exceeded


I don't understand it. Why am I not allowed to iterate infinitely? Something 
about the functions? What should I do for having an infinite loop?

Thanks in advance for your help, 

Adrián.


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


Re: Possible improvement to slice opperations.

2005-09-06 Thread Ron Adam
Patrick Maupin wrote:
> Ron Adam wrote:
> 
> 
>>>This should never fail with an assertion error.  You will note that it
>>>shows that, for non-negative start and end values, slicing behavior is
>>>_exactly_ like extended range behavior.
> 
> 
>>Yes, and it passes for negative start and end values as well.
> 
> 
> Umm, no:
> 
> .>> for stride in [-3, -2, -1, 1, 2, 3]:
> ... for start in range(-1,len(L)):
> ... for end in range(-1,len(L)):
> ... P = L[start:end:stride]
> ... Q = [L[i] for i in range(start, end, stride)]
> ... assert P==Q, [start, end, stride, P, Q]
> ...
> Traceback (most recent call last):
>   File "", line 6, in ?
> AssertionError: [-1, 0, -3, [9, 6, 3], []]

Ah, Yes... I it was way too late last night and I mistakenly changed the 
values of L... which was meaningless.

Range lines in the for statements, need to read..

 range(-len(l),0)

But then it doesn't include all the values of L.


>>Thanks again, this pretty much explains why slices opperate the
>>way they do.  And it explains why the edge case's happen as well I think.
> 
> 
> You're welcome.
> 
> Regards,
> Pat
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __dict__ of object, Was: Regular Expression IGNORECASE differentfor findall and split?

2005-09-06 Thread Fredrik Lundh
Chris <[EMAIL PROTECTED]> wrote:

> but more of a basic question following, I was doing the following before:
>
> method = 'split' # came from somewhere else of course
> result = re.__dict__[method].(REGEX, TXT)
>
> precompiling the regex
>
> r = compile(REGEX)
>
> does give an regex object which has the needed methods
>
> print dir(r)
> ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner',
> 'search', 'split', 'sub', 'subn']
>
> but how do I evaluate them without explicitly calling them?
>
> result = r.__???MAGIC???__[method](TXT)
>
> obviously I am not a Python pro ;)

I really don't understand why you think you have to write
your RE code that way, but the mechanism you're looking
for is getattr:

result = getattr(r, method)(TXT)





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


attn: carline - very colorful premium news server access - vifne col - (1/1)

2005-09-06 Thread briant
Imagine this,

Take a look at all the great features below and imagine! You'll LOVE it.
Images, video, mp3 music, the real news from around the world... it's all 
inside waiting for you.
Take a look, I know you'll love it as much as I do.

Streaming audio and video
Blazing fast downloads
800 GIGS of new multimedia content each day
Keyword searchable

Thank you and have a good night... oh and check out http://www.nuzer.net - 
that's what I'm talking about.


Ut iprunorlav i ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cleaning strings with Regular Expressions

2005-09-06 Thread Fredrik Lundh
"sheffdog" <[EMAIL PROTECTED]> wrote:
> Using basename works, but leaves the extra stuff at the end.
>  Which would have to be removed with another line of code
>
> I get this-->  ppbhat.tga";

if you're trying to parse Maya files, maybe you should start
by writing a simple Maya parser, and use that to extract the
relevant strings, *before* passing them to os.path.baseline?





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


Re: __dict__ of object, Was: Regular Expression IGNORECASE different for findall and split?

2005-09-06 Thread Steven Bethard
Chris wrote:
> but more of a basic question following, I was doing the following before:
> 
> method = 'split' # came from somewhere else of course
> result = re.__dict__[method].(REGEX, TXT)
> 
> precompiling the regex
> 
> r = compile(REGEX)
> 
> does give an regex object which has the needed methods
> 
> print dir(r)
> ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 
> 'scanner', 'search', 'split', 'sub', 'subn']
> 
> but how do I evaluate them without explicitly calling them?
> 
> result = r.__???MAGIC???__[method](TXT)
> 
> obviously I am not a Python pro ;)

Use getattr:

method = 'split'
result = getattr(re.compile(REGEX), method)(TXT)

HTH,

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


Re: Function returns a function

2005-09-06 Thread James Stroud
Thank you Paul, this makes much more sense.

James

On Tuesday 06 September 2005 02:16 pm, Paul Rubin wrote:
>     def FunctionMaker(avar, func, label):
>        def callback():
>           avar.set(label)
>           func()
>        return callback

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: Function returns a function

2005-09-06 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> Any ideas on how to do this with a regular function, or is the way I've done 
> it the pythonic choice?

I think you're trying to do something like this:

def FunctionMaker(avar, func, label):
   def callback():
  avar.set(label)
  func()
   return callback
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cleaning strings with Regular Expressions

2005-09-06 Thread sheffdog
Using basename works, but leaves the extra stuff at the end.
 Which would have to be removed with another line of code

I get this-->  ppbhat.tga";

Thanks, for the idea though.
/\/\ason

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


Re: dual processor

2005-09-06 Thread Paul Rubin
Thomas Bellman <[EMAIL PROTECTED]> writes:
> And I'm fairly certain that 'sort' won't start spending CPU time
> until it has collected all its input, so you won't gain much
> there either.

For large input, sort uses the obvious in-memory sort, external merge
algorithm, so it starts using cpu once there's enough input to fill
the memory buffer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dual processor

2005-09-06 Thread Paul Rubin
Jorgen Grahn <[EMAIL PROTECTED]> writes:
> I feel the recent SMP hype (in general, and in Python) is a red herring. Why
> do I need that extra performance? What application would use it?

How many mhz does the computer you're using right now have?  When did
you buy it?  Did you buy it to replace a slower one?  If yes, you must
have wanted more performance.  Just about everyone wants more
performance.  That's why mhz keeps going up and people keep buying
faster and faster cpu's.

CPU makers seem to be running out of ways to increase mhz.  Their next
avenue to increasing performance is SMP, so they're going to do that
and people are going to buy those.  Just like other languages, Python
makes perfectly good use of increasing mhz, so it keeps up with them.
If the other languages also make good use of SMP and Python doesn't,
Python will fall back into obscurity.

> Am I prepared to pay the price (in bugs, lack of features, money,
> etc) for someone to implement this?  There's already a lot of
> performance lost in bloatware people use everyday; why are we not
> paying the much lower price for having that fixed with traditional
> code optimization?

That is needed too.  But obviously increased hardware speed has a lot
going for it.  That's why people keep buying faster computers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: launching adobe reader with arguments from os.system call

2005-09-06 Thread Martin Miller
Greg Miller wrote:
> Currently I am launching adobe reader using the following call:
> os.system("path.file.pdf")
> this works fine for opening the pdf doc at the beginning. We would like
> to enhance this and open the document to either a page or a nameddest
> in the doc.  The syntax for that in the DOS command prompt world is:
> acroRd32.exe /A "nameddest=Before You Begin" "path.file.pdf"
> However the os.system call won't allow me to call reader using that
> syntax.  Does anyone know how I can launch the Reader application and
> pass in the parameters required to allow the document to be opened to
> the named destination?  Thanks in advance!!

I'm not sure how/if you can do what you want with os.system(), but this
is what I've used to pass arguments directly to applications on
Windows:
># spawn text editor on file
>import os
>applpath = r'C:\Windows\system32\notepad.exe'
>filepath =  r'D:\My Documents\somefile.txt'
>os.spawnv(
>os.P_WAIT,
>applpath,
>[ # argument list
>applpath,
>filepath
>]
>)

A downside is that it requires you to know the full path to the
application, 'acroRd32.exe' in your case. On the other hand, I think
you could pass just about any argument values (as strings) that you
wished in the list passed as the third argument.

HTH,
-Martin

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


Re: Cleaning strings with Regular Expressions

2005-09-06 Thread Larry Bates
May not be what you are looking for, but this works:

import os
s='setAttr ".ftn" -type "string" ' \
  '/assets/chars/boya/geo/textures/lod1/ppbhat.tga";'
fname=os.path.basename(s.split()[-1])


BTW-It does depend on the file/path being the last item
on the line.

Larry Bates


sheffdog wrote:
> Hello,
> 
>  I often find myself cleaning up strings like the following:
> 
> setAttr ".ftn" -type "string" /assets/chars/
> /boya/geo/textures/lod1/ppbhat.tga";
> 
> Using regular expressions, the best I can do so far is using the re.sub
> command but it still takes two lines. Can I do this in one line? Or
> should I be approaching this differently? All I want to end up with is
> the file name "ppbhat.tga".
> 
> Python Code:
> lines[indexC]=re.sub("[\s,\S,]*/", "", lines[indexC])
> lines[indexC]=re.sub(".tga[\s,\S,]*", ".tga", lines[indexC])
> 
> Thanks for your time,
> 
> /\/\ason S
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Paul Rubin
"Terry Reedy" <[EMAIL PROTECTED]> writes:
> Are you claiming that including a reference to the more humanly readable 
> representation of a function (its source code) somehow detracts from the 
> beauty of the function concept?

Huh?  Anonymous functions mean you can use functions as values by
spelling out their source code directly, instead of having to make a
separate reference and then pass that.  There are times when the
separate reference is just clutter.  It's less readable, not more readable.

> Or are you claiming that binding a 
> function to a name rather than some other access reference (like a list 
> slot) somehow detracts from its conceptual beauty?  Is so, would you say 
> the same about numbers?

Yes, I would say the same about numbers; Python would suffer if users
were required to give a name to every number.  I'd say

  x = f(1, 3)

is much less ugly than
 
  one = 1
  three = 3
  x = f(one, three)

I further don't see how the second example is more "readable" than the first.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cleaning strings with Regular Expressions

2005-09-06 Thread Fredrik Lundh
"sheffdog" <[EMAIL PROTECTED]> wrote:

> setAttr ".ftn" -type "string" /assets/chars/
>/boya/geo/textures/lod1/ppbhat.tga";

> Can I do this in one line?

>>> os.path.basename("/assets/chars/.../lod1/ppbhat.tga")
'ppbhat.tga'





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


__dict__ of object, Was: Regular Expression IGNORECASE different for findall and split?

2005-09-06 Thread Chris
Peter Otten wrote:
> Chris wrote:
> 
> 
>> >>> re.split('x', '1x2X3', re.I)
>>['1', '2X3']
> 
> 
> 
>>I expected ['1', '2', '3'] but in this case re.I bahaves exactly as not
>>present at all...
> 
>  
> 
>>Is that an expected behaviour or a fault?
> 
> 
> This is expected:
> 
> 
help(re.split)
> 
> Help on function split in module sre:
> 
> split(pattern, string, maxsplit=0)
> Split the source string by the occurrences of the pattern,
> returning a list containing the resulting substrings.
> 
> You are setting maxsplit to
> 
> 
re.I
> 
> 2
> 
> Use re.compile() to get the desired behaviour:
> 
> 
re.compile("x", re.I).split("1x2X3")
> 
> ['1', '2', '3']
> 
> Peter

thanks, I should read the docs but

but more of a basic question following, I was doing the following before:

method = 'split' # came from somewhere else of course
result = re.__dict__[method].(REGEX, TXT)

precompiling the regex

r = compile(REGEX)

does give an regex object which has the needed methods

print dir(r)
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 
'search', 'split', 'sub', 'subn']

but how do I evaluate them without explicitly calling them?

result = r.__???MAGIC???__[method](TXT)

obviously I am not a Python pro ;)

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


Function returns a function

2005-09-06 Thread James Stroud
Hello,

I want a "function factory" function in python. To do this I made a class like 
such (this is for Tkinter, in case your wondering):

class FunctionMaker:
  def __init__(self, avar, function, label)
self.var = avar
self.function = function
self.label = label
  def __call__(self, e=None):
self.avar.set(self.label)
self.function()

It seems that it would make more sense to make this a function and add it to 
the mixin I am writing. But I'm not quite sure how to do this without making 
lambdas, which seem a little messy and also look to be on the brink of 
deprecation (really not trying to start a lambda pro/con thread here).

Any ideas on how to do this with a regular function, or is the way I've done 
it the pythonic choice?

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Robert Kern
talin at acm dot org wrote:
> I like the decorator idea. Unfortunately, the version of Python I am
> using is pre-decorator, and there are various issues involved in
> upgrading on Mac OS X (due to the built-in Python 2.3 being used by the
> OS itself.) I'll have to look into how to upgrade without breaking too
> much...

There really aren't any issues. The official 2.4.1 binary installs
alongside the built-in 2.3. The executables python{,w,2.4,w2.4} are
installed the /usr/local/bin . Under no circumstances should you have to
replace the built-in 2.3. Indeed, under no circumstances should you
replace it at all.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: Generators and Decorators doing my head in ..

2005-09-06 Thread simonvc
Fantastic, thanks Leif and Paul, My problem is that i thought the
decorator worked at the function runtime, not when the function gets
created.

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


Cleaning strings with Regular Expressions

2005-09-06 Thread sheffdog
Hello,

 I often find myself cleaning up strings like the following:

setAttr ".ftn" -type "string" /assets/chars/
/boya/geo/textures/lod1/ppbhat.tga";

Using regular expressions, the best I can do so far is using the re.sub
command but it still takes two lines. Can I do this in one line? Or
should I be approaching this differently? All I want to end up with is
the file name "ppbhat.tga".

Python Code:
lines[indexC]=re.sub("[\s,\S,]*/", "", lines[indexC])
lines[indexC]=re.sub(".tga[\s,\S,]*", ".tga", lines[indexC])

Thanks for your time,

/\/\ason S

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


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread talin at acm dot org
I like the decorator idea. Unfortunately, the version of Python I am
using is pre-decorator, and there are various issues involved in
upgrading on Mac OS X (due to the built-in Python 2.3 being used by the
OS itself.) I'll have to look into how to upgrade without breaking too
much...

Some further examples of what I am trying to do. First let me state
what my general goal is: There are lots of inference engines out there,
from Prolog to Yacas, but most of them rely on a custom interpreter.
What I want to find out is if I can build a solver, not by creating a
new language on top of Python, but rather by giving solver-like
capabilities to a Python programmer. Needless to say, this involves a
number of interesting hacks, and part of the motivation for my
suggestion(s) is reducing the hack factor.

So, at the risk of being visited by Social Services for my abuse of
Python Operators, here's a sample of how the sovler works:

# Define a function with multiple arities
Simplify = Function()

# Define some arities. We overload __setitem__ to define an arity.
# Param is a class who'se metaclass defines __getattr__ to return a new
instance
# of Param with the given parameter name.
Simplify[ ( add, Param.x, 0 ) ] = lamba x: return Simplify( x )# x
+ 0 = x
Simplify[ ( mul, Param.x, 1 ) ] = lamba x: return Simplify( x )# x
* 1 = x
Simplify[ ( mul, Param.x, 0 ) ] = lamba x: return 0   #
x * 0 = 0
Simplify[ Param.x ] = lamba x: return x
 # Fallback case

# Invoke the function. Should print the value of x
print Simplify( (add, x, 0) )

Of course, what I really want is not def or lambda, what I really want
is to be able to define functions that take suites as arguments. But
that would be crazy talk :)

Define( "Simplify", args ):
   code

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


Re: simple question: $1, $2 in py ?

2005-09-06 Thread Christos Georgiou
On Mon, 05 Sep 2005 12:54:35 +0200, rumours say that "Diez B. Roggisch"
<[EMAIL PROTECTED]> might have written:

>> 
>> As far as I understand there's no $1, $2... etc stuff right ?
>
>Yes - but there is sys.argv
>
>Try this
>
>
>import this

>print sys.argv


I believe this last line should be:

print this.__builtins__['__import__']('sys').argv
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal: add sys to __builtins__

2005-09-06 Thread Christopher Subich
Michael J. Fromberger wrote:

 > While I'm mildly uncomfortable with the precedent that would be set 
by including the contents of "sys" as built-ins, I must confess my 
objections are primarily aesthetic:  I don't want to see the built-in 
namespace any more cluttered than is necessary -- or at least, any more 
than it already is.


I agree with this sentiment, and I'll also additionally say that 'import 
sys' doesn't seem to be needed when writing sufficiently high-level 
code.  My python mud client (forever in development, but the 
structure-code is mostly done) uses TKinter, Twisted, and glue code for 
just about everything.

In currently 1,080 lines of Python code (reported by wc -l, so it 
includes a few blank lines) in 9 files, I needed "import sys" once. [1]

After I import sys, I use it exactly once -- I check the platform so I 
can use the higher resolution time.clock on win32 [time.time on win32 
(win2k) seems to have a resolution of 10ms, while on a 'nix I tested 
with time.time has at least ms resolution].  I'll probably use sys again 
somewhere to build an automagic version/platform string, but uses for it 
seem to be very limited.

I also have 0 imports of 'os', and the only immediately useful case that 
comes to mind is implementation of a #dir scripting command -- providing 
a minimal shell functionality, and this is certainly not a core 
component of the program.

In my opinion, using 'sys' and 'os' are extreme examples of "low-level" 
Python programming.  This sort of thing is probably very useful for 
writing actual scripts that replace the sort of work done by shell 
scripts, but as programs get more complicated I think they'd be used 
(proportionally) less and less.

I'm -0.9 on sys (really don't like the idea but it wouldn't be awful to 
see it included in __builtins__, provided it's namespaced appropriately) 
and -1 on os.

[1] Actually, it's in there three times, but they're all in the same 
file -- I'd just left a legacy 'import sys' in a couple local scopes and 
forgot to remove them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: killing thread after timeout

2005-09-06 Thread Bryan Olson
Bryan Olson wrote:
[Some stuff he thinks is right, but might not answer the real
question]

Definitely look into Peter Hanson's answer.

Olson's answer was about timing-out one's own Python code.


Bryan Olson has heretofore avoided referring to himself in the
third person, and will hence forth endeavor to return to his
previous ways.

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


Re: Django Vs Rails

2005-09-06 Thread Terry Reedy

"bruno modulix" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>D H wrote:
>
> (snip)
>> Go with Rails.  Django is only like a month old.
>
> Please take time to read the project's page. Django has in fact three
> years of existence and is already used on production websites, so it's
> far from pre-alpha/planning stage.

One can also check it out in action.
  http://www.ljworld.com/ is the site it was developed for. 



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


Re: Python compiled?

2005-09-06 Thread Christos Georgiou
On Tue, 06 Sep 2005 03:06:52 -, rumours say that Grant Edwards
<[EMAIL PROTECTED]> might have written:

>There are very, very few pure "exe"
>single-file executable windows apps.  Putty is the only one
>I've run across in a _long_ while.

Then you should also run across Media Player Classic (download it from
http://sourceforge.net/projects/guliverkli ).  Just a plain exe, no
installation needed, and is an excellent media player.  For a funny
side, check the program's version history.
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression IGNORECASE different for findall and split?

2005-09-06 Thread Peter Otten
Chris wrote:

>  >>> re.split('x', '1x2X3', re.I)
> ['1', '2X3']


> I expected ['1', '2', '3'] but in this case re.I bahaves exactly as not
> present at all...
 
> Is that an expected behaviour or a fault?

This is expected:

>>> help(re.split)
Help on function split in module sre:

split(pattern, string, maxsplit=0)
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings.

You are setting maxsplit to

>>> re.I
2

Use re.compile() to get the desired behaviour:

>>> re.compile("x", re.I).split("1x2X3")
['1', '2', '3']

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


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Sybren Stuvel
Terry Reedy enlightened us with:
> Are you claiming that including a reference to the more humanly readable 
> representation of a function (its source code) somehow detracts from the 
> beauty of the function concept?

Nope.

> Or are you claiming that binding a function to a name rather than
> some other access reference (like a list slot) somehow detracts from
> its conceptual beauty?

Nope.

> Is so, would you say the same about numbers?

Nope.

I was under the (apparently very wrong) impression (don't ask my why)
that something like the example that Paul Rubin gave wouldn't be
possible. Now that I've learned that, I take back what I've said. His
code is more beautyful IMO ;-)

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: killing thread after timeout

2005-09-06 Thread Bryan Olson

Jacek Poplawski had written:
 >> I am going to write python script which will read python
 >> command from socket, run it and return some values back to
 >> socket.
 >>
 >> My problem is, that I need some timeout.

Jacek Poplawski wrote:
 > After reading more archive I think that solution may be to raise an
 > Exception after timeout, but how to do it portable?

Python allows any thread to raise a KeyboardInterrupt in the
main thread (see thread.interrupt_main), but I don't think there
is any standard facility to raise an exception in any other
thread. I also believe, and hope, there is no support for lower-
level killing of threads; doing so is almost always a bad idea.
At arbitrary kill-times, threads may have important business
left to do, such as releasing locks, closing files, and other
kinds of clean-up.

Processes look like a better choice than threads here. Any
decent operating system will put a deceased process's affairs
in order.


Anticipating the next issues: we need to spawn and connect to
the various worker processes, and we need to time-out those
processes.

First, a portable worker-process timeout: In the child process,
create a worker daemon thread, and let the main thread wait
until either the worker signals that it is done, or the timeout
duration expires. As the Python Library Reference states in
section 7.5.6:

 A thread can be flagged as a "daemon thread". The
 significance of this flag is that the entire Python program
 exits when only daemon threads are left.

The following code outlines the technique:

 import threading

 work_is_done = threading.Event()

 def work_to_do(*args):
 # ... Do the work.
 work_is_done.set()

 if __name__ == '__main__':
 # ... Set stuff up.
 worker_thread = threading.Thread(
 target = work_to_do,
 args = whatever_params)
 worker_thread.setDaemon(True)
 worker_thread.start()
 work_is_done.wait(timeout_duration)



Next, how do we connect the clients to the worker processes?

If Unix-only is acceptable, we can set up the accepting socket,
and then fork(). The child processes can accept() incomming
connections on its copy of the socket. Be aware that select() on
the process-shared socket is tricky, in that that the socket can
select as readable, but the accept() can block because some
other processes took the connection.


If we need to run on Windows (and Unix), we can have one main
process handle the socket connections, and pipe the data to and
from worker processes. See the popen2 module in the Python
Standard Library.


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


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Sybren Stuvel
Paul Rubin enlightened us with:
> You're a little bit confused; "name" doesn't necessarily mean
> "persistent name".

Wonderful. Another feature added to Python (that is: the Python
version in my mind ;-) without the need to add any features to Python
(that is: the real Python)

Thanks!

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: Writing Multithreaded Client-Server in Python.

2005-09-06 Thread google
a bit of a late reply, sorry...

Paul Rubin schreef:

> [EMAIL PROTECTED] writes:
> > > I suspect he was trying to say that BaseHTTPServer has no mechanism for
> > > handling state. As you know, of course, this is most relevant across
> > > multiple successive connections to a server from the same client, and
> > > has little to do with threads.
>
> Usually you would do that with browser cookies.
>

Mwah... Not if you want the client to be responsive to server-initiated
messages, i.e. to implement some sort of listener ? (Or you should use
Jason-RPC or some other relatively exotic tech?)
And, and my guess is this is more applicable in the context of OP's
question, not if you want to prevent constructing some
client-representing object from a cookie-id for each incoming request
(istd. of forwarding the request to a thread holding the
client-representing object in the correct current state)

> > Correct. My own 'brew' is multi-session-clients enabled (in fact I test
> > with two applets from the same PC) but indeed I used confusing language
> > saying 'client' for 'session'.
> >
> > Again: ThreadingMixIn doesn't give you 'session threads' in which you
> > store persistent information - a candidate for some generic extension
> > of SocketServer ?
>
> What exactly do you mean by session?



I mean (in a C/S context) : "A persistent state initiated by a client
(e.g. a login- or first-message event) and maintained by the server."

>
> How many sessions took place here?

Though trivial: 2 'TCP sessions' but I am (sorry for the confusion) not
talking about TCP sessions but (and I guess OP too) application-level
sessions.

> It sounds like you want the answer
> to be one session, that operations 2 and 3 are part of the same session.
> But that makes no sense unless you associate them somehow, say using
> a client cookie and a global session table indexed by the cookie.
>

In my world, message 3 would be 'session initiating'.
Message 2 could be handled on the basis of a possibly changed 'client
state' due to processing of message 1 (or other intermediate message
exchange).

> Why don't you take a look at any of the web frameworks that get
> discussed here (Spyce, CherryPy, Zope, Django, whatever).  They all
> have mechanisms like that.   BaseHTTPServer doesn't try to operate
> at that level.

The OP had a question about SocketServer not BaseHTTPServer? That
certainly doesn't give you 'persistent state mechanism' for free.
SocketServer doesn't either - all I wanted to say is I got myself
confused a bit by the name "ThreadingMixIn" suggesting to me that it
would give me a thread to store state info in - again it doesn't .

I know Zope very well, and CherryPy a bit. At least for my project they
wouldn't suffice because, as far as I know, they don't offer a
mechanism for the server to 'raise an event' or 'send a non-response
message' to the client. I don't know about Djange and Spyce but thanks:
I'll certainly study them ! I suggested Twisted as an 'out-of-the-box'
framework for state-persistent, real-time C/S framework but I perceived
the overhead/learning-curve intimidating and decided to pass.


--
T.
www.phaedro.com
Compile-time type-checking is a drag.
http://www.bushclintonkatrinafund.com/ - help now but never ever vote
republican again please

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


Re: Ignoring ampersand(&) as a special character in xml

2005-09-06 Thread Chris
Chris wrote:
> Thierry Lam wrote:
> 
>> Let's say I have the following xml tag:
>>
>> a & b
>>
>> Currently, an xml parser will treat & as a special character.  Does
>> anyone know the special characters to use around the ampersand so that
>> the xml parser can treat "a & b" as a whole value?
>>
>> Thanks
>> Thierry
>>
> 
> Simple use the XML Entity for & which is &
> 
> a & b
> 
> You could use CDATA sections too but they seem to have the effect on 
> people ignoring that the containing strings are actually literary what 
> they seem (in this case "a & b") and not what they really are ("a & 
> b")...

should read before posting..., of course the other way round:
some people seem to ignore the visible "a & b" is not the actual "a 
& b" in CDATA sections...

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


Re: Ignoring ampersand(&) as a special character in xml

2005-09-06 Thread Chris
Thierry Lam wrote:
> Let's say I have the following xml tag:
> 
> a & b
> 
> Currently, an xml parser will treat & as a special character.  Does
> anyone know the special characters to use around the ampersand so that
> the xml parser can treat "a & b" as a whole value?
> 
> Thanks
> Thierry
> 

Simple use the XML Entity for & which is &

a & b

You could use CDATA sections too but they seem to have the effect on 
people ignoring that the containing strings are actually literary what 
they seem (in this case "a & b") and not what they really are ("a & 
b")...

chris

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


Regular Expression IGNORECASE different for findall and split?

2005-09-06 Thread Chris
hello,
I have question about the re.I option for Regular Expressions:

 >>> import re
 >>> re.findall('x', '1x2X3', re.I)
['x', 'X']

as expected finds both lower and uppercase x


 >>> re.split('x', '1x2X3', re.I)
['1', '2X3']
 >>> re.split('x', '1x2X3')
['1', '2X3']

I expected ['1', '2', '3'] but in this case re.I bahaves exactly as not 
present at all...

Is that an expected behaviour or a fault?
Running Python 2.4.1 on Windows XP

thanks for any hint
chris

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


Re: py2exe uses __init__ for class names when logging

2005-09-06 Thread Thomas Heller
flupke <[EMAIL PROTECTED]> writes:

> Hi,
>
> when i run my program and use the logging component, i see this:
>
> 2005-09-02 17:07:48,193 INFO windowmain 97 Main window created
> 2005-09-02 17:07:49,020 DEBUG windowmain 103 Frame  proxy of C++ wxFrame instance at _b8dd9401_p_wxFrame>
> 2005-09-02 17:07:49,145 INFO firebird 195 Starting up the database
>
> However when i run py2exe on my app and run it then i don't see the
> file name anymore. Instead it says __init__:
>
> 2005-09-06 16:01:17,098 INFO __init__ 1032 Main window created
> 2005-09-06 16:01:17,615 DEBUG __init__ 1032 Frame  proxy of C++ wxFrame instance at _d8057f01_p_wxFrame>
> 2005-09-06 16:01:17,677 INFO __init__ 1032 Starting up the database
>
> Any ideas on how to solve this?

This has been discussed on the py2exe-users lists, and a fix was found
by David Hess.  Fortunately he added it to the wiki:

http://starship.python.net/crew/theller/moin.cgi/LoggingModule

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


Re: py2exe 0.6.1 released

2005-09-06 Thread Thomas Heller
"cmkl" <[EMAIL PROTECTED]> writes:

> Hi,
>
> I didnt succeed to bundle vpython-3.2.3 with py2exe-0.6.1 - regardless
> if its build as single file or not:
>
> "This application has requested the Runtime to terminate it in an
> unusual way"  and so on...
>
> This error message seems not generated by py2exe. At least I could not
> find a reference to it in the sources of py2exe.

Often this is caused by py2exe not including some needed pyds, together
with 'sloppy' programming in the extensions themselves.

Let me explain: Sometimes, extensions depend on other extensions.  Since
they cannot directly import functions from each other, Python has an API
for that: PyCObject_Import(module_name, cobject_name).  This returns an
opaque pointer, which often points to a table of functions.  Or NULL, in
case there's an error.

Normally, this import will never fail (because all the extensions are
available), so often the return value is *not* checked.  Calling one of
these functions when the import has failed will then crash the
application.

In other cases the extension programmers see no other way to report the
error except calling PyFatal_Error() when the import failed, which would
then give what you see.

For py2exe, it may help to use include more modules or the whole package
in question and try to build again.

Of course, it can also be that py2exe 0.6 has a bug that 0.5.4 did not
have, can you try that version?

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


Ignoring ampersand(&) as a special character in xml

2005-09-06 Thread Thierry Lam
Let's say I have the following xml tag:

a & b

Currently, an xml parser will treat & as a special character.  Does
anyone know the special characters to use around the ampersand so that
the xml parser can treat "a & b" as a whole value?

Thanks
Thierry

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


Re: Python versus Perl

2005-09-06 Thread Matthias Kluwe
Hi!

> [...]

> 1 - How does the speed of execution of Perl compares to that of Python?

This might not answer your question, but I found "The Computer Language
Shootout Benchmarks" quite interesting (and fun). Python to Perl
comparison can be found at

http://shootout.alioth.debian.org/benchmark.php?test=all&lang=python&sort=fullcpu

Regards,
Matthias

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


Re: dual processor

2005-09-06 Thread Thomas Bellman
Michael Sparks <[EMAIL PROTECTED]> writes:

> Similarly, from
> a unix command line perspective, the following will automatically take
> advantage of all the CPU's I have available:

>(find |while read i; do md5sum $i; done|cut -b-32) 2>/dev/null |sort

No, it won't.  At the most, it will use four CPU:s for user code.

Even so, the vast majority of CPU time in the above pipeline will
be spent in 'md5sum', but those calls will be run in series, not
in parallell.  The very small CPU bursts used by 'find' and 'cut'
are negligable in comparison, and would likely fit within the
slots when 'md5sum' is waiting for I/O even on a single-CPU
system.

And I'm fairly certain that 'sort' won't start spending CPU time
until it has collected all its input, so you won't gain much
there either.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"We don't understand the software, and! bellman @ lysator.liu.se
 sometimes  we don't understand the hardware, ! 
 but we can *see* the blinking lights!"   ! Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Terry Reedy

"Sybren Stuvel" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> talin at acm dot org enlightened us with:
>> I'd be sad to see the notion of "anonymous functions" go

Though it is as yet unclear as to what may come in compensation.

> Same here. I think it's a beautyful concept

Are you claiming that including a reference to the more humanly readable 
representation of a function (its source code) somehow detracts from the 
beauty of the function concept?  Or are you claiming that binding a 
function to a name rather than some other access reference (like a list 
slot) somehow detracts from its conceptual beauty?  Is so, would you say 
the same about numbers?

It seems to me that the beauty of the function concept is quite independent 
of its definition syntax and post-definition access method.

>, and very powerful.

If anything, adding a source pointer to a function object makes it more, 
not less powerful.

>> What about passing an anonymous function as an argument,
 >> which is the most common case?
>
> I don't really like that. The syntax is way too messy.

I agree.

> Just the
>funcref = def(args):
>...
> syntax would suffice for me.

But this is deficient relative to def funcref(args): ... since the *only* 
difference is to substitute a generic tag (like '') for a specific 
tag (like 'funcref') for the .func_name attribute.

Terry J. Reedy




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


Re: Python versus Perl

2005-09-06 Thread Michael Ekstrand
I don't have any benchmark/performance data available, so I'll pass on 
those questions, but I'll take a stab at the third (being reasonably 
fluent in both languages).

On Sep 6, 2005, at 12:03 PM, Dieter Vanderelst wrote:
> 3 - In my opinion Python is very well suited for text processing. Does
> Perl have any advantages over Python in the field of textprocessing
> (like a larger standard library maybe).

One of the substantial reasons I choose Perl over Python for text 
processing tasks (where the total program won't be significantly large) 
is that while yes,  Python has decent text processing libraries, Perl 
is a decent text processing language. Regular expressions, data 
splitting and extraction, Unix system calls, capturing output of 
programs, etc. are  all present in the language itself, and the core 
builtin functions, without needing libraries. They are also implemented 
in a manner that is fairly natural to shell programmers.

That said, Python is a much cleaner language. Easier to maintain code 
in Python is. I wrote a custom web page template mechanism in Perl that 
comprised about 5 files and 2-3k lines of code (including comments and 
blank lines - cat |wc -l). I'd be leery of doing anything much more 
substantial than that in Perl - it would rapidly get quite unwieldily. 
OTOH, Python helps organize code and keep it clean - you don't have to 
wade through all manner of punctuation and special cases to keep track 
of what's going on. And Python's OO seems much more natural than 
Perl's.

In general, I consider the two languages to have largely different 
application domains. Perl is excellent for text processing, Unix 
scripting, and parsing HTML (its HTML::Parser library is 
extraordinary). Python is more general-purpose (Perl can be, but it 
gets ugly fast). I'd use Python where someone would otherwise use Java, 
and use Perl where shell scripts don't quite cut it.

I find text processing in Python to be only slightly more natural than 
C++ or Java text processing.

Just my $0.02. Either one will do the job; which one is better depends 
on your tastes, background, specific problem.

- Michael

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


Re: which reg values modified my python installer under windows

2005-09-06 Thread Peter Hansen
Philippe C. Martin wrote:
> I forgot to mention that I want to do it automatically from my application's
> installer.

Calling the "assoc" and "ftype" commands is one approach.  Try them with 
the existing settings to see how standard Python sets them up:

c:\> assoc .py
.py=Python.File

c:\> ftype Python.File
...

Use "assoc /?" or "ftype /?" for help.

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


Re: killing thread after timeout

2005-09-06 Thread Peter Hansen
Jacek Popławski wrote:
> I am going to write python script which will read python command from 
> socket, run it and return some values back to socket.

(Sounds like a huge security risk, unless you have tight control over 
who can connect to that socket.)

> My problem is, that I need some timeout. I need to say for example:
> 
> os.system("someapplication.exe")
> 
> and kill it, if it waits longer than let's say 100 seconds
> 
> I want to call command on separate thread, then after given timeout - 
> kill thread, but I realized (after reading Usenet archive) that there is 
> no way to kill a thread in Python.

The issue isn't killing a thread in Python, it's killing the *new 
process* which that thread has started.  To do that you have to rely on 
OS-specific (i.e. non-portable) techniques.  Googling for "python kill 
process" would probably get you off to a good start.

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


Re: Replacement for lambda - 'def' as an expression?

2005-09-06 Thread Terry Reedy

"talin at acm dot org" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Of course, one can always create a named function. But there are a lot
> of cases, such as multimethods / generics and other scenarios where
> functions are treated as data, where you have a whole lot of functions
> and it can be tedious to come up with a name for each one.

Either reuse names or 'index' them: f0, f1, f2, ...

> add = def( a, b ):
>   return a + b

The difference between this and def add(a,b): return a+b would be the 
finding of .func_name to an uninformative generic tag (like '') 
versus the informative 'add'.

>I need to be able to assign a block of Python code to a particular 
>pattern,

How about (untested -- I have never actually written a decorator, and am 
following a remembered pattern of parameterized decorators) :

patcode = {}
def pat(pattern): # return decorator that registers f in patcode
  def freg(f):
f.func_name = 'pat: <%s>' % pattern # optional but useful for debug
patcode[pattern] = f
# no return needed ? since def name is dummy
  return freg

@pat('pattern1')
def f(): 

@pat('pattern2')
def f():  for pattern 2>

etc

or define freg(f,pat) and call freg *after* each definition

> having to invent a named function for each pattern is a burden :)

But you do not *have to* ;-)
or rather, you can replace func_name with a useful tag as suggested above.

Terry J. Reedy






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


Re: Linux to Windows porting question

2005-09-06 Thread Peter Otten
SHELTRAW, DANIEL wrote:

> I am trying to port some code to Windows that works fine under Linux. The
> offending line is:
> 
> blk = fromstring(f_fid.read(BLOCK_LEN),
> num_type).byteswapped().astype(Float32).tostring()
> 
> The error I get is:
> 
> ValueError: string size must be a multiple of element size
> 
> Does anyone have an idea where the problem might be? BLOCK_LEN is
> specified in bytes and num_type is Int32.

Is the file f_fid opened in binary mode?

Peter

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


Re: which reg values modified my python installer under windows

2005-09-06 Thread Philippe C. Martin
Yes Keir, Thanks a lot.

Regards;

Philippe



keirr wrote:

> Philippe,
> 
> Windows file associations are in
>
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts
> 
> Hope that helps you.
> 
>  All the best,
> 
> Keir.

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


Re: which reg values modified my python installer under windows

2005-09-06 Thread keirr
Philippe,

Windows file associations are in
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts

Hope that helps you.

 All the best,

Keir.

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


Pass pointer from C++ class to Boost Python script ?!!!

2005-09-06 Thread Mavuram, Vishnu (IT)
Hi,
Did you get an answer to this posting of yours?

What I am trying to do is:

struct Sec
{
...
};

int main(int, char **)
{
  Py_Initialize();
  ...

  Sec *s1 = new Sec();
  PyObject *args  = Py_BuildValue("(O)", s1);  //*** this is where I am
having problem

  ...
  PyObject* res = PyEval_CallObject( func, args);
  ...
  Py_Finalize();
  return 0;
}

Can you please tell me how to get convert my pointer to a valid
PyObject*?

Thanks,
Vishnu Mavuram


NOTICE: If received in error, please destroy and notify sender.  Sender does 
not waive confidentiality or privilege, and use is prohibited.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pervasive Database Connection

2005-09-06 Thread Neil Hughes
On 6/9/05 08:52, Alex Le Dain wrote:
> What is the best way to access a Pervasive database on another machine?

Assuming you mean the Pervasive.SQL DBMS...

...depends what you're trying to do and what you're comfortable with. 
Pervasive can be accessed through various access methods, e.g. low-level 
C (Btrieve) and Java APIs, ODBC/JDBC, .Net, etc.

For quick-and-dirty utilities and queries I tend to use the old Python 
ODBC driver and I've dabbled with Jython+zxJDBC.

For production code I have the luxury of a tried-and-tested C wrapper 
developed in-house as a DLL, so I can use that through c-types.

-- 
Neil

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


Linux to Windows porting question

2005-09-06 Thread SHELTRAW, DANIEL
Hello Pyhton Listees

I am trying to port some code to Windows that works fine under Linux. The 
offending line
is:

blk = fromstring(f_fid.read(BLOCK_LEN), 
num_type).byteswapped().astype(Float32).tostring()

The error I get is:

ValueError: string size must be a multiple of element size

Does anyone have an idea where the problem might be? BLOCK_LEN is specified in 
bytes
and num_type is Int32.

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


Re: killing thread after timeout

2005-09-06 Thread Steve Horsley
Jacek Popławski wrote:
> Hello.
> 
> I am going to write python script which will read python command from 
> socket, run it and return some values back to socket.
> 
> My problem is, that I need some timeout. I need to say for example:
> 
> os.system("someapplication.exe")
> 
> and kill it, if it waits longer than let's say 100 seconds
> 
> I want to call command on separate thread, then after given timeout - 
> kill thread, but I realized (after reading Usenet archive) that there is 
> no way to kill a thread in Python.
> 
> How can I implement my script then?
> 
> PS. it should be portable - Linux, Windows, QNX, etc


Probably the easiest way is to use select with a timeout (see the 
docs for library module select). eg.

 a, b c = select.select([mySocket], [], [], timeout)
 if len(a) == 0:
 print 'We timed out'
 else:
 print 'the socket has something for us'


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


Re: execute commands independantly

2005-09-06 Thread Jorgen Grahn
On 6 Sep 2005 08:07:12 -0700, Eric McGraw <[EMAIL PROTECTED]> wrote:
>
> If you want it to return when the program is finished then use
> os.system('app') but if you just want to start it and return right
> away, use os.startfile('app')

That one is Windows-only, though -- at least in 2.3 where I live. The
os.spawn* family of calls are more portable, but I'm not sure it's a good
idea to just spawn-and-forget a process. 

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dual processor

2005-09-06 Thread Jorgen Grahn
On Tue, 06 Sep 2005 08:57:14 +0100, Michael Sparks <[EMAIL PROTECTED]> wrote:
...
> Are you so sure? I suspect this is due to you being used to writing code
> that is designed for a single CPU system. What if you're basic model of
> system creation changed to include system composition as well as
> function calls? Then each part of the system you compose can potentially
> run on a different CPU. Take the following for example:
...
> It probably looks strange, but it's really just a logical extension of the
> Unix command line's pipelines to allow multiple pipelines. Similarly, from
> a unix command line perspective, the following will automatically take
> advantage of all the CPU's I have available:
>
>(find |while read i; do md5sum $i; done|cut -b-32) 2>/dev/null |sort
>
> And a) most unix sys admins I know find that easy (probably the above
> laughable) b) given a multiprocessor system will probably try to maximise
> pipelining c) I see no reason why sys admins should be the only people
> writing programs who use concurrency without thinking about it :-)

Nitpick: not all Unix users are sysadmins ;-) Some Unix sysadmins actually
have real users, and the clued users use the same tools. I used the 'make
-j3' example elsewhere in the thread (I hadn't read this posting when I
responded there).

It seems to me that there must be a flaw in your arguments, but I can't seem
to find it ;-)

Maybe it's hard in real life to find two independent tasks A and B that can
be parallellized with just a unidirectional pipe between them?  Because as
soon as you have to do the whole threading/locking/communication circus, it
gets tricky and the bugs (and performance problems) show up fast.

But it's interesting that the Unix pipeline Just Works (TM) with so little
effort.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >