Re: Python/UNO/OpenOffice?

2006-10-02 Thread olive
For me the problem is that OO2.0 is compiled against P2.3.

Is there any OO compiled with P2.4x for Windows somewhere ?

Sybren Stuvel wrote:
> Aside from what has already been said, it might be nice for you to
> read my article about OOo and Python at
> http://www.stuvel.eu/ooo-python ;-)

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


Re: PATCH: Speed up direct string concatenation by 20+%!

2006-10-02 Thread John Machin

Fredrik Lundh wrote:

>
> You should also benchmark this against code that uses the ordinary
> append/join pattern.  (you've posted conflicting benchmarks for 2.5,
> but if I'm trusting the benchmarks that looks more reasonable, the
> standard implementation pattern is still around 10 times faster than
> your approach).
>

And the OP might like to go a bit further, and as well as benchmarking
this style:
array = []
array.append("aaa")
array.append("bbb")
etc
try benchmarking this ... well "style" may not be the appropriate word
:-)
array = []
arrapp = array.append
arrapp('aaa')
arrapp('bbb')
etc

Cheers,
John

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


Re: Problem with .next() method adding junk characters.

2006-10-02 Thread Fredrik Lundh
"Rainy" <[EMAIL PROTECTED]> wrote:

> I'm just curious as to what's happening. I understand that you're not
> supposed to call .next on a file open for writing. But I don't know why
> and how it does what happened here; besides, I've seen the same thing
> happen before when I was doing something else with file
> open/write/close, but I don't remember the specifics.

C's stdio library require you to call "flush" when switching between reading and
writing; if you don't, the result is undefined.

 



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


Re: builtin regular expressions?

2006-10-02 Thread Nick Craig-Wood
Kay Schluehr <[EMAIL PROTECTED]> wrote:
>  I notice two issues here. Only one has anything to do with regular
>  expressions. The other one with 'explicit is better than implicit': the
>  many implicit passing operations of Rubys case statement. Using
>  pseudo-Python notation this could be refactored into a more explicit
>  and not far less concise style:
> 
>  if line.match( "title=(.*)" ) as m:
> print "Title is %s"%m.group(1)
>  elif line.match( "track=(.*)" ) as m:
> print "Track is %s"%m.group(1)
>  elif line.match( "artist=(.*)" ) as m:
> print "Artist is %s"%m.group(1)
> 
>  Here the result of the test line.match( ) is assigned to the local
>  variable m if bool(line.match( )) == True. Later m can be used in the
>  subsequent block.

Interesting!

This is exactly the area that (for me) python regexps' become more
clunky that perl's - not being able to assign and test the match
object in one line.

This leads to the rather wordy

m = re.match("title=(.*)", line)
if m:
print "Title is %s" % m.group(1)
else:
m =  re.match("track=(.*)", line)
if m:
print "Track is %s"%m.group(1)
else:
m = re.match("artist=(.*)", line)
if m:
print "Artist is %s"%m.group(1)


If you could write

if re.match("title=(.*)", line) as m:
print "Title is %s" % m.group(1)
elif re.match("track=(.*)", line) as m:
print "Track is %s" % m.group(1)
elif re.match("artist=(.*)", line) as m:
print "Artist is %s" % m.group(1)

that would be a significant benefit.

You can of course define a helper class like this

class Matcher:
"""Regexp matcher helper"""
def match(self, r,s):
"""Do a regular expression match and return if it matched."""
self.value = re.match(r,s)
return self.value
def __getitem__(self, n):
"""Return n'th matched () item."""
return self.value.group(n)

Which makes this bit really quite neat

m = Matcher()
if m.match("title=(.*)", line):
print "Title is %s" % m[1]
elif m.match("track=(.*)", line):
print "Track is %s" % m[1]
elif m.match("artist=(.*)", line):
print "Artist is %s" % m[1]

> Moreover match becomes a string method. No need for extra importing
> re and applying re.compile(). Both can be done in str.match() if
> necessary.

I'm happy with the re module.  Having transitioned from perl to python
some time ago now, I find myself using many fewer regexps due to the
much better built in string methods of python.  This is a good thing,
because regexps should be used sparingly and they do degenerate into
line noise quite quickly...

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DAT file compilation

2006-10-02 Thread Nick Craig-Wood
Jay <[EMAIL PROTECTED]> wrote:
>  Diez B. Roggisch wrote:
> > Jay schrieb:
> > > Is there a way through python that I can take a few graphics and/or
> > > sounds and combine them into a single .dat file?  If so, how?  And how
> > > can I access the data in the .dat file from inside the python script?
> > 
> > Use a zip-file. See the zipfile-module.
>
>  That's one solution, but I'd rather a file format the end-user can't
>  easily mess around with.

Just don't give it a .zip extension.  Works for java and .jar, and
openoffice and all of its many extensions.

If you are feeling really paranoid then encrypt it.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: windev vs python SOS

2006-10-02 Thread Bruno Desthuilliers
Amanda wrote:
(snip)
> I am always amazed when I meet fanatics!!

I'm always amazed when I meet PC-Soft's salespersons...

> Links abour Windev for those who like facts :
> 
> http://www.windev.com/pcsoft/testimonials/index.html
> http://www.pcsoft.fr/annonce10/photos.html
> http://www.pcsoft.fr/pcsoft/120pages/index.html

"Facts" ? Lol ! It's about as factual as the existence of Saddam
Hussein's mass destruction weapons.

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


Re: windev vs python SOS

2006-10-02 Thread Fredrik Lundh
Bruno Desthuilliers wrote:

> Amanda wrote:
> (snip)
>> I am always amazed when I meet fanatics!!
>
> I'm always amazed when I meet PC-Soft's salespersons...

isn't there some non-python forum where you can sort this one out ?

 



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


Re: Can recursive descent parser handle Python grammar?

2006-10-02 Thread Ben Sizer
[EMAIL PROTECTED] wrote:
> Ben Sizer wrote:
> > [EMAIL PROTECTED] wrote:
> > > I'm a compiler newbie and was curious if Python's language/grammar
> > > can be handled by a recursive descent parser.
> >
> > I believe a recursive descent parser can handle any grammar; it just
> > depends on how pure you want it to be.
> >
> > --
> > Ben Sizer
>
> Thanks!  What do you mean by 'pure'?

By 'pure' I mean entirely recursive and not iterative. Implementation
becomes easier if you're not writing a purely recursive parsing
program, and it makes it more practical to implement an arbitrary
amount of 'read-ahead'.

-- 
Ben Sizer

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


Re: preemptive OOP?

2006-10-02 Thread Bruno Desthuilliers
John Salerno wrote:
> Ok, I have a new random question for today -- feel free to ignore and
> get back to your real jobs! :)
> 
> Anyway, I'm creating a GUI (yes, all part of my master plan to
> eventually have some sort of database application working) and it's
> going to involve a wx.Notebook control. I think I have two options for
> how I can do this. Within the class for the main window frame, I can say:
> 
> notebook = wx.Notebook(panel) # panel is parent of the Notebook control
> 
> This uses the default wx.Notebook class, and works just fine. But I was
> thinking, is it a smart idea to do this instead:
> 
> class MyNotebook(wx.Notebook):
> def __init__(self, parent):
> wx.Notebook.__init__(self, parent)
> 
> and then call it from the main frame as:
> 
> notebook = MyNotebook(panel)
> 
> This seems to allow for future expansion of the customized Notebook
> class, but at the same time I have no idea how or why I'd want to do that.
> 
> So my question in general is, is it a good idea to default to an OOP
> design like my second example when you aren't even sure you will need
> it?

It of course depends on a lot of factors. Two of these factors are:

1/ given my current knowledge of the project, what are the probabilities
that I'll end up subclassing wx.Notebook ?

2/ if so, in how many places would I have to s/wx.Notebook/MyNotebook/

The second factor is certainly the most important here. Even if the
answer to 1/ is "> 50%", if there's only a couple of calls in a single
file, there's really no need to do anything by now IMHO.

As a side note, the common OO pattern for this potential problem is to
replace direct instanciation with a factory, so you just have to modify
the factory's implementation.

Now one of the nice things with Python is that it doesn't have a "new"
keyword, instead using direct calls to the class (the fact is that in
Python, classes *are* factories already). Another nice thing is that you
can easily 'alias' callables. The combination of these 2 features makes
factory pattern mostly straightforward and transparent. As someone
already pointed out, you don't need to subclass wx.Notebook - just
'alias' it to another name.

> I know it won't hurt, 

Mmm... Not so sure. One could argue that "premature generalization is
the root of all evil" !-)

> and is probably smart to do sometimes,

cf above.

> but
> maybe it also just adds unnecessary code to the program.

It's not that much about the unnecessary code (which can boil down to a
single assignement), but about the unnecessary level of indirection
(which, as someone stated, is the one and only problem that cannot be
solved by adding a level of indirection !-).



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


Re: "Wiki in 10 minutes"

2006-10-02 Thread Bruno Desthuilliers
Michiel Sikma wrote:
> Hello everybody.
> 
> I recently had a bit of data loss and, among some other minor things,
> lost my bookmarks. 
(snip)
> 
> Any other links pertaining to the creation of web applications with
> Python, which I'm only just getting into, would also be appreciated.

Could it be that one ?

http://adminspotting.net/building-web-pages-with-python/


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


Re: python threading and timing

2006-10-02 Thread Laurent Pointal
Dennis Lee Bieber a écrit :
> On Sun, 1 Oct 2006 22:28:10 +0200, "Oeyvind Brandtsegg"
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
>> Also, I wonder what method I should be using to get a precise timing
>> in my automation thread (acting as a sequencer).
>>
>   Use a real-time OS (which neither M$ Windows nor Linux/UNIX claim to
> be).
> 
>   All non-deterministic, multi-tasking, OS's (like Windows, Linux,
> Solaris, AmigaOS) only guarantee that, for example, a sleep() call will
> not return /before/ the time specified. There is no specification for
> how much time /over/ the duration actually takes place.
> 
>   And setting the task priority into the Windows "real-time" category
> is not sufficient -- I had an application that had to put out data on
> six pins of the parallel port (acting as three discrete RS-422 style
> balanced signals) in time with a (1KHz, as I recall) clock signal coming
> in on another pin of the parallel port. The data was still getting
> glitches every ~256 clocks as the OS did something in the background.
> (the application was written in VC++6, and even disabled the GUI during
> the data output operation.
> 

+++

realtime OSes != high level priority threads

And for a sound production using a sequencer, it looks like to need real
realtime.


And dont use Python threads for realtime multithreading, even on a
realtime OS (because of the GIL - Global Interpreter Lock).

May use Python for some -non realtime- parts, but I would not use any
scripting language (not specific to Python) for real-time work (prefer
C, ADA, maybe Java with ad-hoc extensions).

You may go to Python by writing a Python C extension module (doing
realtime work on its own - but never relying on python GIL in critical
times), communicating with normal python scripts (shared memory...
things which dont need the GIL if possible).

A+

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


Re: strange append

2006-10-02 Thread Bruno Desthuilliers
E.Nurminski wrote:
> Hello to all good people
> 
> I am new to the great Py so am quite puzzled by the following code
> 
> ---
> 
> res = []
> x = [ 1, 1 ]
> for i in xrange(0,5):
>   res.append(x)
>   x[1] = x[1] + 1
>   print "x = ", x
>   print "res = ", res
> 
> ---
> 
> Looks like it puts smth like reference to 'x' into 'res' list, instead of 
> value. But if I want a value should I use a different method or what ?

What difference do you make between "values" and "references" ?-)

Hint 1: in Python, all you have are objects. Yes, even strings and
numbers etc...

> Evgeni
> 
> P.S. Could not easily find the issue in the manual/tutorial can you point 
> me out to smth relevant ?
> 

Hint 2 : Python has something very nice which is the interactive python
shell. This lets you try code snippets and see by yourself how it really
works :

[EMAIL PROTECTED] ~ $ python
Python 2.4.3 (#1, Sep 29 2006, 20:26:46)
[GCC 4.1.1 (Gentoo 4.1.1-r1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = [1, "aaa"]
>>> mylist.append(42)
>>> mylist.append("lala")
>>> mylist
[1, 'aaa', 42, 'lala']
>>>

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


Re: Making sure script only runs once instance at a time.

2006-10-02 Thread Hari Sekhon




Fredrik Lundh wrote:

  Hari Sekhon wrote:

  
  
I'm not sure if that is a very old way of doing it, which is why I was 
reluctant to do it. My way actually uses the process list of the os 
(linux) and counts the number of instances. If it is more than 0 then 
another process is running and the script exits gracefully.

  
  
the code that reliably identifies instances of a given program would be 
interesting to see.

  
  
Also, apart from the fact the using lockfiles feels a bit 1970s, I have

  
   > found that in real usage of other programs within the company that use
 > lockfiles, it sometimes causes a bit of troubleshooting time when
 > it stops working due to a stale lockfile.

to minimize that risk, store the pid in the lockfile (and preferrably 
also the host name), and make sure that the program checks that the pid 
is still active before it "stops working".



  


How exactly do you check that the pid is still active in python? Is
there a library or something that will allow me to manipulate system
processes and listings etc the way everybody does in unix shells

I'm a huge fan of shell so I've done my own thing which leans on shell
as follows:

import sys,commands,os

scriptpath = sys.argv[0]
scriptname = os.path.basename(scriptpath)

number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc
-l' % scriptpath)

if number_procs > 1:
    print "There appears to be another %s process running." % scriptname
    print "Please do not run more than one instance of this program"
    print "Quitting for safety..."
    sys.exit(200)

This works nicely for me.

You might also want to add a bit of discrimination to the script
(something along the lines of "get a decent os"...since this won't work
on windows)

import platform
if platform.system() != 'Linux':
    print "Sorry but this program can only be run on Linux"
    sys.exit(201)
    #todo: should do a bit extra for our bsd cousins here


Let me know if you think you have a better way. Please provide a code
snippet if so.

-h


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

Re: Making sure script only runs once instance at a time.

2006-10-02 Thread Hari Sekhon




AMENDMENT:

The line 

number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc
-l' % scriptpath)

was supposed to be

number_procs=int(commands.getstatusoutput('ps -ef|grep %s|grep -v
grep|wc
-l' % scriptpath)[1])

-h

Hari Sekhon


Hari Sekhon wrote:

  
Fredrik Lundh wrote:
  
Hari Sekhon wrote:

  

  I'm not sure if that is a very old way of doing it, which is why I was 
reluctant to do it. My way actually uses the process list of the os 
(linux) and counts the number of instances. If it is more than 0 then 
another process is running and the script exits gracefully.



the code that reliably identifies instances of a given program would be 
interesting to see.

  

  Also, apart from the fact the using lockfiles feels a bit 1970s, I have


 > found that in real usage of other programs within the company that use
 > lockfiles, it sometimes causes a bit of troubleshooting time when
 > it stops working due to a stale lockfile.

to minimize that risk, store the pid in the lockfile (and preferrably 
also the host name), and make sure that the program checks that the pid 
is still active before it "stops working".



  
  
  
How exactly do you check that the pid is still active in python? Is
there a library or something that will allow me to manipulate system
processes and listings etc the way everybody does in unix shells
  
I'm a huge fan of shell so I've done my own thing which leans on shell
as follows:
  
import sys,commands,os
  
scriptpath = sys.argv[0]
scriptname = os.path.basename(scriptpath)
  
number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc
-l' % scriptpath)
  
if number_procs > 1:
    print "There appears to be another %s process running." % scriptname
    print "Please do not run more than one instance of this program"
    print "Quitting for safety..."
    sys.exit(200)
  
This works nicely for me.
  
You might also want to add a bit of discrimination to the script
(something along the lines of "get a decent os"...since this won't work
on windows)
  
import platform
if platform.system() != 'Linux':
    print "Sorry but this program can only be run on Linux"
    sys.exit(201)
    #todo: should do a bit extra for our bsd cousins here
  
  
Let me know if you think you have a better way. Please provide a code
snippet if so.
  
-h



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

Re: PyXML not supported, what to use next?

2006-10-02 Thread Oliver Andrich
Hi PaulOn 9/30/06, Paul Watson <[EMAIL PROTECTED]> wrote:
It would appear that xml.dom.minidom or xml.sax.* might be the bestthing to use since PyXML is going without support.  Best of all it isincluded in the base Python distribution, so no addition hunting required.
Is this right thinking?  Is there a better solution?I am using lxml as my standard tool of choice. It includes the easy interface of ElementTree and the speed and power of being backed by libxml2 and libxslt. But this mainly cause I have to deal with large XMLs in a fast way. Otherwise pure ElementTree is a very, very nice choice. And it is also our "backup" choice, when lxml is not available on a system.
Best regards,Oliver-- Oliver Andrich <[EMAIL PROTECTED]> --- http://roughbook.de/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [OT] windev vs python SOS

2006-10-02 Thread Bruno Desthuilliers
Fredrik Lundh wrote:
> Bruno Desthuilliers wrote:
> 
>> Amanda wrote:
>> (snip)
>>> I am always amazed when I meet fanatics!!
>> I'm always amazed when I meet PC-Soft's salespersons...
> 
> isn't there some non-python forum where you can sort this one out ?

Yes, you're right, sorry...

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


Python threads and Numeric/SciPy exploit Dual Core ?

2006-10-02 Thread robert
Simple Python code obviously cannot use the dual core by Python threads.
Yet, a program drawing CPU mainly for matrix computations - preferably 
with Numeric/SciPy -  will this profit from a dual core when using 2 (or 
more) Python threads?

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


__init__ style questions

2006-10-02 Thread Will McGugan
I am writting a Vector3D class as a teaching aid (not for me, for
others), and I find myself pondering over the __init__ function. I want
it to be as easy to use as possible (speed is a secondary
consideration).

Heres the __init__ function I have at the moment.

class Vector3D(object):

__slots__ = ('x', 'y', 'z')

def __init__(self, x_or_iter=None, y=None, z=None):

if x_or_iter is None:
self.x = self.y = self.z = 0
elif z is None:
it = iter(x_or_iter)
self.x = float(it.next())
self.y = float(it.next())
self.z = float(it.next())
else:
self.x = float(x_or_iter)
self.y = float(y)
self.z = float(z)

A Vector3D can be constructed in 3 ways. If no parameters are given it
assumes a default of (0, 0, 0). If one parameter is given it is assumed
to be an iterable capable of giving 3 values. If 3 values are given
they are assumed to be the initial x, y, z.

And now for the ponderings...

1) Is 'overloading' like this pythonic, or should I supply alternative
contstructors?

2) I convert the input values to floats, which seems convenient because
a Vector could be constructed with integers and other objects capable
of being converted to floats. Could this hide errors?

3) I like the constructing from an iterable, but it does mean that I
can do something crazy like Vector3D("123"). Could this also hide
errors?

4) This does seem like a good candidate for __slots__, since there will
could be large-ish lists of Vector3Ds. But is it a premature
optimization?

If it was just for myself or other experienced programmers I wouldn't
be bothered about having the ability to do stupid things, because I
simply wouldnt do them! But I dont want to teach beginner programmers
bad habbits!

Any comments appreciated...

Will McGugan
--
http://www.willmcgugan.com

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


Re: Python threads and Numeric/SciPy exploit Dual Core ?

2006-10-02 Thread Fredrik Lundh
"robert" wrote:

> Simple Python code obviously cannot use the dual core by Python threads.
> Yet, a program drawing CPU mainly for matrix computations - preferably
> with Numeric/SciPy -  will this profit from a dual core when using 2 (or
> more) Python threads?

as long as the binding releases the GIL, sure.

 



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


Re: __init__ style questions

2006-10-02 Thread Duncan Booth
"Will McGugan" <[EMAIL PROTECTED]> wrote:

> A Vector3D can be constructed in 3 ways. If no parameters are given it
> assumes a default of (0, 0, 0). If one parameter is given it is assumed
> to be an iterable capable of giving 3 values. If 3 values are given
> they are assumed to be the initial x, y, z.
> 
> And now for the ponderings...
> 
> 1) Is 'overloading' like this pythonic, or should I supply alternative
> contstructors?

No it isn't Pythonic. Why not just require 3 values and move the 
responsibility onto the caller to pass them correctly? They can still use 
an iterator if they want:

Vector3D(a, b, c)
Vector3D(*some_iter)

Then your initialiser becomes:

def __init__(self, x=0, y=0, z=0):
self.x, self.y, self.z = x, y, z

much cleaner and also catches accidental use of iterators.

Alternatively, insist on always getting exactly 0 or 1 arguments:

Vector3D((a,b,c))
Vector3D(some_iter)

def __init__(self, (x, y, z)=(0,0,0)):
self.x, self.y, self.z = x, y, z

which is great if you already have lots of 3-tuples, but a pain otherwise 
to remember to double the parentheses.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __init__ style questions

2006-10-02 Thread Fredrik Lundh
Duncan Booth wrote:

> No it isn't Pythonic.

rubbish.  using a single constructor that handles two common use cases is
perfectly Pythonic (especially if you're targeting casual programmers).

 



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


Re: __init__ style questions

2006-10-02 Thread Will McGugan

Duncan Booth wrote:

> No it isn't Pythonic. Why not just require 3 values and move the
> responsibility onto the caller to pass them correctly? They can still use
> an iterator if they want:
>
> Vector3D(a, b, c)
> Vector3D(*some_iter)

I kind of liked the ability to partially use iterators. It would be
convenient for reading in from a file for example

f = file( "model.txt" )
v1 = Vector3D( f )
v2 = Vector3D( f )
v3 = Vector3D( f )

Which you couldnt do with a tuple, because the * syntac would attempt
to read the entire file (I think).

>
> Then your initialiser becomes:
>
> def __init__(self, x=0, y=0, z=0):
> self.x, self.y, self.z = x, y, z
>
> much cleaner and also catches accidental use of iterators.
>
> Alternatively, insist on always getting exactly 0 or 1 arguments:
>
> Vector3D((a,b,c))
> Vector3D(some_iter)
>
> def __init__(self, (x, y, z)=(0,0,0)):
> self.x, self.y, self.z = x, y, z
>
> which is great if you already have lots of 3-tuples, but a pain otherwise
> to remember to double the parentheses.

Hmm. Not keen on that for the reason you mentioned. For my particular
use case there would be a lot of Vector3D 'literals'.

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


Re: Python threads and Numeric/SciPy exploit Dual Core ?

2006-10-02 Thread Oeyvind Brandtsegg
I've been trying to make my music app use dual core,
and would very much like some more detailed information on this.

Excuse my lack of knowledge,
but how do I explicitly release the GIL ?

I haven't learned this, but have found through experimentation that I
can release a thread by using time.sleep(0) inside a thread's "run
while true" loop. This seems to create an interrupt, and give other
threads a chance to do their thing.
If this is terribly wrong (it works, but I dont' know how stable it
is), please do point me in the direction of a proper way to implement
it.
As stated in an earlier post, my threads do not work on shared data,
so I have not implemented any sort of lock or mutex.

best
Oeyvind



On 10/2/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> "robert" wrote:
>
> > Simple Python code obviously cannot use the dual core by Python threads.
> > Yet, a program drawing CPU mainly for matrix computations - preferably
> > with Numeric/SciPy -  will this profit from a dual core when using 2 (or
> > more) Python threads?
>
> as long as the binding releases the GIL, sure.
>
> 
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __init__ style questions

2006-10-02 Thread Duncan Booth
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote:

> Duncan Booth wrote:
> 
>> No it isn't Pythonic.
> 
> rubbish.  using a single constructor that handles two common use cases is
> perfectly Pythonic (especially if you're targeting casual programmers).
> 
Yes, but I don't think that the specific case the OP asked about would be 
pythonic: there was no need two separate calling conventions there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "ValueError: Empty module name" on basic import

2006-10-02 Thread alain MONTMORY






alain MONTMORY a écrit :

  
Thank for your response  :-) 
  
I have tried (it's my first try ..)  :
  ./TestOfficiel TestPythonFoo multiply 3 2
and i get :
[EMAIL PROTECTED] swigCallPython]$ ./TestOfficiel TestPythonFoo
multiply 3 2
ImportError: No module named TestPythonFoo
Failed to load "TestPythonFoo"
  
Then i tried what you suggest below :
[EMAIL PROTECTED] swigCallPython]$ python
Python 2.3.4 (#2, Aug 19 2004, 15:49:40)
[GCC 3.4.1 (Mandrakelinux (Alpha 3.4.1-3mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> __import__("TestPythonFoo")

  
and it works !!!
why this doesn't work with the api 
  pModule = PyImport_Import(pName);

  
  pModule is null after the call
  
  
is there a PYTHONPATH to set or semething else...

I put :
export PYTHONPATH=$PYTHONPATH:
and it works,
thank you,
your response put me on the way...



thanks 
  
Alain
  
John Machin a écrit :
  
alain MONTMORY wrote:
  

  Hello everybody,

I am a newbie to python so I hope I am at the right place to expose my
problem. :-[

I am working on linux mandrake 10.1 with python :
python -V
Python 2.3.4
I am trying o run the example which stay in the documentation in paragraph
http://www.python.org/doc/2.4.2/ext/pure-embedding.html 5.3 Pure Embedding
I download the code example from
http://www.python.org/doc/2.4.2/ext/run-func.txt
I call the file "TestOfficiel.c" and I compile it with :
gcc -g -I/usr/include/python2.3/ TestOfficiel.c -o TestOfficiel
-lpython2.3 -ldl
all is OK (or seems to be...).
as stated in the documentation  I creat a file "TestPythonFoo.py" which
contain
"
def multiply(a,b):
print "Will compute", a, "times", b
c = 0
for i in range(0, a):
c = c + b
return c
"
I launch
./TestOfficiel ./TestPythonFoo.py multiply 3 2
and as a result :
ValueError: Empty module name
Failed to load "./TestPythonFoo.py"



This is (I believe) because of the "." at the front.

  

  if I try an absolute path to the python file :
./TestOfficiel `pwd`/TestPythonFoo.py multiply 3 2
I obtain :
ImportError: No module named
/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py



It's quite correct, there never could be a module named that. The name
of your module is TestPythonFoo -- so all you should have to do is
./TestOfficiel TestPythonFoo multiply 3 2

  

  Failed to load
"/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py"




  

  Of course the file exist :
[EMAIL PROTECTED] swigCallPython]$ ll
/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py
-rwxrwx--x  1 montmory esoppe 126 sep 29 14:04
/space/ESOPPE_PROJET/Outils/SwigPython/swigCallPython/TestPythonFoo.py*

I found lot of post about "ValueError: Empty module name" but no clear
solution (clear for me...).
What's wrong ?
my python version?
Additionnal informations :
gcc version 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)

Thanks for your help,

best regards,

Alain




--07010503090108070407
Content-Type: text/plain
Content-Disposition: inline;
	filename="TestOfficiel.c"
X-Google-AttachSize: 2022

#include 

int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;

if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");



"pythonfile" is confusing; it should be "modulename".


  
  
Yes you are right, but i left the example file "as it is"
  

  return 1;
}

Py_Initialize();
pName = PyString_FromString(argv[1]);
/* Error checking of pName left out */

pModule = PyImport_Import(pName);



As the docs for this function say, it just calls the same routine that
is called by the __import__ built-in function. One can experiment with
that:


OS-prompt>copy con foo.py
print 'hello fubar world'
^Z
1 file(s) copied.

OS-prompt>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
  

  

  __import__("foo")


  

hello fubar world

  

  

  __import__("foo.py")


  

Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named py
  

  

  __import__("")


  

Traceback (most recent call last):
  File "", line 1, in ?
ValueError: Empty module name
  

  

  __import__(r".\foo")


  

Traceback (most recent call last):
  File "", line 1, in ?
ValueError: Empty module name
  

  

  __import__(r"./foo")


  

Traceback (most recent call last):
  File "", line 1, in ?
ValueError: Empty module name
  

  

  __import

Re: __init__ style questions

2006-10-02 Thread Duncan Booth
"Will McGugan" <[EMAIL PROTECTED]> wrote:

> Duncan Booth wrote:
> 
>> No it isn't Pythonic. Why not just require 3 values and move the
>> responsibility onto the caller to pass them correctly? They can still
>> use an iterator if they want:
>>
>> Vector3D(a, b, c)
>> Vector3D(*some_iter)
> 
> I kind of liked the ability to partially use iterators. It would be
> convenient for reading in from a file for example
> 
> f = file( "model.txt" )
> v1 = Vector3D( f )
> v2 = Vector3D( f )
> v3 = Vector3D( f )
> 
> Which you couldnt do with a tuple, because the * syntac would attempt
> to read the entire file (I think).

Yes, it would, although since the implication is that your class expected 
numbers and the file iterator returns strings I'm not sure how much it 
matters: you are still going to have to write more code than in your 
example above. e.g.

   v1 = Vector3D(float(n) for n in itertools.islice(f, 3))

or with my variant:

   v1 = Vector3D(*(float(n) for n in itertools.islice(f, 3)))


I think my main objection to your code was that it introduced too many ways 
for the constructor to do unexpected things silently. e.g. your suggestion 
Vector3D("abc"), or Vector3D((1,2,3,4)) and I don't like errors going 
uncaught. That's why I think it is better to pass in exactly the arguments 
you need and convert them at the point where you can tell what the ambigous 
construction actually meant. I have no objection though to e.g. a class 
factory method which does all of this:

@classmethod
def fromStringSequence(cls, iter):
return cls(*(float(n) for n in itertools.islice(iter, 3)))

because that still makes you decide at the point of call whether you want:

   v1 = Vector3D(1, 2, 3)

or
   v1 = Vector3D.fromStringSequence(f)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/UNO/OpenOffice?

2006-10-02 Thread Colin J. Williams
wesley chun wrote:
> as others have said, that project provides a working interface to OOo
> (OpenOffice 2 on Ubuntu Breezy and Dapper).  i've made several posts
> to this regard over the summer here on CLP.  i was mostly using it to
> "mess around" with documents in StarWriter.
> 
> cheers,
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
> http://corepython.com
> 
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
I've done some small things with Python/OpenOffice, using Windows XP. 
They appear to work OK.

It seems that there is only one person to maintain the Python interface 
and that there few users - no critical mass.  I hope that this will 
change as OpenOffice is, with the exception of the Base component, a 
solid package. The base (database) component is evolving.

Colin W.


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


Re: Python threads and Numeric/SciPy exploit Dual Core ?

2006-10-02 Thread Fredrik Lundh
Oeyvind Brandtsegg wrote:

> I've been trying to make my music app use dual core,
> and would very much like some more detailed information on this.
>
> Excuse my lack of knowledge,
> but how do I explicitly release the GIL ?

http://docs.python.org/api/threads.html

> I haven't learned this, but have found through experimentation that I
> can release a thread by using time.sleep(0) inside a thread's "run
> while true" loop. This seems to create an interrupt, and give other
> threads a chance to do their thing.

that (momentarily) blocks the current thread, and forces a rescheduling.

 



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


Re: __init__ style questions

2006-10-02 Thread Will McGugan

Duncan Booth wrote:
>
> Yes, it would, although since the implication is that your class expected
> numbers and the file iterator returns strings I'm not sure how much it
> matters: you are still going to have to write more code than in your
> example above. e.g.
>
>v1 = Vector3D(float(n) for n in itertools.islice(f, 3))
>
> or with my variant:
>
>v1 = Vector3D(*(float(n) for n in itertools.islice(f, 3)))
>

The generator expression wouldnt really be neccesary since the
constructor converts the iterated values to floats.

But! I understand your objection. It doesn't quite fit with 'explicit
is better than implicit'. Im just debating the trade-off with catching
foolish mistakes and making it easier to use for beginners.

Thanks.

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


Re: Python/UNO/OpenOffice?

2006-10-02 Thread John Machin

Colin J. Williams wrote:

> I've done some small things with Python/OpenOffice, using Windows XP.
> They appear to work OK.

As you might have noticed from my earlier post, I can't get off the
ground. Can you please give an example (with code) of a "small thing"
that works OK?

TIA,
John

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


VIdeo Converence Software: Tk and thread synchronization

2006-10-02 Thread Paolo Pantaleo
Hi,

I am going on writing my video conference software. I wrote the video
grab, code/decode, and netwoark (multicast) transport.

I have one thread doing this:

[thread 1]
while True:
  for some times:
my_socket.recv() #blocking here
store data
  compute image #here we have a complete new image to display

Now, I was thinking to display the image in a  Tk window. But I think
i will need a separate thread to run the mainloop() [thread 2], right?
 How can I signale to the Tk thread that a new image is ready to be
shown? I was thinkin on using an event generated for the first
(network) thread. But I don't know how to do it exactly. Any
suggestion, please?

What if I access to Tk object form thread 1, is Tk thread safe?

Thnx
PAolo

-- 
if you have a minute to spend please visit my photogrphy site:
http://mypic.co.nr
-- 
http://mail.python.org/mailman/listinfo/python-list


PYTHON PHONE MODULE

2006-10-02 Thread vedran_dekovic
Hello,
Can you tell me one simple python phone module and if that module have
some
moudules which need download from internet,then give me urls of that
modules







  THANKS!!

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


Help with ConfigParser

2006-10-02 Thread tony . ha

Hello I use ConfigParser as show below
to read a config.txt file;

from ConfigParser import ConfigParser

config = ConfigParser()
config.read('config.txt')
items = config.items('FV')
for item in items:
   module_name = item[0]
   print module_name


The config.txt file has the following

[FV]
# Set the module to "1" to
enable the regression test run on it, otherwise set it to "0"

ip_dtlmmio0_1803: 0
ip_gpio0_4004: 0
ip_dmac0_1903: 0
ip_ptA_a_sdramc_2022: 1
ip_timer0_3012: 0



the output has been convert to lowercase,
i.e ip_ptA_a_sdramc_2022  become ip_pta_a_sdramc_2022
(the captial letter 'A, become lower
case 'a').

Question: How can I pervent ConfigParse
to convert Upper case yo lower case??, thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: changing a file's permissions

2006-10-02 Thread oscartheduck
> This is an attribute of the file (an object in the filesystem) which
> is checked by the kernel before allowing the file to be
> executed. Python has nothing to do with this; if the attributes allow
> execution, you can execute it as a program; if not, you can't.
>

I took this to heart and changed my question to "How do I run shell
commands within a python script?" I was taking my lead from Perl, which
has the infamous backquotes, and though the two languages differ in
conceptive aim, I discovered that shell commands are accessible in
python:

http://pyre.third-bit.com/pipermail/2005fall/2005-October/000228.html




> Incidentally, if the program is intended to be run from a command
> line, it's best to name the file with no '.py' extension. The fact
> that a command is implemented in Python is irrelevant to the person
> running that command; it also means you can implement it in some other
> language later on without changing everything that uses that command.

How I've been doing it inside my script (which is a script generation
tool, nicely enough) is creating symlinks with no extension on them in
a directory in $PATH that the user has read/write/execute access to.
It's a hidden directory inside the user's home folder that I added to
the end of the path.

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


Re: Python/UNO/OpenOffice?

2006-10-02 Thread olive
John,

Here is something that works for me under XPsp2 to either save a doc or
save it as PDF:

filepath = argv[0]
exportpdf  = argv[1]

ctxLocal = uno.getComponentContext()
smgrLocal = ctxLocal.ServiceManager
resolver =
smgrLocal.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver",ctxLocal)
url =
"uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
ctx = resolver.resolve(url)
smgr = ctx.ServiceManager
desktop =
smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)

properties = []
if exportpdf == "yes":
p = PropertyValue()
p.Name = "Hidden"
p.Value = True
properties.append(p)
properties = tuple(properties)
doc = desktop.loadComponentFromURL("file:///c:"+filepath+".odt" ,
"_blank", 0, properties)

if exportpdf == "yes":
properties = []

p = PropertyValue()
p.Name = "Overwrite"
p.Value = True
properties.append(p)

p = PropertyValue()
p.Name = "FilterName"
p.Value = 'writer_pdf_Export'
properties.append(p)

properties = tuple(properties)
doc.storeToURL("file:///c:"+filepath+".pdf", properties)

else:
doc.store()

doc.dispose()

You must start OO this way first:
cd C:\Program Files\OpenOffice.org 2.0\program
soffice "-accept=socket,host=localhost,port=2002;urp;"

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


Rich view for python?

2006-10-02 Thread Jorge Vilela
Hello, this is my first post and hope can help in next posts :)i have a question, and think that many peoples have same question.Do exists any component to rich editing text?I has seen the Rich View for Delphi, it looks like an embeded world in app, so i though that could exist something as it for python.
I'm not looking for a python IDE or so, just a component to edit text in application.Thanks.Jorge Vilela.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: __init__ style questions

2006-10-02 Thread Gerard Flanagan
Will McGugan wrote:

> I am writting a Vector3D class as a teaching aid (not for me, for
> others), and I find myself pondering over the __init__ function. I want
> it to be as easy to use as possible (speed is a secondary
> consideration).
>
> Heres the __init__ function I have at the moment.
>
> class Vector3D(object):
>
> __slots__ = ('x', 'y', 'z')
>
> def __init__(self, x_or_iter=None, y=None, z=None):
>
> if x_or_iter is None:
> self.x = self.y = self.z = 0
> elif z is None:
> it = iter(x_or_iter)
> self.x = float(it.next())
> self.y = float(it.next())
> self.z = float(it.next())
> else:
> self.x = float(x_or_iter)
> self.y = float(y)
> self.z = float(z)
>
> A Vector3D can be constructed in 3 ways. If no parameters are given it
> assumes a default of (0, 0, 0). If one parameter is given it is assumed
> to be an iterable capable of giving 3 values. If 3 values are given
> they are assumed to be the initial x, y, z.
>

here's a slightly different approach:


class Vector3D(object):
__slots__ = ('x', 'y', 'z')

def __init__(self, X1=None, X2=None, X3=None):
if X3 is not None:
#assume 3 numbers
self.x = X1
self.y = X2
self.z = X3
else:
X1 = X1 or (0,0,0)
X2 = X2 or (0,0,0)
self.x = X1[0] - X2[0]
self.y = X1[1] - X2[1]
self.z = X1[2] - X2[2]

def __getitem__(self, index):
return getattr(self,self.__slots__[index])

def __str__(self):
return '(%s, %s, %s)' % (self.x, self.y, self.z )

u = Vector3D()
print u
u = Vector3D(3,4,5)
print u
u, v = Vector3D( [1,2,3] ), Vector3D( (3,2,1) )
print u, v
w = Vector3D( u,v )
print w
w = Vector3D( u, (2,2,2))
print w

(0, 0, 0)
(3, 4, 5)
(1, 2, 3) (3, 2, 1)
(-2, 0, 2)
(-1, 0, 1)

Gerard

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


Re: Python/UNO/OpenOffice?

2006-10-02 Thread olive

... and you have to start your py file with:

import uno, sys, socket
from com.sun.star.beans import PropertyValue

... and your start_oo_server.bat file with:

@SET PYTHONPATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program
Files\OpenOffice.org 2.0\program\python-core-2.3.4\lib
@SET PATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program
Files\OpenOffice.org 2.0\program\python-core-2.3.4\bin

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


Re: __init__ style questions

2006-10-02 Thread bearophileHUGS
Will McGugan:
> I am writting a Vector3D class as a teaching aid (not for me, for
> others), and I find myself pondering over the __init__ function. I want
> it to be as easy to use as possible (speed is a secondary
> consideration).

If optimizations are less important, then don't use __slots__, it
simplifies OOP management of it.

I think that accepting a single iterable too makes the calling a bit
too much elastic, so it can produce silent problems. Something like
this may be better:

from itertools import imap

class Vector3D(object):
def __init__(self, *args):
len_args = len(args)
if len_args == 3:
self.x, self.y, self.z = imap(float, args)
elif len_args == 0:
self.x = self.y = self.z = 0
else:
raise TypeError("...")

If you don't like imap, you can change that code.
If you want to accept single parameter too then you can use something
like:

class Vector3D(object):
def __init__(self, *args):
len_args = len(args)
if len_args == 3:
self.x, self.y, self.z = imap(float, args)
elif len_args == 1:
self.x, self.y, self.z = imap(float, args[0])
elif len_args == 0:
self.x = self.y = self.z = 0
else:
raise TypeError("...")

If you don't like the explicit raising of an error you may use:

class Vector3D(object):
def __init__(self, first=None, *other):
if first:
if other:
self.x = float(first)
self.y, self.z = imap(float, other)
else:
self.x, self.y, self.z = imap(float, first)
else:
self.x = self.y = self.z = 0

But this last code is less readable.

Bye,
bearophile

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


Re: PYTHON PHONE MODULE

2006-10-02 Thread skip

vedran> Can you tell me one simple python phone module ...

What is a "phone module"?  Does it manipulate phone numbers, map phone
numbers to locations, place phone calls, handle phone calls?

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


Re: Problem with .next() method adding junk characters.

2006-10-02 Thread Paul McGuire
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Rainy" <[EMAIL PROTECTED]> wrote:
>
>> I'm just curious as to what's happening. I understand that you're not
>> supposed to call .next on a file open for writing. But I don't know why
>> and how it does what happened here; besides, I've seen the same thing
>> happen before when I was doing something else with file
>> open/write/close, but I don't remember the specifics.
>
> C's stdio library require you to call "flush" when switching between 
> reading and
> writing; if you don't, the result is undefined.
>
> 
>

Sure enough, following the OP's original sequence, with an intervening flush 
between the writes and next, leaves the file in the expected state:

>>> f = file("xyzzy.dat","w")
>>> f.write("1\n")
>>> f.write("2\n")
>>> f.write("3\n")
>>> f.flush()
>>> f.next()
Traceback (most recent call last):
  File "", line 1, in ?
IOError: [Errno 9] Bad file descriptor
>>> f.close()
>>> f = file("xyzzy.dat")
>>> f.next()
'1\n'
>>> f.next()
'2\n'
>>> f.next()
'3\n'
>>> f.next()
Traceback (most recent call last):
  File "", line 1, in ?
StopIteration
>>>

I would guess then that the likely extent of any fix to this "bug" would be 
documentation to the effect of Fredrik's last comment above.

-- Paul


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


automatic progress indicator

2006-10-02 Thread rubbishemail
Hello,


I have several functions calling each other several times:

iter=0
iterations=50*20 in this case, how can the program calculate this value
automatically 


def a(y):
   for x in range(20):
# this takes a constant time
...
iter+=1
progress=iter/iterations


def b()
for y in range(50):
a(y)


The  level of the loops is not known in advance, since the
user can supply his own script to modify the main program.
(b is a library routine, the user will write something like
for value in [...]
for voltage in [...]
 b()

I would like to supply a progress indicator,  any ideas?


many thanks


Daniel

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


Re: changing a file's permissions

2006-10-02 Thread Max Erickson
James <[EMAIL PROTECTED]> wrote:
> --=_Part_63041_761240.1159752399799
> I'm writing a script in linux to excercise my python skills and
> have encountered a minor issue.
> 
> Writing the script and creating an ouput file was simple enough
> and didn't take too long. However, I don't have permissions to
> execute the file by default. Now, I could simply chmod 755 the
> sucker and have done with it, but I want to apply the permissions
> within the python script if I can. 
> 
> So my question is: how does one change a file's permissions
> inside of python?
> 
> James
> 

Assuming you want to operate on the output file:

import os
os.chmod(path, 755)


Hope this helps,

max

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


Re: Gadfly server startup error

2006-10-02 Thread aaronwmail-usenet
> Is anybody out there who has used the server+client operation
> mode successfully?

Well, several years ago, yes.

Since then the project was taken over by some volunteers
and they did an excellent job of
restructuring and modernizing (somewhat) the
*standalone* part of gadfly, but apparently they
didn't port the *client/server* component properly.
As it stands the client server portion is broken now.
(I hadn't tried it after the port, sorry).

I think if you find an older (pre-sourceforge)
tarball it will work.  I will try
to find time to fix this, unless someone else wants
to have a try.  Sorry!

Also, the reference to the new release on the
site refers to a mini-release I did a year or more
ago which fixed various bugs and also added
an xsdb interface component.

   -- Aaron Watters

===
There once was a man from Japan
whose limericks never would scan
when told this was so
he said "yes, I know,
but I always try to put as many words in the last line as I possibly
can."

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


Re: Help with ConfigParser

2006-10-02 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Question: How can I pervent ConfigParse to convert Upper case yo lower
> case??, thanks.

http://docs.python.org/dev/lib/RawConfigParser-objects.html

"""
optionxform(option)

Transforms the option name option as found in an input file or as passed in
by client code to the form that should be used in the internal structures.
The default implementation returns a lower-case version of option;
subclasses may override this or client code can set an attribute of this
name on instances to affect this behavior. Setting this to str(), for
example, would make option names case sensitive. 


If you don't pass defaults:

config = ConfigParser()
config.optionxform = str
# ...

Or, to be on the safe side:

class MyCasePreservingConfigParser(ConfigParser):
optionxform = str

config = MyCasePreservingConfigParser()
# ...

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


Re: PYTHON PHONE MODULE

2006-10-02 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> Can you tell me one simple python phone module and if that module have
> some moudules which need download from internet,then give me urls of that
> modules

I did see that you were trying to get pyphone [1] to work. According to
the description in that program, it seems that the solution you're
looking for involves dialling numbers on your modem from a Python
program. Is this correct? If so, there's a thread [2] about such
matters which mentions PySerial [3] and provides an example, tidied up
and reproduced here:

import serial
modem = serial.Serial(2)
modem.write("ATDT555\r\n")

There are other Python-based solutions involving doing things with
different kinds of telephones and telephony: t616hack [4] deals with
messaging on certain mobile telephones, BitPim [5] provides a lot of
features for communicating with various CDMA telephones, Chestnut
Dialer [6] is a PPP dialler.

Anyway, I can't really hope to enumerate all available solutions in a
reasonable amount of time, but I hope this helps at least.

Paul

[1] http://lstep.free.fr/actuel/Code/PyPhone/index.html
[2] http://mail.python.org/pipermail/python-list/2002-June/110862.html
[3] http://pyserial.sourceforge.net/
[4] http://www.python.org/pypi/t616hack
[5] http://www.bitpim.org/
[6] http://chestnut-dialer.sourceforge.net/

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


Re: Problems wth os.stat().st_mtime on Mac

2006-10-02 Thread Michael Glassford
Martin v. Löwis wrote:
> Michael Glassford schrieb:
>> Although not mentioned in the Python 2.5 News, apparently there was a
>> similar change on Mac that I'm having some problems with. On the Mac,
>> just as on Windows, os.stat().st_mtime now returns a float instead of an
>> integer.
> 
> It's isn't really new; os.stat_float_times was introduced in Python 2.3.
> What changed in 2.5 is that it is now true. See
> 
> http://docs.python.org/whatsnew/modules.html

Thanks, I wasn't aware of os.stat_float_times. This helps me a lot, 
since I can turn off the floating point times in places until 
incompatible code can be fixed.

> 
>> a) Why the difference between machines?
> 
> You really have to delve into OSX to answer this question. Several
> reasons are possible:
> - there is a change in the operating system implementations

Possible, I guess, although I don't know how to find out and there's 
likely nothing I could do about it even if I did.

> - you are using different Python versions

Python 2.5 on both.

> - you are using different file systems

This is the first thing I thought of, but all of the drives are 
formatted using "Mac OS Extended (Journalled)", which I assumed meant 
they are using the same file system.

> 
>> b) Why do most files on this machine have ".0", while some (generally
>> those I created myself using Python 2.5, I think) don't?
> 
> Hard to tell. Maybe the software that created those files explicitly
> set a time stamp on them, and failed to use the API that supports
> subsecond resolution in setting those time stamps.
> 
>> I understand how the results can be different: the os.stat() function
>> returns a posix.stat_result object, which gives back an integer value
>> for the mtime if you call __str__ or __repr__, or if you iterate on it;
>> and a float if you get the st_mtime attribute. But I would consider it a
>> bug that the results are different: a float should be returned in either
>> case.
> 
> That's for backwards compatibility: You shouldn't use the tuple
> interface anymore, but use st_mtime for new code. This will always
> be a float. OTOH, the tuple interface will continue to return
> integers forever 



OK, thanks for the explanation.

Mike

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


Re: Help with ConfigParser

2006-10-02 Thread TonyHa
Hello Peter,

Thanks for your help, and it works now!

Tony.

Peter Otten wrote:
> [EMAIL PROTECTED] wrote:
>
> > Question: How can I pervent ConfigParse to convert Upper case yo lower
> > case??, thanks.
>
> http://docs.python.org/dev/lib/RawConfigParser-objects.html
>
> """
> optionxform(option)
>
> Transforms the option name option as found in an input file or as passed in
> by client code to the form that should be used in the internal structures.
> The default implementation returns a lower-case version of option;
> subclasses may override this or client code can set an attribute of this
> name on instances to affect this behavior. Setting this to str(), for
> example, would make option names case sensitive.
> 
>
> If you don't pass defaults:
>
> config = ConfigParser()
> config.optionxform = str
> # ...
>
> Or, to be on the safe side:
>
> class MyCasePreservingConfigParser(ConfigParser):
> optionxform = str
> 
> config = MyCasePreservingConfigParser()
> # ...
> 
> Peter

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


regular expressions in the pexpect module for python

2006-10-02 Thread Mark Devine
HiI wonder if you can help me. I am using pexpect with python to access remote machines and run commands on them. I pass commands into code like so:def cmd(self, cmd):        pp=[ "|", "]", "[", "(", ")", "$", "?", "*", ".", ":"]
        expcmd=cmd        for element in pp:            expcmd=expcmd.replace(element, "\\%s" % element)        self.spawn.setecho(False)        self.spawn.sendline(cmd)        self.spawn.expect

(expcmd)        self.spawn.expect(self.prompt)        return self.spawn.beforeThe above code is supposed to match the command, then match the prompt and then return what is in between. Since pexpect uses regular expressions to match what it sees


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

commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Hari Sekhon
I'm running a command like

import commands
result = commands.getstatusoutput('somecommand')
print result[0]
3072


However, this exit code made no sense so I ran it manually from the 
command line in bash on my linux server and it gives the exit code as 
12, not this weird 3072 number.

So I tried os.system('somecommand') in the interactive python shell and 
it too returned the same result for the exit code as the unix shell, 12, 
but re-running the commands.getstatusoutput() with the exact same 
command still gave 3072.


Is commands.getstatusoutput() broken or something?


-h

-- 
Hari Sekhon

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


PyCon proposals (was Re: PATCH: Speed up direct string concatenation by 20+%!)

2006-10-02 Thread Aahz
In article <[EMAIL PROTECTED]>,
Larry Hastings <[EMAIL PROTECTED]> wrote:
>Steve Holden wrote:
>>
>> I think your project might make a very
>> interesting PyCon paper for people who were thinking about joining the
>> development effort but hadn't yet started.
>
>Perhaps; I've never been to PyCon, but it might be fun to give a
>presentation there.  That said, it would be way more relevant if the
>patch got accepted, don'tcha think?

Not really.  The principles involved are timeless, and I guarantee you a
large audience regardless of whether the patch gets accepted (provided
you specify an appropriate presentation title and summary).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"LL YR VWL R BLNG T S"  -- www.nancybuttons.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/UNO/OpenOffice?

2006-10-02 Thread John Machin

olive wrote:
> ... and you have to start your py file with:
>
> import uno, sys, socket
> from com.sun.star.beans import PropertyValue
>
> ... and your start_oo_server.bat file with:
>
> @SET PYTHONPATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program
> Files\OpenOffice.org 2.0\program\python-core-2.3.4\lib
> @SET PATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program
> Files\OpenOffice.org 2.0\program\python-core-2.3.4\bin

Many thanks for all that, olive; I made the minimal hacks to make it
open an XLS ffile, and it worked!
I'll try to see why that worked and my previous experiment crashed
inside a DLL.
Cheers,
John

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


Re: Help with ConfigParser

2006-10-02 Thread Enrico
Hi,
from the documentation:

optionxform(option)

Transforms the option name option as found in an input file or as passed in
by client code to the form that should be used in the internal structures.
The default implementation returns a lower-case version of option;
subclasses may override this or client code can set an attribute of this
name on instances to affect this behavior. Setting this to str(), for
example, would make option names case sensitive.

Bye,
Enrico


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


How to coerce a list of vars into a new type?

2006-10-02 Thread Matthew Wilson

I want to verify that three parameters can all be converted into
integers, but I don't want to modify the parameters themselves.

This seems to work:

def f(a, b, c):

a, b, c = [int(x) for x in (a, b, c)]

Originally, I had a bunch of assert isinstance(a, int) statements at the
top of my code, but I decided that I would rather just check if the
parameters can be converted into integers.

The new a, b, and c are all different objects, with different id values.
Anyhow, this all seems like black magic to me.  Can anyone explain what
is going on?

Is it as simple as call-by-value?




-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Making posts to an ASP.NET webform.

2006-10-02 Thread Bernard
hiya everyone,

I've made this little webcrawler using BeautifulSoup, urllib and
urllib2. I've been encountering ASP.NET Forms recently and I can't seem
to make a proper post to some of them. My post function has been doing
great until this particular website.
Here's some explanations first so that you guys understands my
problem...

Usually there are 8 hidden inputs spread all over the web page:
__EVENTTARGET --> that is the id of the control that is assigned by the
ASP.NET engine. It is usually in this particular form
"dg_Result$_ctl2$linkbtn1" The javascript function DoPostback usually
replaces the '$' for a ':' before doing the real post. Some other
ASP.NET page doesn't.
__EVENTARGUMENT --> nothing's here usually.
__ScrollTop --> its value is often 0
__ScrollLeft --> same as __ScrollTop
__ValidationSummary --> usually empty
__VIEWSTATEENCRYPTED --> an encrypted string. I don't know what it
means nor what it does.
__EVENTVALIDATION --> an encrypted string. I don't know what it means
nor what it does.
__VIEWSTATE --> the encrypted state of the current control. the state
of a datagrid for example.

I extract all those values using regexes on the web page, build a
dictionnary out of all those values and encrypt the whole thing using
urllib.urlencode(). Afterwards I extract the form action and post the
whole thing with cookies enabled. This procedure works like a charm.

The website I've just encounted has only 3 of the 8 hidden inputs.
(EVENTTARGET, EVENTARGUMENT & VIEWSTATE ).
I tried posting the whole thing using only these 3 values & nada.
I then tried posting the whole thing using all empty values for the 5
remaining values...still nothing.

Has anyone tried what I'm doing? and if you tried how have you
succeeded getting the data back after the post action?

thanks for any tips!

cP

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


How can I make a class that can be converted into an int?

2006-10-02 Thread Matthew Wilson
What are the internal methods that I need to define on any class so that
this code can work?

c = C("three")

i = int(c) # i is 3

I can handle the part of mapping "three" to 3, but I don't know what
internal method is called when int(c) happens.

For string conversion, I just define the __str__ method.  What's the
equivalent for int?  For float, too, while I'm at it?

TIA

Matt

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Sort by domain name?

2006-10-02 Thread js
Hi list,

I have a list of URL and I want to sort that list by the domain name.

Here, domain name doesn't contain subdomain,
or should I say, domain's part of 'www', mail, news and en should be excluded.

For example, if the list was the following

http://mail.google.com
http://reader.google.com
http://mail.yahoo.co.uk
http://google.com
http://mail.yahoo.com


the sort's output would be

http://google.com
http://mail.google.com
http://reader.google.com
http://mail.yahoo.co.uk
http://mail.yahoo.com


As you can see above, I don't want to


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


Re: How can I make a class that can be converted into an int?

2006-10-02 Thread Tim Chase
> What are the internal methods that I need to define on any class so that
> this code can work?
> 
> c = C("three")
> 
> i = int(c) # i is 3
> 
> I can handle the part of mapping "three" to 3, but I don't know what
> internal method is called when int(c) happens.
> 
> For string conversion, I just define the __str__ method.  What's the
> equivalent for int?  For float, too, while I'm at it?

Is it too unkind to say it's semi-obvious?

 >>> class Impersonator(object):
... def __str__(self): return "I'm a string"
... def __int__(self): return 42
... def __float__(self): return 3.14159
...
 >>> c = Impersonator()
 >>> float(c)
3.14158999
 >>> int(c)
42
 >>> str(c)
"I'm a string"

You say you can handle the conversion of "three" to 3, so I leave 
that implementation of __int__(self) to you... :)

-tkc



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


Re: How can I make a class that can be converted into an int?

2006-10-02 Thread Mikael Olofsson


Matthew Wilson wrote:
> What are the internal methods that I need to define on any class so that
> this code can work?
>
> c = C("three")
>
> i = int(c) # i is 3

 From Python Reference Manual, section 3.4.7 Emulating numeric types:

__complex__( self)
__int__( self)
__long__( self)
__float__( self)
 Called to implement the built-in functions complex(), int(), 
long(), and float(). Should return a value of the appropriate type.

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


Re: Python-list Digest, Vol 37, Issue 23

2006-10-02 Thread Mark Devine
HiSorry about that. Here is the full question:I wonder if you can help me. I am using pexpect with python to access remote machines and run commands on them. I pass commands into code like so:def cmd(self, cmd):
    pp=[ "|", "]", "[", "(", ")", "$", "?", "*", ".", ":"]    expcmd=cmd    for element in pp:
    expcmd=expcmd.replace(element, "\\%s" % element)    self.spawn.setecho(False)    self.spawn.sendline(cmd)    self.spawn.expect(expcmd)    self.spawn.expect(self.prompt
)    return self.spawn.beforeThe above code is supposed to match the command, then match the prompt and then return what is in between. Since pexpect uses regular expressions to match what it sees, the command needs to have certain characters backslashed. The problem is that on some remote shells hidden characters are introduced that causes the expect statement (
self.spawn.expect(expcmd)) to timeout without matching. In perl there is a way to translate any character with an ascii value of less than 32 to "" so that all hidden characters are removed. Can this be done in python? Can this be applied to the regular _expression_ used by pexpect?
BewilderedOn 02/10/06, [EMAIL PROTECTED] <
[EMAIL PROTECTED]> wrote:Send Python-list mailing list submissions to
        [email protected] subscribe or unsubscribe via the World Wide Web, visit        
http://mail.python.org/mailman/listinfo/python-listor, via email, send a message with subject or body 'help' to        
[EMAIL PROTECTED]You can reach the person managing the list at        [EMAIL PROTECTED]
When replying, please edit your Subject line so it is more specificthan "Re: Contents of Python-list digest..."Today's Topics:   1. Re: Problems wth os.stat().st_mtime on Mac (Michael Glassford)
   2. Re: Help with ConfigParser (TonyHa)   3. regular expressions in the pexpect module for python (Mark Devine)   4. commands.getstatusoutput result is not command line exit      value!!! (Hari Sekhon)
   5. PyCon proposals (was Re: PATCH: Speed up direct string      concatenation     by 20+%!) (Aahz)   6. Re: Python/UNO/OpenOffice? (John Machin)   7. Re: Help with ConfigParser (Enrico)   8. How to coerce a list of vars into a new type? (Matthew Wilson)
   9. Making posts to an ASP.NET webform. (Bernard)  10. How can I make a class that can be converted into an int?
      (Matthew Wilson)  11. Sort by domain name? (js )-- Forwarded message --From: Michael Glassford <[EMAIL PROTECTED]>
To: [email protected]: Mon, 02 Oct 2006 10:15:26 -0400Subject: Re: Problems wth os.stat().st_mtime on MacMartin v. Löwis wrote:> Michael Glassford schrieb:
>> Although not mentioned in the Python 2.5 News, apparently there was a>> similar change on Mac that I'm having some problems with. On the Mac,>> just as on Windows, os.stat().st_mtime now returns a float instead of an
>> integer.>> It's isn't really new; os.stat_float_times was introduced in Python 2.3.> What changed in 2.5 is that it is now true. See>> 
http://docs.python.org/whatsnew/modules.htmlThanks, I wasn't aware of os.stat_float_times. This helps me a lot,since I can turn off the floating point times in places untilincompatible code can be fixed.
>>> a) Why the difference between machines?>> You really have to delve into OSX to answer this question. Several> reasons are possible:> - there is a change in the operating system implementations
Possible, I guess, although I don't know how to find out and there'slikely nothing I could do about it even if I did.> - you are using different Python versionsPython 2.5 on both.> - you are using different file systems
This is the first thing I thought of, but all of the drives areformatted using "Mac OS Extended (Journalled)", which I assumed meantthey are using the same file system.>>> b) Why do most files on this machine have ".0", while some (generally
>> those I created myself using Python 2.5, I think) don't?>> Hard to tell. Maybe the software that created those files explicitly> set a time stamp on them, and failed to use the API that supports
> subsecond resolution in setting those time stamps.>>> I understand how the results can be different: the os.stat() function>> returns a posix.stat_result object, which gives back an integer value
>> for the mtime if you call __str__ or __repr__, or if you iterate on it;>> and a float if you get the st_mtime attribute. But I would consider it a>> bug that the results are different: a float should be returned in either
>> case.>> That's for backwards compatibility: You shouldn't use the tuple> interface anymore, but use st_mtime for new code. This will always> be a float. OTOH, the tuple interface will continue to return
> integers foreverOK, thanks for the explanation.Mike-- Forwarded message --From: "TonyHa" <
[EMAIL PROTECTED]>To: [email protected]: 2 Oct 2006 07:29:49 -0700Subject: Re: Help with ConfigParserHello Peter,Thanks for your help, and it works now!
Tony.Peter Otten wrot

SimpleParse installer available for 2.5

2006-10-02 Thread David Isaac
This is important for my move to Python 2.5,
so I thought others might want to know...

Alan Isaac


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


Re: How can I make a class that can be converted into an int?

2006-10-02 Thread faulkner
__int__
__long__
__float__


Matthew Wilson wrote:
> What are the internal methods that I need to define on any class so that
> this code can work?
>
> c = C("three")
>
> i = int(c) # i is 3
>
> I can handle the part of mapping "three" to 3, but I don't know what
> internal method is called when int(c) happens.
>
> For string conversion, I just define the __str__ method.  What's the
> equivalent for int?  For float, too, while I'm at it?
>
> TIA
>
> Matt
>
> --
> A better way of running series of SAS programs:
> http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles

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


Re: Sort by domain name?

2006-10-02 Thread Paul Rubin
"js " <[EMAIL PROTECTED]> writes:
> Here, domain name doesn't contain subdomain,
> or should I say, domain's part of 'www', mail, news and en should be
> excluded.

It's a little more complicated, you have to treat co.uk about 
the same way as .com, and similarly for some other countries
but not all.  For example, subdomain.companyname.de versus
subdomain.companyname.com.au or subdomain.companyname.co.uk.
You end up needing a table or special code to say
how to treat various countries.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I make a class that can be converted into an int?

2006-10-02 Thread Peter Otten
Matthew Wilson wrote:

> What are the internal methods that I need to define on any class so that
> this code can work?
> 
> c = C("three")
> 
> i = int(c) # i is 3
> 
> I can handle the part of mapping "three" to 3, but I don't know what
> internal method is called when int(c) happens.

>>> class C(object):
... def __int__(self): return 42
...
>>> int(C())
42

> For string conversion, I just define the __str__ method.  What's the
> equivalent for int?  For float, too, while I'm at it?

http://docs.python.org/ref/numeric-types.html

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


Re: How to coerce a list of vars into a new type?

2006-10-02 Thread Simon Brunning
On 10/2/06, Matthew Wilson <[EMAIL PROTECTED]> wrote:
>
> I want to verify that three parameters can all be converted into
> integers, but I don't want to modify the parameters themselves.
>
> This seems to work:
>
> def f(a, b, c):
>
> a, b, c = [int(x) for x in (a, b, c)]
>
> Originally, I had a bunch of assert isinstance(a, int) statements at the
> top of my code, but I decided that I would rather just check if the
> parameters can be converted into integers.
>
> The new a, b, and c are all different objects, with different id values.
> Anyhow, this all seems like black magic to me.  Can anyone explain what
> is going on?

You've re-bound the names "a", "b" and "c" to new objects, so
naturally they have different ids. If you leave out the "a, b, c ="
bit, you'll leave the original names bound to the objects that have
been passed into your function as arguments.

> Is it as simple as call-by-value?

The "call-by-whatever" concepts don't really apply to Python very well
- any attempt to do so seems to result in more confusion than anything
else.

I'd recommend you take a look at
. it explains everything
far better than I could.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Steve Holden
Hari Sekhon wrote:
> I'm running a command like
> 
> import commands
> result = commands.getstatusoutput('somecommand')
> print result[0]
> 3072
> 
> 
> However, this exit code made no sense so I ran it manually from the 
> command line in bash on my linux server and it gives the exit code as 
> 12, not this weird 3072 number.
> 
> So I tried os.system('somecommand') in the interactive python shell and 
> it too returned the same result for the exit code as the unix shell, 12, 
> but re-running the commands.getstatusoutput() with the exact same 
> command still gave 3072.
> 
> 
> Is commands.getstatusoutput() broken or something?
> 
> 
> -h
> 
No, it's just returning the error code in the top half of a sixteen-bit 
value. You will notice that 3072 == 2 * 256.

That's always been the way the Unix return code has been returned 
programattically, but the shell shifts it down to make it more usab;e.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: How can I correct an error in an old post?

2006-10-02 Thread Jorgen Grahn
On 1 Oct 2006 10:18:59 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
...
> and I wish to add my findings to the post, to prevent others from
> taking the wrong path.

> When I tried to replay to the post I received a reject message stating
> that it is impossible to replay to the topic since it is old and was
> closed by a manager.

That's through the Google Groups Usenet interface, right? Because on Usenet,
that's misleading at best -- we have no managers, and noone can "close a
topic". (It's alright for them to add this extra limitation, of course.)

> The question is how can I add this correction?

In Usenet terms, make a posting with a References: header which mentions the
Message-ID of the bad posting (just like this posting references yours, if
you look closely at the headers).  That's easier if the posting hasn't
already expired on your server, but by no means impossible if it has.

/Jorgen

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


Re: How to coerce a list of vars into a new type?

2006-10-02 Thread bearophileHUGS
Matthew Wilson wrote:
> I want to verify that three parameters can all be converted into
> integers, but I don't want to modify the parameters themselves.

To do what you need you can try this:

def f(a, b, c):
map(int, [a, b, c])
...code...

Bye,
bearophile

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


Re: How can I correct an error in an old post?

2006-10-02 Thread Steve Holden
Jorgen Grahn wrote:
> On 1 Oct 2006 10:18:59 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
> 
>>and I wish to add my findings to the post, to prevent others from
>>taking the wrong path.
> 
> 
>>When I tried to replay to the post I received a reject message stating
>>that it is impossible to replay to the topic since it is old and was
>>closed by a manager.
> 
> 
> That's through the Google Groups Usenet interface, right? Because on Usenet,
> that's misleading at best -- we have no managers, and noone can "close a
> topic". (It's alright for them to add this extra limitation, of course.)
> 
> 
>>The question is how can I add this correction?
> 
> 
> In Usenet terms, make a posting with a References: header which mentions the
> Message-ID of the bad posting (just like this posting references yours, if
> you look closely at the headers).  That's easier if the posting hasn't
> already expired on your server, but by no means impossible if it has.
> 
> /Jorgen
> 
Since this message was never on topic, I'd appreciate it if all 
concerned would close this thread now.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Hari Sekhon




I don't quite understand what you are saying here:

2 * 256 is 512,
2 ** 256 is some extremely large number.

2**12 is 4096.

So how does 3072 factor into this?

Could you explain what you mean by "the error in the top half of a
sixteen-bit value"?

This makes no sense to me at this moment.

-h

Hari Sekhon


Steve Holden wrote:

  Hari Sekhon wrote:
  
  
I'm running a command like

import commands
result = commands.getstatusoutput('somecommand')
print result[0]
3072


However, this exit code made no sense so I ran it manually from the 
command line in bash on my linux server and it gives the exit code as 
12, not this weird 3072 number.

So I tried os.system('somecommand') in the interactive python shell and 
it too returned the same result for the exit code as the unix shell, 12, 
but re-running the commands.getstatusoutput() with the exact same 
command still gave 3072.


Is commands.getstatusoutput() broken or something?


-h


  
  No, it's just returning the error code in the top half of a sixteen-bit 
value. You will notice that 3072 == 2 * 256.

That's always been the way the Unix return code has been returned 
programattically, but the shell shifts it down to make it more usab;e.

regards
  Steve
  



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

Re: Sort by domain name?

2006-10-02 Thread Tim Chase
>> Here, domain name doesn't contain subdomain, or should I
>> say, domain's part of 'www', mail, news and en should be 
>> excluded.
> 
> It's a little more complicated, you have to treat co.uk about
>  the same way as .com, and similarly for some other countries 
> but not all.  For example, subdomain.companyname.de versus 
> subdomain.companyname.com.au or subdomain.companyname.co.uk. 
> You end up needing a table or special code to say how to treat
> various countries.

In addition, you get very different results even on just "base"
domain-name, such as "whitehouse" based on whether you use the
".gov" or ".com" variant of the TLD. Thus, I'm not sure there's
any way to discern this example from the "yahoo.com" vs.
"yahoo.co.uk" variant without doing a boatload of WHOIS queries,
which in turn might be misleading anyways.

A first-pass solution might look something like:

##>>> 
sites
['http://mail.google.com', 'http://reader.google.com', 
'http://mail.yahoo.co.uk', 'http://google.com', 
'http://mail.yahoo.com']
 >>> sitebits = [site.lower().lstrip('http://').split('.') for 
site in sites]
 >>> for site in sitebits: site.reverse()
...
 >>> sorted(sitebits)
[['com', 'google'], ['com', 'google', 'mail'], ['com', 'google', 
'reader'], ['co
m', 'yahoo', 'mail'], ['uk', 'co', 'yahoo', 'mail']]
 >>> results = ['http://' + ('.'.join(reversed(site))) for site 
in sorted(sitebits)]
 >>> results
['http://google.com', 'http://mail.google.com', 
'http://reader.google.com', 'http://mail.yahoo.com', 
'http://mail.yahoo.co.uk']
##

which can be wrapped up like this:

##
 >>> def sort_by_domain(sites):
... sitebits = [site.lower().lstrip('http://').split('.') for 
site in sites]
... for site in sitebits: site.reverse()
... return ['http://' + ('.'.join(reversed(site))) for site 
in sorted(sitebits)]
...
 >>> s = sites
 >>> sort_by_domain(sites)
['http://google.com', 'http://mail.google.com', 
'http://reader.google.com', 'http://mail.yahoo.com', 
'http://mail.yahoo.co.uk']
##

to give you a sorting function.  It assumes http rather than 
having mixed url-types, such as ftp or mailto.  They're easy 
enough to strip off as well, but putting them back on becomes a 
little more exercise.

Just a few ideas,

-tkc




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


Re: *** Spam *** Re: commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Steve Holden
A famous Holden typo - it should have been "12 * 256 == 3072", but 
really it shouldn't have been beyond you to perform a division of 3072 
by 12 (given that you already knew the number 12 was potentially involved).

Basically the value you want is shifted up 8 bits. Perhaps I should more 
understandably have said:

   12 << 8 == 3072

regards
  Steve

Hari Sekhon wrote:
> I don't quite understand what you are saying here:
> 
> 2 * 256 is 512,
> 2 ** 256 is some extremely large number.
> 
> 2**12 is 4096.
> 
> So how does 3072 factor into this?
> 
> Could you explain what you mean by "the error in the top half of a 
> sixteen-bit value"?
> 
> This makes no sense to me at this moment.
> 
> -h
> 
> Hari Sekhon
> 
> 
> 
> Steve Holden wrote:
> 
>>Hari Sekhon wrote:
>>  
>>
>>>I'm running a command like
>>>
>>>import commands
>>>result = commands.getstatusoutput('somecommand')
>>>print result[0]
>>>3072
>>>
>>>
>>>However, this exit code made no sense so I ran it manually from the 
>>>command line in bash on my linux server and it gives the exit code as 
>>>12, not this weird 3072 number.
>>>
>>>So I tried os.system('somecommand') in the interactive python shell and 
>>>it too returned the same result for the exit code as the unix shell, 12, 
>>>but re-running the commands.getstatusoutput() with the exact same 
>>>command still gave 3072.
>>>
>>>
>>>Is commands.getstatusoutput() broken or something?
>>>
>>>
>>>-h
>>>
>>>
>>>
>>No, it's just returning the error code in the top half of a sixteen-bit 
>>value. You will notice that 3072 == 2 * 256.
>>
>>That's always been the way the Unix return code has been returned 
>>programattically, but the shell shifts it down to make it more usab;e.
>>
>>regards
>>  Steve
>>  
>>


-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
-- 
http://mail.python.org/mailman/listinfo/python-list


postgresql database

2006-10-02 Thread Paolo
Ciao a tutti, sto cercando di implementare un applicazione che si
interfaccia con postgresql(8.1), utilizzando Psycopg2, in ambiente
windows (python versione 2.5). Ho installato Psycopg2 e provando
solamente fare: import psycopg mi ritorna il seguente errore:

import psycopg
ImportError: No module named psycopg

come mai? va settata qualche path oltre a quella di postgresql ?

grazie dell'aiuto

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


Re: Sort by domain name?

2006-10-02 Thread js
Thanks for your quick reply.
yeah, it's a hard task and unfortunately even google doesn't help me much.

All I want to do is to sort out a list of url by companyname,
like oreilly, ask, skype, amazon, google and so on, to find out
how many company's url the list contain.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort by domain name?

2006-10-02 Thread gene tani

Paul Rubin wrote:
> "js " <[EMAIL PROTECTED]> writes:
> > Here, domain name doesn't contain subdomain,
> > or should I say, domain's part of 'www', mail, news and en should be
> > excluded.
>
> It's a little more complicated, you have to treat co.uk about
> the same way as .com, and similarly for some other countries
> but not all.  For example, subdomain.companyname.de versus
> subdomain.companyname.com.au or subdomain.companyname.co.uk.
> You end up needing a table or special code to say
> how to treat various countries.

Plus, how do you order "https:", "ftp", URLs with "www.", "www2." ,
named anchors etc?

Gentle reminder: is this homework?  And you can expect better responses
if you show youve bootstrapped yourself on the problem to some extent.

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


Re: Making posts to an ASP.NET webform.

2006-10-02 Thread Max M
Bernard skrev:

> Has anyone tried what I'm doing? and if you tried how have you
> succeeded getting the data back after the post action?

Most likely you get assigned a cookie that you then need to return.

Try the cookielib which automates all this for you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Multiplayer 2-D space action shooter in Python (using wxWindows)

2006-10-02 Thread [EMAIL PROTECTED]
Hi guys,

Well, here is my humble contribution to the community:

http://sourceforge.net/projects/erocket

I started that project to learn Python and wxWindows.
By all means, I am no Python Guru, but maybe someone could find
something useful.
Also please consider that it is under development and is far from being
finished.

Best regards,
Andrei

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


Re: Sort by domain name?

2006-10-02 Thread bearophileHUGS
Tim Chase:
> to give you a sorting function.  It assumes http rather than
> having mixed url-types, such as ftp or mailto.  They're easy
> enough to strip off as well, but putting them back on becomes a
> little more exercise.

With a modern Python you don't need to do all that work, you can do:

sorted(urls, key=cleaner)

Where cleaner is a function the finds the important part of a string of
the ones you have to sort.

Bye,
bearophile

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


Re: commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Hari Sekhon
I'm sorry, this may seem dense to you but I have to ask. What on earth 
are you talking about?

Why is it shifted 8 bits to the left? Why is there bitshifting at all? 
Why doesn't commands give the same exit value as os.system() and the 
unix cli?

When you choose to exit a program you give it a return value to exit 
with, so why would this change, I exit with the number 1 then expect 
that number to be the exit code, right? Where do these higher numbers 
come into the equation and why?

Please assume that I am not a mind reader and require explanation before 
I can understand.

Perhaps you aren't a mind reader either and don't know why the writers 
of the commands lib chose to do this insanity either? It seems the 
os.system() guys did the right thing, I wonder why 
commands.getstatusoutput doesn't...

Having just tested it manually with a shell script returning 2, 
commands.getstatusoutput did give the exit code as 512, so it does seem 
to generically shift the exit code 8 bits to the left or multiply it by 
256 for those of us who need some more straight talking...

ugg, perhaps it's time to stop using this thing and use a better lib module.

any explanations welcome...

-h

Hari Sekhon



Steve Holden wrote:
> A famous Holden typo - it should have been "12 * 256 == 3072", but 
> really it shouldn't have been beyond you to perform a division of 3072 
> by 12 (given that you already knew the number 12 was potentially 
> involved).
>
> Basically the value you want is shifted up 8 bits. Perhaps I should 
> more understandably have said:
>
>   12 << 8 == 3072
>
> regards
>  Steve
>
> Hari Sekhon wrote:
>> I don't quite understand what you are saying here:
>>
>> 2 * 256 is 512,
>> 2 ** 256 is some extremely large number.
>>
>> 2**12 is 4096.
>>
>> So how does 3072 factor into this?
>>
>> Could you explain what you mean by "the error in the top half of a 
>> sixteen-bit value"?
>>
>> This makes no sense to me at this moment.
>>
>> -h
>>
>> Hari Sekhon
>>
>>
>>
>> Steve Holden wrote:
>>
>>> Hari Sekhon wrote:
>>>  
>>>
 I'm running a command like

 import commands
 result = commands.getstatusoutput('somecommand')
 print result[0]
 3072


 However, this exit code made no sense so I ran it manually from the 
 command line in bash on my linux server and it gives the exit code 
 as 12, not this weird 3072 number.

 So I tried os.system('somecommand') in the interactive python shell 
 and it too returned the same result for the exit code as the unix 
 shell, 12, but re-running the commands.getstatusoutput() with the 
 exact same command still gave 3072.


 Is commands.getstatusoutput() broken or something?


 -h

   
>>> No, it's just returning the error code in the top half of a 
>>> sixteen-bit value. You will notice that 3072 == 2 * 256.
>>>
>>> That's always been the way the Unix return code has been returned 
>>> programattically, but the shell shifts it down to make it more usab;e.
>>>
>>> regards
>>>  Steve
>>>  
>>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort by domain name?

2006-10-02 Thread bearophileHUGS
js:
> All I want to do is to sort out a list of url by companyname,
> like oreilly, ask, skype, amazon, google and so on, to find out
> how many company's url the list contain.

Then if you can define a good enough list of such company names, you
can just do a search of such names inside each url.
Maybe you can use string method, or a RE, or create a big string with
all the company names and perform a longest common subsequence search
using the stdlib function. 

Bye,
bearophile

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


Re: Sort by domain name?

2006-10-02 Thread jay graves

gene tani wrote:
> Plus, how do you order "https:", "ftp", URLs with "www.", "www2." ,
> named anchors etc?

Now is a good time to point out the urlparse module in the standard
library.  It will help the OP with all of this stuff.

just adding my 2 cents.

...
jay graves

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


Re: Making posts to an ASP.NET webform.

2006-10-02 Thread Bernard

Max M wrote:
> Bernard skrev:
>
> > Has anyone tried what I'm doing? and if you tried how have you
> > succeeded getting the data back after the post action?
>
> Most likely you get assigned a cookie that you then need to return.
>
> Try the cookielib which automates all this for you.

Yea I'm already using it. I set the cookies before making the server
request. its name is ASP.NET_SessionId.

I've tried setting it on & off during my various tests but I still get
the "urllib2.HTTPError: HTTP Error 500: Internal Server Error" message.

thanks for the response by the way :)

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


Re: Sort by domain name?

2006-10-02 Thread Paul Rubin
"js " <[EMAIL PROTECTED]> writes:
> All I want to do is to sort out a list of url by companyname,
> like oreilly, ask, skype, amazon, google and so on, to find out
> how many company's url the list contain.

Here's a function I used to use.  It makes no attempt to be
exhaustive, but did a reasonable job on the domains I cared about at
the time:

def host_domain(hostname):
parts = hostname.split('.')
if parts[-1] in ('au','uk','nz', 'za', 'jp', 'br'):
# www.foobar.co.uk, etc
host_len = 3
elif len(parts)==4 and re.match('^[\d.]+$', hostname):
host_len = 4# 2.3.4.5 numeric address
else:
host_len = 2
d = '.'.join(parts[-(host_len):])
#   print 'host_domain:', hostname, '=>', d
return d
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: postgresql database

2006-10-02 Thread Michele Simionato

Paolo wrote:
> Ciao a tutti, sto cercando di implementare un applicazione che si
> interfaccia con postgresql(8.1), utilizzando Psycopg2, in ambiente
> windows (python versione 2.5). Ho installato Psycopg2 e provando
> solamente fare: import psycopg mi ritorna il seguente errore:
>
> import psycopg
> ImportError: No module named psycopg
>
> come mai? va settata qualche path oltre a quella di postgresql ?
>
> grazie dell'aiuto

Well, if you are using Psycopg2, do

import psycopg2

(and please use the italian mailing list for questions in Italian).

 Michele Simionato

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


Re: Sort by domain name?

2006-10-02 Thread Paul McGuire
"js " <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi list,
>
> I have a list of URL and I want to sort that list by the domain name.
>
> Here, domain name doesn't contain subdomain,
> or should I say, domain's part of 'www', mail, news and en should be 
> excluded.
>
> For example, if the list was the following
> 
> http://mail.google.com
> http://reader.google.com
> http://mail.yahoo.co.uk
> http://google.com
> http://mail.yahoo.com
> 
>
> the sort's output would be
> 
> http://google.com
> http://mail.google.com
> http://reader.google.com
> http://mail.yahoo.co.uk
> http://mail.yahoo.com
> 
>
> As you can see above, I don't want to
>
>
> Thanks in advance.

How about sorting the strings as they are reversed?

urls = """\
http://mail.google.com
http://reader.google.com
http://mail.yahoo.co.uk
http://google.com
http://mail.yahoo.com""".split("\n")

sortedList = [ su[1] for su in sorted([ (u[::-1],u) for u in urls ]) ]

for url in sortedList:
print url


Prints:
http://mail.yahoo.co.uk
http://mail.google.com
http://reader.google.com
http://google.com
http://mail.yahoo.com


Close to what you are looking for, might be good enough?

-- Paul 


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


Re: Sort by domain name?

2006-10-02 Thread js
> Gentle reminder: is this homework?  And you can expect better responses
> if you show youve bootstrapped yourself on the problem to some extent.

Sure thing.
First I tried to solve this by using a list of domain found at
http://www.neuhaus.com/domaincheck/domain_list.htm

I converted this to a list (in python) and tried like below

look for url that endswith(domain in domains)
if found:
  capture the left side of the domain part(tld) and
  save all url to a dictionary that key is the captured string

to me this seems to work but stuck because this solution seems no good.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort by domain name?

2006-10-02 Thread js
On 2 Oct 2006 08:56:09 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> js:
> > All I want to do is to sort out a list of url by companyname,
> > like oreilly, ask, skype, amazon, google and so on, to find out
> > how many company's url the list contain.
>
> Then if you can define a good enough list of such company names, you
> can just do a search of such names inside each url.
> Maybe you can use string method, or a RE, or create a big string with
> all the company names and perform a longest common subsequence search
> using the stdlib function.

well, I think list is so large that that's impossible to
create such a good company-list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python threads and Numeric/SciPy exploit Dual Core ?

2006-10-02 Thread robert
Fredrik Lundh wrote:

> "robert" wrote:
> 
> 
>>Simple Python code obviously cannot use the dual core by Python threads.
>>Yet, a program drawing CPU mainly for matrix computations - preferably
>>with Numeric/SciPy -  will this profit from a dual core when using 2 (or
>>more) Python threads?
> 
> 
> as long as the binding releases the GIL, sure.

Thus - does Numeric/SciPy release it?
The same q about the orange (data mining) lib.

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


tkinter to mpeg

2006-10-02 Thread dug
Hi,

I have a small program that moves some shapes around a tkinter canvas.
Is there any way to save the output in a movie file, maybe mpeg?

Thank you,

Douglas

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


Re: Gadfly server startup error

2006-10-02 Thread aaronwmail-usenet

[EMAIL PROTECTED] wrote:
> > Is anybody out there who has used the server+client operation
> > mode successfully?
>
> Well, several years ago, yes.

I looked into it and it was mainly a documentation and
test issue, I think.  The code seems to work.

Please go

  http://gadfly.sourceforge.net/gadfly_server_test.zip

and look at the readme.  I will try to fold this in to the
distribution sometime soon.

from the README in the zip:

==
gadfly_server_test readme

This directory provides a proof of concept test run of the
gadfly server components. It requires gadfly to be installed
in the local python installation ( http://gadfly.sourceforge.net ).

Please see the doc string at the top of gfstest.py for details.

Example demo run sequence (in Windows installations the "python" prefix
is optional):

1. Set up the database.
 % python gftest.py dbtest

2. Start the server
 % python gfstest.py start

   This starts an infinite server loop in the current console.

3. SWITCH TO ANOTHER WINDOW and run test queries.
 % python gfstest.py queries

4. Shut down the server.
 % python gfstest.py shutdown
=

   -- Aaron Watters

===
There once was a man who said "Well!
Will nobody answer this bell?
I have pulled day and night
'til my hair has grown white
but nobody answers this bell!"
  -- Edward Lear

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


Re: Sort by domain name?

2006-10-02 Thread js
> How about sorting the strings as they are reversed?
>
> urls = """\
> http://mail.google.com
> http://reader.google.com
> http://mail.yahoo.co.uk
> http://google.com
> http://mail.yahoo.com""".split("\n")
>
> sortedList = [ su[1] for su in sorted([ (u[::-1],u) for u in urls ]) ]
>
> for url in sortedList:
> print url
>

>
> Close to what you are looking for, might be good enough?

Great... I couldn't thought that way. Thanks a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Fredrik Lundh
Hari Sekhon wrote:

> I'm sorry, this may seem dense to you but I have to ask. What on earth 
> are you talking about?
 >
> Why is it shifted 8 bits to the left? Why is there bitshifting at all? 
> Why doesn't commands give the same exit value as os.system() and the 
> unix cli?

because that's how Unix's wait() operation returns the status code (as 
mentioned in the "commands" section of the library reference).

you can use the os.WIFEXITED(status) and os.WEXITSTATUS(code) helpers to 
convert between wait return codes and signal numbers/exit codes.  see:

 http://docs.python.org/lib/os-process.html

or you can forget about the obsolete "commands" module, and use the new 
subprocess module instead; e.g.

def getstatusoutput(command):
 from subprocess import Popen, PIPE, STDOUT
 p = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True)
 s = p.stdout.read()
 return p.wait(), s

print getstatusoutput("ls -l /bin/ls")
(0, '-rwxr-xr-x1 root root68660 Aug 12  2003 /bin/ls\n')

the subprocess module is highly flexible; see the library reference for 
details.



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


Re: tkinter to mpeg

2006-10-02 Thread Thomas Jollans
On Mon, 02 Oct 2006 09:18:13 -0700, "dug" <[EMAIL PROTECTED]> let this
slip:

> Hi,
> 
> I have a small program that moves some shapes around a tkinter canvas.
> Is there any way to save the output in a movie file, maybe mpeg?

you can record any app with special programs designed for the job, such as
vnc2swf (which produces macromedia flash), vncrec (which produces a
special format readable by transcode) or istanbul (which produces
ogg/theora). I doubt Tk would have a special mechanism to do this.

-- 
Thomas Jollans alias free-zombie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Martin v. Löwis
Hari Sekhon schrieb:
> I'm sorry, this may seem dense to you but I have to ask. What on earth
> are you talking about?

You may not be dense, but you are certainly fairly aggressive in your
postings. If you just want to complain, go ahead. If you want actual
help, you should reconsider your tone.

> Why is it shifted 8 bits to the left?

As Steve says, that what the system returns (from popen(3)), in this
case. It's the true exit status, not just the exit code.

> Why is there bitshifting at all?

Read some Unix book.

> Why doesn't commands give the same exit value as os.system() and the
> unix cli?

Read some Unix book.

> When you choose to exit a program you give it a return value to exit
> with, so why would this change, I exit with the number 1 then expect
> that number to be the exit code, right?

Read some Unix book. Hint: how do you know whether the program was
killed, and didn't actually invoke exit(3)?

> Where do these higher numbers
> come into the equation and why?

Read some Unix book. Hint: Read about WIFEXITED, WIFSIGNALED, and
WEXITSTATUS.

> Please assume that I am not a mind reader and require explanation before
> I can understand.

You are apparently not a documentation reader, as well. Nobody owes you
an explanation.

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


Re: commands.getstatusoutput result is not command line exit value!!!

2006-10-02 Thread Hari Sekhon




ok, I was thinking of shifting using subprocess, guess I'd better do
that and forget about this waste of time.

thanks

Hari Sekhon


Fredrik Lundh wrote:

  Hari Sekhon wrote:

  
  
I'm sorry, this may seem dense to you but I have to ask. What on earth 
are you talking about?

  
   >
  
  
Why is it shifted 8 bits to the left? Why is there bitshifting at all? 
Why doesn't commands give the same exit value as os.system() and the 
unix cli?

  
  
because that's how Unix's wait() operation returns the status code (as 
mentioned in the "commands" section of the library reference).

you can use the os.WIFEXITED(status) and os.WEXITSTATUS(code) helpers to 
convert between wait return codes and signal numbers/exit codes.  see:

 http://docs.python.org/lib/os-process.html

or you can forget about the obsolete "commands" module, and use the new 
subprocess module instead; e.g.

def getstatusoutput(command):
 from subprocess import Popen, PIPE, STDOUT
 p = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True)
 s = p.stdout.read()
 return p.wait(), s

print getstatusoutput("ls -l /bin/ls")
(0, '-rwxr-xr-x1 root root68660 Aug 12  2003 /bin/ls\n')

the subprocess module is highly flexible; see the library reference for 
details.



  



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

Pythonic API design: detailed errors when you usually don't care

2006-10-02 Thread Simon Willison
Hi all,

I have an API design question. I'm writing a function that can either
succeed or fail. Most of the time the code calling the function won't
care about the reason for the failure, but very occasionally it will.

I can see a number of ways of doing this, but none of them feel
aesthetically pleasing:

1.

try:
  do_something()
except HttpError:
  # An HTTP error occurred
except ApplicationError:
  # An application error occurred
else:
  # It worked!

This does the job fine, but has a couple of problems. The first is that
I anticipate that most people using my function won't care about the
reason; they'll just want a True or False answer. Their ideal API would
look like this:

if do_something():
  # It succeeded
else:
  # It failed

The second is that the common path is success, which is hidden away in
the 'else' clause. This seems unintuitive.

2.

Put the method on an object, which stores the reason for a failure:

if obj.do_something():
  # It succeeded
else:
  # It failed; obj.get_error_reason() can be called if you want to know
why

This has an API that is closer to my ideal True/False, but requires me
to maintain error state inside an object. I'd rather not keep extra
state around if I don't absolutely have to.

3.

error = do_something()
if error:
  # It failed
else:
  # It succeeded

This is nice and simple but suffers from cognitive dissonance in that
the function returns True (or an object evaluating to True) for
failure.

4.

The preferred approach works like this:

if do_something():
  # Succeeded
else:
  # Failed

BUT this works too...

ok = do_something()
if ok:
  # Succeeded
else:
  # ok.reason has extra information
  reason = ok.reason

This can be implemented by returning an object from do_something() that
has a __nonzero__ method that makes it evaluate to False. This solves
my problem almost perfectly, but has the disadvantage that it operates
counter to developer expectations (normally an object that evaluates to
False is 'empty').

I know I should probably just pick one of the above and run with it,
but I thought I'd ask here to see if I've missed a more elegant
solution.

Thanks,

Simon

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


Re: Python/UNO/OpenOffice?

2006-10-02 Thread Sybren Stuvel
John Machin enlightened us with:
> Many thanks for all that, olive; I made the minimal hacks to make it
> open an XLS ffile, and it worked!
> I'll try to see why that worked and my previous experiment crashed
> inside a DLL.

Thanks, keep us posted!

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making sure script only runs once instance at a time.

2006-10-02 Thread Fredrik Lundh
Hari Sekhon wrote:

> How exactly do you check that the pid is still active in python? Is 
> there a library or something that will allow me to manipulate system 
> processes and listings etc the way everybody does in unix shells

by passing zero to the os.kill primitive:

os.kill(pid, 0)

if this raises an OSError, there's no active process with the given pid.

> I'm a huge fan of shell so I've done my own thing which leans on shell 
> as follows:
> 
> import sys,commands,os
> 
> scriptpath = sys.argv[0]
> scriptname = os.path.basename(scriptpath)
> 
> number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc 
> -l' % scriptpath)
> 
> if number_procs > 1:
> print "There appears to be another %s process running." % scriptname

what if you have commands with overlapping names (e.g. "bar.py" and 
"foobar.py"), or some other user on the machine happens to run a
command that, on purpose or by accident, contains your script's name 
(e.g. "emacs mybar.py") ?



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


Re: Python threads and Numeric/SciPy exploit Dual Core ?

2006-10-02 Thread Robert Kern
robert wrote:
> Fredrik Lundh wrote:
> 
>> "robert" wrote:
>>
>>> Simple Python code obviously cannot use the dual core by Python threads.
>>> Yet, a program drawing CPU mainly for matrix computations - preferably
>>> with Numeric/SciPy -  will this profit from a dual core when using 2 (or
>>> more) Python threads?
>>
>> as long as the binding releases the GIL, sure.
> 
> Thus - does Numeric/SciPy release it?

Depends. Some of the linear algebra functions in scipy do. Most operations do 
not. People are looking at adding more.

-- 
Robert Kern

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

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


Re: How can I correct an error in an old post?

2006-10-02 Thread Blair P. Houghton

Steve Holden wrote:
> Since this message was never on topic, I'd appreciate it if all
> concerned would close this thread now.

I already did.  How did you get in here?

--Blair

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


  1   2   >