Re: argument to python cgi script

2008-04-10 Thread Gabriel Genellina
En Wed, 09 Apr 2008 11:14:33 -0300, syed mehdi <[EMAIL PROTECTED]>  
escribió:

> Hi Guys,
> If someone can help me in telling how can i pass arguments to python cgi
> script then that will be good.
> like if i want to pass "some argument" to my remote python script, by
> calling something like:
> http://localhost/cgi-bin/test.py?some\ argument.
> What is the correct way of sending arguments in this way, and how can i
> decode/receive them in test.py

Encoding:

py> args = {'some': 'argument', 'x': 1, 'z': 23.4}
py> import urllib
py> urllib.urlencode(args)
'x=1&z=23.4&some=argument'

You can then use urllib.urlopen or urllib2.urlopen to send the HTTP  
request and retrieve the response.
http://docs.python.org/lib/module-urllib.html

In the server side, use cgi.FieldStorage:

form = cgi.FieldStorage()
x = form.getfirst('x', 0) # '1'
y = form.getfirst('y', 0) # '0'
z = form.getfirst('z', 0) # '23.4'

http://docs.python.org/lib/module-cgi.html

-- 
Gabriel Genellina

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


Re: wrapping C functions in python

2008-04-10 Thread Diez B. Roggisch
Paul Anton Letnes schrieb:
> Brian and Diez:
> 
> First of all, thanks for the advice.
> 
> Brian:
> 
> I have installed NumPy and SciPy, but I can't seem to find a wavelet 
> transform there.
> 
> The main point of this was more to learn C wrapping than to actually get 
> a calculation done. I will probably be starting a PhD soon, doing really 
> heavy computations. If I want to manipulate data (input / results), 
> python is very nice, especially with gnuplot-py. However, heavy 
> calculations should probably be done in C(++), especially as some code 
> for this already exists.
> 
> I will look into SWIG.
> 
> 
> Diez:
> 
> I will look into it. Do you know a good tutorial for this? I found the 
> "standard" tutorial on C extensions, 
> http://www.python.org/doc/ext/intro.html , but as I mentioned, it seems 
> to be a bit complicated to wrap heavy data structures like arrays.

ctypes is documented as part of the python 2.5 standard lib 
documentation. And google helps as always.

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


SWIG/C++

2008-04-10 Thread Bill Davy
Is there a better place to post such questions?

Anyway, in the hope it is something simple, I would appreciate some help.

I am adding some C++ code to Python.  From Python I want to be able to read 
data from a target device, over USB.  My software does all the hard work and 
I have a class:

class ViperUsbC
{
public:
// snip snip
ERROR_T ReadSlaveMemory(u8 Slave, u16 Offset, u8* pData, u16 
Length);
// Snip,snip
};

I use swigwin-1.3.34 to wrap it into a module called SHIP.

In Python, I have:

import SHIP
ViperUsb = SHIP.ViperUsbC()
Slave =7
Offset = 0
Length = 64
Buffer = 'a' * Length
print "type(Buffer)=%s" % type(Buffer)
print "len(Buffer)=%s" % len(Buffer)
Result = ViperUsb.ReadSlaveMemory(Slave, Offset, Buffer, Length);

That fails with:

type(Buffer)=
len(Buffer)=64

Traceback (most recent call last):
  File "H:\Husky\HostPC\V1\SHIP\test1.py", line 1970, in -toplevel-
ViperTests()
  File "H:\Husky\HostPC\V1\SHIP\test1.py", line 1884, in ViperTests
Result = ViperUsb.ReadSlaveMemory(Slave, Offset, Buffer, Length);
  File "H:\Husky\HostPC\V1\SHIP\Release\SHIP.py", line 1757, in 
ReadSlaveMemory
def ReadSlaveMemory(*args): return 
_SHIP.ViperUsbC_ReadSlaveMemory(*args)
TypeError: in method 'ViperUsbC_ReadSlaveMemory', argument 4 of type 'u8 *'


How do I provide a buffer into which to read the data?  It would not be 
intolerable to provide another layer using %extend, but I feel sure this 
should be automagic.

Thanks in advance
Bill

PS This is a very small part of a much larger project so I cannot supply 
complete source code. 


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


Re: new user needs help!

2008-04-10 Thread Chris
On Apr 9, 11:02 pm, drjekil <[EMAIL PROTECTED]> wrote:
> I have done something so far about that problem,but its not the good way to
> do it
>
> need ur comments about that
>
> from string import  *;
> import sys
>
> myfile = open("/afs/pdc.kth.se/home/d/debnath/membrane/1a91A.txt")
> a = myfile.readlines()
> data = myfile.readlines()
> for line in myfile.readlines():
>        fields = line.split('\t')
>
>        items=fields.strip()
>        list1.append(items[1])
>
> for i in aminoacid:
>     if  10.0 <= z <= 22.0:
>     matches.append([1,i])
> #here i am getting comment!  bash-3.1$ python bb.py
>   File "bb.py", line 16
>     matches.append([1,i])
>           ^
> IndentationError: expected an indented block
>
>     else:
>     matches.append([-1,i])
>

You are getting the indentation error because you need to tab the
lines in after your 'if' and 'else' statements.  After that is fixed
you should get an Attribute Error on the 'items=fields.strip()' as a
list doesn't have access to strip.

import string
myfile = open("/afs/pdc.kth.se/home/d/debnath/membrane/1a91A.txt",
'rb')

AMINO_ACIDS = ['A','B','C',..'X','Y','Z']

for line in myfile:   # Files are iterable themselves.

try:
fields = map(string.strip, line.split('\t'))  # This will
strip every column for you
name, aa, topo, access, tssp, stride, z = fields
except IndexError:# In case you don't have enough elements
print 'Not enough elements on the line, moving along'

if 10 <= z <= 22:   # You only wanted between those Z-Coords ?
if aa in AMINO_ACIDS:
# Now actually process the data you want


> print "#T/F  A  C  D  E  F  G  H  I  K  L  M  N  P  Q  R  S  T  V  W  X  Y
> Z"
>
> for a in range(0,len(matches),1):
>
>     if     matches[a][0]==1:
>
>     if matches[a][1]=='A':
>         print "1  1:1 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0
> 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     elif matches[a][1]=='C':
>         print "1  1:0 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0
> 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     elif matches[a][1]=='D':
>
>         print "    1  1:0 2:0 3:1 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> """    if matches[a][1]=='E' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:1 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='F' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:1 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='G' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:1 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='H' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='I' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:1 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='K' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:1 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='L' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:1 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='M' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:1 12:0
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='N' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:1
> 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='P' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:1 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='Q' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:1 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='R' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:1 16:0 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='S' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:1 17:0 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='T' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:1 18:0 19:0 20:0 21:0"
>     if matches[a][1]=='V' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> 13:0 14:0 15:0 16:0 17:0 18:1 19:0 20:0 21:0"
>     if matches[a][1]=='X' and matches[a][0]==1:
>
>         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:

questions about Exceptions?

2008-04-10 Thread skanemupp
is there a general philosophy as to when to use exceptions and when
not to?

like here:
def Calc():
global nbr
try:
print eval(nbr)
except:
print "Not computable"
nbr = ""

i have a calculator and nbr is a string that contains '0123456789+-*/'

if the string ends on +-*/ it will throw an exception(unexpected EOF).

i could easily prevent the exceptions here with an if-statement, is
that preferrable and why?


also when u throw exceptions should u catch the speicfic one? i guess
only if u want it to do soemthing special since  catching only only
one exception logicall would abort the program if another one is
thrown?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new user needs help!

2008-04-10 Thread Chris
On Apr 10, 10:07 am, Chris <[EMAIL PROTECTED]> wrote:
> On Apr 9, 11:02 pm, drjekil <[EMAIL PROTECTED]> wrote:
>
>
>
> > I have done something so far about that problem,but its not the good way to
> > do it
>
> > need ur comments about that
>
> > from string import  *;
> > import sys
>
> > myfile = open("/afs/pdc.kth.se/home/d/debnath/membrane/1a91A.txt")
> > a = myfile.readlines()
> > data = myfile.readlines()
> > for line in myfile.readlines():
> >        fields = line.split('\t')
>
> >        items=fields.strip()
> >        list1.append(items[1])
>
> > for i in aminoacid:
> >     if  10.0 <= z <= 22.0:
> >     matches.append([1,i])
> > #here i am getting comment!  bash-3.1$ python bb.py
> >   File "bb.py", line 16
> >     matches.append([1,i])
> >           ^
> > IndentationError: expected an indented block
>
> >     else:
> >     matches.append([-1,i])
>
> You are getting the indentation error because you need to tab the
> lines in after your 'if' and 'else' statements.  After that is fixed
> you should get an Attribute Error on the 'items=fields.strip()' as a
> list doesn't have access to strip.
>
> import string
> myfile = open("/afs/pdc.kth.se/home/d/debnath/membrane/1a91A.txt",
> 'rb')
>
> AMINO_ACIDS = ['A','B','C',..'X','Y','Z']
>
> for line in myfile:   # Files are iterable themselves.
>
>     try:
>         fields = map(string.strip, line.split('\t'))  # This will
> strip every column for you
>         name, aa, topo, access, tssp, stride, z = fields
>     except IndexError:    # In case you don't have enough elements
>         print 'Not enough elements on the line, moving along'
>
>     if 10 <= z <= 22:   # You only wanted between those Z-Coords ?
>         if aa in AMINO_ACIDS:
>             # Now actually process the data you want
>
>
>
> > print "#T/F  A  C  D  E  F  G  H  I  K  L  M  N  P  Q  R  S  T  V  W  X  Y
> > Z"
>
> > for a in range(0,len(matches),1):
>
> >     if     matches[a][0]==1:
>
> >     if matches[a][1]=='A':
> >         print "1  1:1 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0
> > 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     elif matches[a][1]=='C':
> >         print "1  1:0 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0
> > 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     elif matches[a][1]=='D':
>
> >         print "    1  1:0 2:0 3:1 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> > """    if matches[a][1]=='E' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:1 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='F' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:1 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='G' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:1 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='H' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='I' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:1 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='K' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:1 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='L' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:1 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='M' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:1 12:0
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='N' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:1
> > 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='P' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:1 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='Q' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:1 15:0 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='R' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:1 16:0 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='S' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:1 17:0 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='T' and matches[a][0]==1:
>
> >         print "    1  1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0
> > 13:0 14:0 15:0 16:0 17:1 18:0 19:0 20:0 21:0"
> >     if matches[a][1]=='V' and m

Re: How to find documentation about methods etc. for iterators

2008-04-10 Thread tinnews
Terry Reedy <[EMAIL PROTECTED]> wrote:
> 
> <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> | I'm not sure if I have even phrased that right but anyway
> |
> | How does one find (in the standard Python documentation) information
> | about things like the iteritems() method and the enumerate() function.
> 
> The Library Reference manual sections on builtin functions and dict 
> methods.
> 
> Or, help(enumerate) and help({}.iteritems)
> 
 but that doesn't address my problem really, how do I know that I
need to look for the words enumerate and/or iteritems?  This is what
my original question was about.

There I was thinking that there has to be an easy way to get line
numbers as I read lines from a file but not knowing how to find out
how to do it:-

First question, what sort of 'thing' is the file object, I need to
know that if I'm to look up ways of using it.

Second question, even if I know what sort of thing a file object
is, how do I find methods applicable to it and/or functions
applicable to it?

The possibility that I might want either a method or a function adds
to the fun.  In my original query it seemed odd that some objects have
the iteritems *method* whereas other objects have the enumerate
*function*.

It's a common problem in all sorts of computer fields, if you know the
name of what you want it's easy to find out details of how to use it
but if you don't know its name (or even if it exists) it's much more
difficult to find.

I've only been using Python for a few months and most of the time I
can find my way to what I need but this area of "what things can I do
with this object" still eludes me sometimes.  What *I* need (I'm not
sure if this is a universal requirement though) is some consistent way
of firstly finding out what sort of an object something is (i.e. in
this case, what sort of object is a file) and then getting a list of
methods that I can apply to that object (O.K., this may need some
hierachy or other classification to keep it sane, but hopefully you
can see where I'm going).

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


urgent question, about filesystem-files

2008-04-10 Thread bvidinli
i started python programming a few months ago.

now i need the code to understand if a file already opened in
filesystem by another process ?

i looked at docs, howtos, but did not find related info.
note that normal file open/write operations in python, i know it.

i specificly need to know that "is a file already open by some other
process other than python".


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


Re: email header decoding fails

2008-04-10 Thread Gabriel Genellina
En Wed, 09 Apr 2008 23:12:00 -0300, ZeeGeek <[EMAIL PROTECTED]> escribió:

> It seems that the decode_header function in email.Header fails when
> the string is in the following form,
>
> '=?gb2312?Q?=D0=C7=C8=FC?=(revised)'
>
> That's when a non-encoded string follows the encoded string without
> any whitespace. In this case, decode_header function treats the whole
> string as non-encoded. Is there a work around for this problem?

That header does not comply with RFC2047 (MIME Part Three: Message Header  
Extensions for Non-ASCII Text)

Section 5 (1)
 An 'encoded-word' may replace a 'text' token (as defined by RFC 822)
 in any Subject or Comments header field, any extension message
 header field, or any MIME body part field for which the field body
 is defined as '*text'. [...]
 Ordinary ASCII text and 'encoded-word's may appear together in the
 same header field.  However, an 'encoded-word' that appears in a
 header field defined as '*text' MUST be separated from any adjacent
 'encoded-word' or 'text' by 'linear-white-space'.

Section 5 (3)
 As a replacement for a 'word' entity within a 'phrase', for example,
 one that precedes an address in a From, To, or Cc header.  [...]
 An 'encoded-word' that appears within a
 'phrase' MUST be separated from any adjacent 'word', 'text' or
 'special' by 'linear-white-space'.

-- 
Gabriel Genellina

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


Re: urgent question, about filesystem-files

2008-04-10 Thread Gabriel Genellina
En Thu, 10 Apr 2008 05:11:09 -0300, bvidinli <[EMAIL PROTECTED]> escribió:

> i started python programming a few months ago.
>
> now i need the code to understand if a file already opened in
> filesystem by another process ?
>
> i looked at docs, howtos, but did not find related info.
> note that normal file open/write operations in python, i know it.
>
> i specificly need to know that "is a file already open by some other
> process other than python".

The operating system is more relevant here than Python. Is it Windows,  
some Linux flavor, what?

-- 
Gabriel Genellina

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


Re: I am worried about Python 3

2008-04-10 Thread Gerhard Häring
John Nagle wrote:
> jmDesktop wrote:
> 
>> If I continue in Python 2.5.x, am I making a mistake?  Is it really
>> that different?
> 
>No.  It may never happen, either.  The Perl crowd tried
> something like this, Perl 6, which was announced in 2000 and still
> hasn't come out.  The C++ standards committee has been working on a
> revision of C++ since the 1990s, and that hasn't happened either.
> 
>The general consensus is that Python 3.x isn't much of an
> improvement over the existing language.  There's just not much
> demand for it.

The difference is that Guido learnt from the mistakes of Perl 6 and set 
much more realistic (moderate) goals for Python 3.0.

Unlike others, I think that Python 3.0 will get popular sooner than you 
think. Imagine:

- you're the developer of an Open Source Python library
- for fame and glory, you port it to Python 3.0
- you realize that maintaining two branches is cumbersome
- Python 3.0 becomes first class
- Users switch to ...

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


Re: urgent question, about filesystem-files

2008-04-10 Thread Gary Herron
bvidinli wrote:
> i started python programming a few months ago.
>
> now i need the code to understand if a file already opened in
> filesystem by another process ?
>
> i looked at docs, howtos, but did not find related info.
> note that normal file open/write operations in python, i know it.
>
> i specificly need to know that "is a file already open by some other
> process other than python".
>
>
> Thank you in advance
>   

This is certainly an operating-system dependent bit of functionality.   
So first off, you are going to have to tell us *which* OS you're working 
on. 

Then, perhaps someone can help...

Gary Herron

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


Fwd: urgent question, about filesystem-files

2008-04-10 Thread bvidinli
Sory for lack of information,

 i use linux/unix
 i need to solve this for linux/unix

 i tested os.open with O_EXCL flag, and some other things, that did not solve.

 i need exacly: say example file testfile,

 check if testfile already open by some other process in linux,


 tahnks.
 2008/4/10, Gary Herron <[EMAIL PROTECTED]>:

> bvidinli wrote:
 >
 > > i started python programming a few months ago.
 > >
 > > now i need the code to understand if a file already opened in
 > > filesystem by another process ?
 > >
 > > i looked at docs, howtos, but did not find related info.
 > > note that normal file open/write operations in python, i know it.
 > >
 > > i specificly need to know that "is a file already open by some other
 > > process other than python".
 > >
 > >
 > > Thank you in advance
 > >
 > >
 >
 >  This is certainly an operating-system dependent bit of functionality.   So
 > first off, you are going to have to tell us *which* OS you're working on.
 >  Then, perhaps someone can help...
 >
 >  Gary Herron
 >
 >



--
 İ.Bahattin Vidinli
 Elk-Elektronik Müh.
 ---
 iletisim bilgileri (Tercih sirasina gore):
 skype: bvidinli (sesli gorusme icin, www.skype.com)
 msn: [EMAIL PROTECTED]
 yahoo: bvidinli

 +90.532.7990607
 +90.505.5667711


-- 
İ.Bahattin Vidinli
Elk-Elektronik Müh.
---
iletisim bilgileri (Tercih sirasina gore):
skype: bvidinli (sesli gorusme icin, www.skype.com)
msn: [EMAIL PROTECTED]
yahoo: bvidinli

+90.532.7990607
+90.505.5667711
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urgent question, about filesystem-files

2008-04-10 Thread bvidinli
The need/reason for this,

i write a program that should perform some operation on files, only if
the file is not being used

this is for ensuring that file is not in use, ...
by any process  in system

10.04.2008 tarihinde bvidinli <[EMAIL PROTECTED]> yazmış:
> Sory for lack of information,
>
>   i use linux/unix
>   i need to solve this for linux/unix
>
>   i tested os.open with O_EXCL flag, and some other things, that did not 
> solve.
>
>   i need exacly: say example file testfile,
>
>   check if testfile already open by some other process in linux,
>
>
>   tahnks.
>   2008/4/10, Gary Herron <[EMAIL PROTECTED]>:
>
>
>  > bvidinli wrote:
>   >
>   > > i started python programming a few months ago.
>   > >
>   > > now i need the code to understand if a file already opened in
>   > > filesystem by another process ?
>   > >
>   > > i looked at docs, howtos, but did not find related info.
>   > > note that normal file open/write operations in python, i know it.
>   > >
>   > > i specificly need to know that "is a file already open by some other
>   > > process other than python".
>   > >
>   > >
>
>  > > Thank you in advance
>   > >
>   > >
>   >
>   >  This is certainly an operating-system dependent bit of functionality.   
> So
>   > first off, you are going to have to tell us *which* OS you're working on.
>   >  Then, perhaps someone can help...
>   >
>   >  Gary Herron
>   >
>   >
>
>
>
>  --
>   İ.Bahattin Vidinli
>   Elk-Elektronik Müh.
>   ---
>   iletisim bilgileri (Tercih sirasina gore):
>   skype: bvidinli (sesli gorusme icin, www.skype.com)
>   msn: [EMAIL PROTECTED]
>   yahoo: bvidinli
>
>   +90.532.7990607
>   +90.505.5667711
>
>
>  --
>  İ.Bahattin Vidinli
>  Elk-Elektronik Müh.
>  ---
>  iletisim bilgileri (Tercih sirasina gore):
>  skype: bvidinli (sesli gorusme icin, www.skype.com)
>  msn: [EMAIL PROTECTED]
>  yahoo: bvidinli
>
>  +90.532.7990607
>  +90.505.5667711
>


-- 
İ.Bahattin Vidinli
Elk-Elektronik Müh.
---
iletisim bilgileri (Tercih sirasina gore):
skype: bvidinli (sesli gorusme icin, www.skype.com)
msn: [EMAIL PROTECTED]
yahoo: bvidinli

+90.532.7990607
+90.505.5667711
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what's the reasonale of loghelper() in mathmodule.c

2008-04-10 Thread rockins
On Apr 9, 9:11 pm, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Apr 9, 4:38 am,rockins<[EMAIL PROTECTED]> wrote:
>
> > I cannot understand it well, can anyone explain me why and how
> > loghelper() can compute any base logarithm? Or could anyone give me
> > some reference(such as, books or papers)?
>
> loghelper is there so that log(n) can be computed for any positive
> integer n---it's nothing to do with computing logs to an arbitrary
> base.
>
> All of the other math functions convert an integer argument to a float
> first.  That conversion fails if the integer is larger than the
> largest
> representable float (around 1.7e308 on most systems).  For example:
>
> >>> from math import sqrt, log
> >>> sqrt(10**600)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> OverflowError: long int too large to convert to float>>> log(10**600)
>
> 1381.5510557964274
>
> The sqrt call first tries to convert 10**600 to a float, giving an
> OverflowError (even though the actual square root *is* representable
> as a float).  The log call goes through loghelper instead, which
> doesn't try to convert 10**600 to a float, but instead computes
> the log based on the top few bits of 10**600 (in its internal
> binary representation) and on the number of bits required to
> represent 10**600.
>
> You're not going to learn much about math function implementations
> from mathmodule.c:  all it does it wrap the platform libm functions.
>
> Mark

Thanks Marks, your explanation is very clear. Yes, I do not need to
learn much about the math functions' implementation of libm, I just
need to know why there exists loghelper() in mathmodule.c; I have
checked Python's longobject.c, I think I have understood why
loghelper() is needed now. Since Python can represent arbitrary
precision long integer object, so for logarithm it indeed need to deal
with very huge number. Doesn't it? If there's any misunderstanding of
mine, please point out. Thank you very much.

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


Re: questions about Exceptions?

2008-04-10 Thread cokofreedom
In general you should only catch the exceptions you want to catch,
therefore avoiding the issue of catching "unexpected" ones, for
instances the programming unexpectandly closing.

Well, exception handling is expensive (when it catches one) so it
really is up to you. If you are using eval and know it might "EOF"
then you should probably look to handle that. The main IF statement
style I can think of (checking the end of the string) wouldn't be much
of an improvement.

Currently I would be very worried about seeing that code as it breaks
a number of "conventions". However it depends on the importance of the
code to wherever or not you should change this. (Global variable, the
use of Eval, the CATCH ALL except and the setting of a global variable
at the end.)

I've seen a good few (simple and advanced) calculator examples using
python on the NET, it might be worth looking at some to see their
style of coding a calculator to help your own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find documentation about methods etc. for iterators

2008-04-10 Thread Gabriel Genellina
En Thu, 10 Apr 2008 05:24:24 -0300, <[EMAIL PROTECTED]> escribió:

> Terry Reedy <[EMAIL PROTECTED]> wrote:
>>
>> <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>> | I'm not sure if I have even phrased that right but anyway
>> |
>> | How does one find (in the standard Python documentation) information
>> | about things like the iteritems() method and the enumerate() function.
>>
>> The Library Reference manual sections on builtin functions and dict
>> methods.
>>
>> Or, help(enumerate) and help({}.iteritems)
>>
>  but that doesn't address my problem really, how do I know that I
> need to look for the words enumerate and/or iteritems?  This is what
> my original question was about.

You'll have to read at least section 2 (built-in objects) and section 3  
(built-in types) in the Library Reference: http://docs.python.org/lib/
That's the most important part to know.

> There I was thinking that there has to be an easy way to get line
> numbers as I read lines from a file but not knowing how to find out
> how to do it:-
>
> First question, what sort of 'thing' is the file object, I need to
> know that if I'm to look up ways of using it.
>
> Second question, even if I know what sort of thing a file object
> is, how do I find methods applicable to it and/or functions
> applicable to it?

You look for 'file object' in the index and find
http://docs.python.org/lib/bltin-file-objects.html

> The possibility that I might want either a method or a function adds
> to the fun.  In my original query it seemed odd that some objects have
> the iteritems *method* whereas other objects have the enumerate
> *function*.

Other objects don't "have" the enumerate function, enumerate is a builtin  
function that can be used with any sequence or iterable object. Your know  
it because you have read section 2.1 in the Library Reference as I've told  
you a few lines above :)

> It's a common problem in all sorts of computer fields, if you know the
> name of what you want it's easy to find out details of how to use it
> but if you don't know its name (or even if it exists) it's much more
> difficult to find.

Yes, certainly. Python comes with "batteries included" and there are many  
of them. You don't have to read the whole Library Reference from begin to  
end, but at least have a look at the titles so you know that certain thing  
exists.

> I've only been using Python for a few months and most of the time I
> can find my way to what I need but this area of "what things can I do
> with this object" still eludes me sometimes.  What *I* need (I'm not
> sure if this is a universal requirement though) is some consistent way
> of firstly finding out what sort of an object something is (i.e. in
> this case, what sort of object is a file) and then getting a list of
> methods that I can apply to that object (O.K., this may need some
> hierachy or other classification to keep it sane, but hopefully you
> can see where I'm going).

A file is... a file:

py> f = open("temp.txt","r")
py> type(f)


You can invoke the help system with any object:

py> help(f)
Help on file object:

class file(object)
  |  file(name[, mode[, buffering]]) -> file object
  |
  |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
  |  writing or appending.  The file will be created if it doesn't exist
  |  when opened for writing or appending; [blah...]
  [... including all methods defined in the file class ...]

You can use help with a particular methods or function too:

py> help(f.write)
Help on built-in function write:

write(...)
 write(str) -> None.  Write string str to file.

 Note that due to buffering, [blah...]

You can use dir(something) to see which attributes (including methods) an  
object has:

py> dir(f)
['__class__', '__delattr__', '__doc__',
...
'close', 'closed', 'encoding', ... 'write', 'writelines', 'xreadlines']

Hope this helps.

-- 
Gabriel Genellina

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


Re: Sorting Directories from files in a os.listdir??

2008-04-10 Thread Giampaolo Rodola'
On 10 Apr, 11:55, Soren <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'd like to read the filenames in a directory, but not the
> subdirectories, os.listdir() gives me everything... how do I separate
> the directory names from the filenames? Is there another way of doing
> this?
>
> Thanks!

I guess you have no other way than using os.path.isfile or
os.path.isdir for every entry returned by os.listdir.


--- Giampaolo
http://code.google.com/p/pyftpdlib
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call python from c -> pass and return arrays/lists

2008-04-10 Thread Diez B. Roggisch
Pieter wrote:

> Hi all,
> 
> I'm trying to call a python function from c. I need to pass an
> 2D-array to python and the python function returns a 2D-list back to
> c. I googled arround and I found how to pass ints/strings/... back and
> forth, but didn't find anything on passing arrays.
> 
> For an int it's as simple as this:
> 
> PyArg_Parse(ret,"i#", &my_long);
> 
> But I hacve no idea how to parse python lists to a c-array?

You return a list, parse that as object, and then work with the
sequence-protocol on them.

UNTESTED:

PyArg_Parse(ret,"o", &the_list);
if(PySequence_Check(the_list) {
  int size = PySequence_Size(the_list);
  int *result = malloc(sizof(int) * size);
  for(int i = 0; i < size; i++) {
 PyObject *item = PySequence_GetItem(the_list, i);
 if(PyInt_Check(item)) {
   result[i] = PyInt_AsLong(item);
 } else {
   return NULL;
 }
  }



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


Re: How is GUI programming in Python?

2008-04-10 Thread David Cook
On 2008-04-10, Chris Stewart <[EMAIL PROTECTED]> wrote:

> I've always had an interest in Python and would like to dabble in it  
> further.  I've worked on a few very small command line programs but  
> nothing of any complexity.  I'd like to build a really simple GUI app  
> that will work across Mac, Windows, and Linux.  How painful is that  
> going to be?  

With wxpython and pyqt, it can be relatively painless.  You can often just
copy your code directly from one OS to the other and run it, and py2exe
makes it easy to distribute python apps to windows users.  I haven't tried
packaging on OS X (with py2app?).

> I used to be really familiar with Java Swing a few years  
> ago.  I imagine it will be similar.

Yes, the broad principles (event driven, single-threaded event loop) are
pretty much the same.

Note, if you really like Swing, you can use it from Jython.  Your app would
install and look like any other Java app to users (Jython is just another
jar in your distribution), for good or ill.

> Next, what would you say is the best framework I should look into?   
> I'm curious to hear opinions on that.

We use wxPython at work because of the more liberal license.  It's very
capable and works well for us.  

However, for my own projects, I've switched to pyqt, which offers more
complete application help (e.g. things like Actions) and uses MVC from the
ground up rather than as an afterthought.  I also find the pyqt API cleaner
and more consistent; some aspects of wxpython still seem clunky to me.  And
the auto-completion solution offered on the wxPython wiki doesn't work on
Mac, which pretty much killed it for my project.

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


Re: email header decoding fails

2008-04-10 Thread ZeeGeek
On Apr 10, 4:31 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 09 Apr 2008 23:12:00 -0300, ZeeGeek <[EMAIL PROTECTED]> escribió:
>
> > It seems that the decode_header function in email.Header fails when
> > the string is in the following form,
>
> > '=?gb2312?Q?=D0=C7=C8=FC?=(revised)'
>
> > That's when a non-encoded string follows the encoded string without
> > any whitespace. In this case, decode_header function treats the whole
> > string as non-encoded. Is there a work around for this problem?
>
> That header does not comply with RFC2047 (MIME Part Three: Message Header
> Extensions for Non-ASCII Text)
>
> Section 5 (1)
>  An 'encoded-word' may replace a 'text' token (as defined by RFC 822)
>  in any Subject or Comments header field, any extension message
>  header field, or any MIME body part field for which the field body
>  is defined as '*text'. [...]
>  Ordinary ASCII text and 'encoded-word's may appear together in the
>  same header field.  However, an 'encoded-word' that appears in a
>  header field defined as '*text' MUST be separated from any adjacent
>  'encoded-word' or 'text' by 'linear-white-space'.
>
> Section 5 (3)
>  As a replacement for a 'word' entity within a 'phrase', for example,
>  one that precedes an address in a From, To, or Cc header.  [...]
>  An 'encoded-word' that appears within a
>  'phrase' MUST be separated from any adjacent 'word', 'text' or
>  'special' by 'linear-white-space'.

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


Re: Sorting Directories from files in a os.listdir??

2008-04-10 Thread David Harrison
On 10/04/2008, Soren <[EMAIL PROTECTED]> wrote:
> Hi,
>
>  I'd like to read the filenames in a directory, but not the
>  subdirectories, os.listdir() gives me everything... how do I separate
>  the directory names from the filenames? Is there another way of doing
>  this?

The only thing I can think of if you just want the immediate dir is to
use the os.path module's function isfile to test each item from the
list returned by os.listdir.

This should do the trick I think:

[ f for f in os.listdir('pathname') if os.path.isfile(f) ]

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


Re: urgent question, about filesystem-files

2008-04-10 Thread Gerhard Häring
bvidinli wrote:
> i started python programming a few months ago.
> 
> now i need the code to understand if a file already opened in
> filesystem by another process ?
> 
> i looked at docs, howtos, but did not find related info.
> note that normal file open/write operations in python, i know it.
> 
> i specificly need to know that "is a file already open by some other
> process other than python".

The pragmatic solution here is to not worry about it and let it be the 
user's problem if he does something stupid.

It's OS specific how to get at this information. On Linux, for example 
you can call the `fuser` program (if installed; on Ubuntu it's in the 
psmisc package). But this will only tell you if the same user has the 
file open (or if you're root).

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


Re: email header decoding fails

2008-04-10 Thread Gabriel Genellina
En Thu, 10 Apr 2008 05:45:41 -0300, ZeeGeek <[EMAIL PROTECTED]> escribió:

> On Apr 10, 4:31 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
>> En Wed, 09 Apr 2008 23:12:00 -0300, ZeeGeek <[EMAIL PROTECTED]>  
>> escribió:
>>
>> > It seems that the decode_header function in email.Header fails when
>> > the string is in the following form,
>>
>> > '=?gb2312?Q?=D0=C7=C8=FC?=(revised)'

>>  An 'encoded-word' that appears within a
>>  'phrase' MUST be separated from any adjacent 'word', 'text' or
>>  'special' by 'linear-white-space'.
>
> Thank you very much, Gabriel.

The above just says "why" decode_header refuses to decode it, and why it's  
not a bug. But if you actually have to deal with those malformed headers,  
some heuristics may help. By example, if you *know* your mails typically  
specify gb2312 encoding, or iso-8859-1, you may look for things that look  
like the example above and "fix" it.

-- 
Gabriel Genellina

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


Sorting Directories from files in a os.listdir??

2008-04-10 Thread Soren
Hi,

I'd like to read the filenames in a directory, but not the
subdirectories, os.listdir() gives me everything... how do I separate
the directory names from the filenames? Is there another way of doing
this?

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


Re: Sorting Directories from files in a os.listdir??

2008-04-10 Thread Soren
On Apr 10, 12:14 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Thu, 10 Apr 2008 06:55:13 -0300, Soren <[EMAIL PROTECTED]>
> escribió:
>
> > I'd like to read the filenames in a directory, but not the
> > subdirectories, os.listdir() gives me everything... how do I separate
> > the directory names from the filenames? Is there another way of doing
> > this?
>
> Check each returned name using os.path.isfile
> (untested):
>
> def files_only(path):
>return [filename for filename in os.listdir(path)
>if os.path.isfile(os.path.join(path, filename))]
>
> --
> Gabriel Genellina

Thanks everyone! That worked! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about Exceptions?

2008-04-10 Thread cokofreedom
> def Calc():
> global nbr
> try:
> print eval(nbr)
> #a = Label(mygui, text=eval(nbr))
> #a.place(relx=0.4, rely=0.1, anchor=CENTER)
> except:
> print "Not computable"
> nbr = ""
>
> def Erase():
> global nbr
> nbr = ""

Seems to me you could be better off passing a parameter and a return
statement of None (or your parameter cleaned) for those functions,
which should work. Given an input, Eval it and then return None. That
way you wouldn't need the Erase...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am worried about Python 3

2008-04-10 Thread Carl Banks
On Apr 9, 11:53 am, John Nagle <[EMAIL PROTECTED]> wrote:
> jmDesktop wrote:
> > If I continue in Python 2.5.x, am I making a mistake?  Is it really
> > that different?
>
> No.  It may never happen, either.  The Perl crowd tried
> something like this, Perl 6, which was announced in 2000 and still
> hasn't come out.  The C++ standards committee has been working on a
> revision of C++ since the 1990s, and that hasn't happened either.

You're not paying attention if you think there's it's still doubt over
whether Python 3 will happen.


> The general consensus is that Python 3.x isn't much of an
> improvement over the existing language.

I'm going to have to opine that you pulled this out of your ass.


> There's just not much demand for it.

Well that's a little mode defensible seeing that we really don't know
how people will react.


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


Re: urgent question, about filesystem-files

2008-04-10 Thread bvidinli
* i do not want to prevent other process access same file,  i only
want if a file being used as i acess it.

* i am not interested if a process will access same file just after i
access it... because in my case, this is not possible..

* i want some other way, other than linux lsof command. it is slow for me.
is there a native python way, ?

thanks.


2008/4/10, Diez B. Roggisch <[EMAIL PROTECTED]>:
> bvidinli wrote:
>
>  > this is for ensuring that file is not in use, ...
>  > by any process  in system
>
>
> How do you prevent the other processes that *might* access that file from
>  doing so while *you* work on it? unless they cooperate using file-locks,
>  you might end up with garbage.
>
>  Diez
>
> --
>  http://mail.python.org/mailman/listinfo/python-list


-- 
İ.Bahattin Vidinli
Elk-Elektronik Müh.
---
iletisim bilgileri (Tercih sirasina gore):
skype: bvidinli (sesli gorusme icin, www.skype.com)
msn: [EMAIL PROTECTED]
yahoo: bvidinli

+90.532.7990607
+90.505.5667711
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about Exceptions?

2008-04-10 Thread skanemupp
On 10 Apr, 12:38, [EMAIL PROTECTED] wrote:
> > def Calc():
> > global nbr
> > try:
> > print eval(nbr)
> > #a = Label(mygui, text=eval(nbr))
> > #a.place(relx=0.4, rely=0.1, anchor=CENTER)
> > except:
> > print "Not computable"
> > nbr = ""
>
> > def Erase():
> > global nbr
> > nbr = ""
>
> Seems to me you could be better off passing a parameter and a return
> statement of None (or your parameter cleaned) for those functions,
> which should work. Given an input, Eval it and then return None. That
> way you wouldn't need the Erase...

the erase() id alwys need if u wanna abort whilst u wrote something.
-- 
http://mail.python.org/mailman/listinfo/python-list


call python from c -> pass and return arrays/lists

2008-04-10 Thread Pieter
Hi all,

I'm trying to call a python function from c. I need to pass an
2D-array to python and the python function returns a 2D-list back to
c. I googled arround and I found how to pass ints/strings/... back and
forth, but didn't find anything on passing arrays.

For an int it's as simple as this:

PyArg_Parse(ret,"i#", &my_long);

But I hacve no idea how to parse python lists to a c-array?

thanks a lot,

Pieter
-- 
Pieter Cogghe
Ganzendries 186
9000 Gent
0487 10 14 21
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urgent question, about filesystem-files

2008-04-10 Thread Diez B. Roggisch
bvidinli wrote:

> this is for ensuring that file is not in use, ...
> by any process  in system

How do you prevent the other processes that *might* access that file from
doing so while *you* work on it? unless they cooperate using file-locks,
you might end up with garbage.

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

Re: urgent question, about filesystem-files

2008-04-10 Thread Robert.Spilleboudt
bvidinli wrote:
> i started python programming a few months ago.
> 
> now i need the code to understand if a file already opened in
> filesystem by another process ?
> 
> i looked at docs, howtos, but did not find related info.
> note that normal file open/write operations in python, i know it.
> 
> i specificly need to know that "is a file already open by some other
> process other than python".
> 
> 
> Thank you in advance
This is a OS function. With Linux you use the command lsof (as root). A 
Python program can call such a command, but you have to parse the output.
Robert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting Directories from files in a os.listdir??

2008-04-10 Thread Gabriel Genellina
En Thu, 10 Apr 2008 06:55:13 -0300, Soren <[EMAIL PROTECTED]>  
escribió:

> I'd like to read the filenames in a directory, but not the
> subdirectories, os.listdir() gives me everything... how do I separate
> the directory names from the filenames? Is there another way of doing
> this?

Check each returned name using os.path.isfile
(untested):

def files_only(path):
   return [filename for filename in os.listdir(path)
   if os.path.isfile(os.path.join(path, filename))]

-- 
Gabriel Genellina

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


Re: How to find documentation about methods etc. for iterators

2008-04-10 Thread Tim Chase
> First question, what sort of 'thing' is the file object, I need to
> know that if I'm to look up ways of using it.

you can always use

   type(thing)

to find out what type it is.

> Second question, even if I know what sort of thing a file object
> is, how do I find methods applicable to it and/or functions
> applicable to it?

If you don't have a web-connection under your finger tips, using

   dir(thing)
   help(thing)
   help(thing.method)

will tell you most of what you need to know.  There's the 
occasional gap, and it doesn't always work when the underlying 
object is out in C-land, rather than a pure Python object that's 
well-designed with doc-strings (personal complaint about 
mod_python's failure to return dir() contents last I checked). 
But for the most part I can just pull up a console debug-session 
with Python, enter enough to get an instance of the object in 
question, and then use the above commands.

This for me is Python's chief selling point:  dir()dir() and 
help().  Python's two selling points are dir(), help(), and very 
readable code.  Python's *three* selling points are dir(), 
help(), very readable code, and an almost fanatical devotion to 
the BFDL.  Amongst Python's selling points are such elements as 
dir(),  help()...I'll come in again. 

> It's a common problem in all sorts of computer fields, if you know the
> name of what you want it's easy to find out details of how to use it
> but if you don't know its name (or even if it exists) it's much more
> difficult to find.

All Monty Python-quoting aside, Python has solved this (and gives 
3rd-party library developers the tools to solve as well) problem 
of discoverability using dir() and help().

-tkc




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


Re: questions about Exceptions?

2008-04-10 Thread skanemupp
On 10 Apr, 10:51, [EMAIL PROTECTED] wrote:
> In general you should only catch the exceptions you want to catch,
> therefore avoiding the issue of catching "unexpected" ones, for
> instances the programming unexpectandly closing.
>
> Well, exception handling is expensive (when it catches one) so it
> really is up to you. If you are using eval and know it might "EOF"
> then you should probably look to handle that. The main IF statement
> style I can think of (checking the end of the string) wouldn't be much
> of an improvement.
>
> Currently I would be very worried about seeing that code as it breaks
> a number of "conventions". However it depends on the importance of the
> code to wherever or not you should change this. (Global variable, the
> use of Eval, the CATCH ALL except and the setting of a global variable
> at the end.)
>
> I've seen a good few (simple and advanced) calculator examples using
> python on the NET, it might be worth looking at some to see their
> style of coding a calculator to help your own.


i know about the GLOBAL stuff, i might rewrite the program using
classes later so i can avoid this. i am mainly playin with tkinter for
now.

i was thinking the same check with if at the beginning and end of the
string so there isnt a */ but also if someone uses /// or soemthing
like that in the middle it crashes so it is hard to cover every case,
esp since **5 means ^5.
is the use of if also expensive?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wrapping C functions in python

2008-04-10 Thread Jaap Spies
Paul Anton Letnes wrote:
> Hi, and thanks.
> 
> 
> However, being a newbie, I now have to ask: What is SWIG? I have heard 
> the name before, but haven't understood what it is, why I need it, or 
> similar. Could you please supply some hints?
> 
[...]
>>>
>>> I am a "scientific" user of Python, and hence have to write some 
>>> performance
>>> critical algorithms. Right now, I am learning Python, so this is a 
>>> "newbie"
>>> question.
>>>
>>> I would like to wrap some heavy C functions inside Python, 
>>> specifically a
>>> wavelet transform. I am beginning to become aquainted with the functions
>>> PyArg_ParseTuple() and Py_BuildValue(). However, I am unable to 
>>> figure out
>>> how to pass Python list -> C function or C array -> return value in 
>>> Python.
>>> I manage to build and run the C function, print to screen, pass 
>>> string as
>>> argument, return an int, etc. The thing which is missing is the magic
>>> array/list...
>>>
>>>
>>> Thanks in advance! I fart in your general direction.
>>> Paul.

Maybe you should have a look at Cython:

http://www.cython.org/

and Sage:

http://www.sagemath.org/

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


Re: questions about Exceptions?

2008-04-10 Thread skanemupp
here is the whole code:

from __future__ import division
import Tkinter
from Tkinter import *

mygui = Tkinter.Tk()
mygui.title("Calculator")

w = Label(mygui, text="Answer: ")
w.place(relx=0.15, rely=0.1, anchor=CENTER)

nbr = ""

def Disp(nstr):
global nbr
nbr=nbr+nstr
print "You need to seek help!",nbr

def Calc():
global nbr
try:
print eval(nbr)
#a = Label(mygui, text=eval(nbr))
#a.place(relx=0.4, rely=0.1, anchor=CENTER)
except:
print "Not computable"
nbr = ""

def Erase():
global nbr
nbr = ""


b = Button(mygui, text="1",command=lambda n='1':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.2, anchor=CENTER)
b = Button(mygui, text="2",command=lambda n='2':Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.2, anchor=CENTER)
b = Button(mygui, text="3",command=lambda n='3':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.2, anchor=CENTER)
b = Button(mygui, text="+",command=lambda n='+':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.2, anchor=CENTER)
b = Button(mygui, text="4",command=lambda n='4':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.3, anchor=CENTER)
b = Button(mygui, text="5",command=lambda n='5':Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.3, anchor=CENTER)
b = Button(mygui, text="6",command=lambda n='6':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.3, anchor=CENTER)
b = Button(mygui, text="-",command=lambda n='-':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.3, anchor=CENTER)
b = Button(mygui, text="7",command=lambda n='7':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.4, anchor=CENTER)
b = Button(mygui, text="8",command=lambda n='8':Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.4, anchor=CENTER)
b = Button(mygui, text="9",command=lambda n='9':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.4, anchor=CENTER)
b = Button(mygui, text="*",command=lambda n='*':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.4, anchor=CENTER)
b = Button(mygui, text="0",command=lambda n='0':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.5, anchor=CENTER)
b = Button(mygui, text="C",command=Erase, width=2, height=1)
b.place(relx=0.2, rely=0.5, anchor=CENTER)
b = Button(mygui, text="^.5",command=lambda n='**.5':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.5, anchor=CENTER)
b = Button(mygui, text="/",command=lambda n='/':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.5, anchor=CENTER)
b = Button(mygui, text="=",command=Calc, width=2, height=1)
b.place(relx=0.2, rely=0.7, anchor=CENTER)

mygui.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about Exceptions?

2008-04-10 Thread cokofreedom
> the erase() id alwys need if u wanna abort whilst u wrote something.

But if it is meant to only evaluate once you've pressed the enter key
(I take it?) you shouldn't need that. And if you are to abort while
evaluating it will not do that.
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with using gnuplot/demo.py

2008-04-10 Thread diljeet kaur
hi
i want to use gnuplot with python
i installed it  seemingly successfully
but when i try to run demo.py it gives the following error


Traceback (most recent call last):
  File "C:\Python23\Lib\site-packages\Gnuplot\demo.py", line 113, in ?
demo()
  File "C:\Python23\Lib\site-packages\Gnuplot\demo.py", line 39, in demo
g.reset()
  File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 355, in reset
self('reset')
  File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 199, in 
__call__
self.gnuplot(s)
  File "C:\Python23\Lib\site-packages\Gnuplot\gp_win32.py", line 125, in 
__call__
self.write(s + '\n')


im using python23 & gnuplot1.7

please help


  Save all your chat conversations. Find them online at 
http://in.messenger.yahoo.com/webmessengerpromo.php-- 
http://mail.python.org/mailman/listinfo/python-list

Re: questions about Exceptions?

2008-04-10 Thread skanemupp
On 10 Apr, 13:15, [EMAIL PROTECTED] wrote:
> > the erase() id alwys need if u wanna abort whilst u wrote something.
>
> But if it is meant to only evaluate once you've pressed the enter key
> (I take it?) you shouldn't need that. And if you are to abort while
> evaluating it will not do that.


CHANGED IT NOW TO A MUCH BETTER SOLUTION(will see if i can make a
better solution with the buttons, hate big blocks of similarlooking
code):


from __future__ import division
import Tkinter
from Tkinter import *

mygui = Tkinter.Tk()
mygui.title("Calculator")

l = Label(mygui, text="Answer: ")
l.place(relx=0.15, rely=0.2, anchor=CENTER)

e = Entry(mygui)
e.place(relx=0.4, rely=0.1, anchor=CENTER)

def Disp(nstr):
e.insert(END, nstr)

def Calc():
expr=e.get()
try:
b = Label(mygui, text=eval(expr))
b.place(relx=0.4, rely=0.2, anchor=CENTER)
except:
b = Label(mygui, text="Not computable")
b.place(relx=0.4, rely=0.2, anchor=CENTER)

def Erase():
e.delete(0,END)

b = Button(mygui, text="1",command=lambda n='1':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.4, anchor=CENTER)
b = Button(mygui, text="2",command=lambda n='2':Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.4, anchor=CENTER)
b = Button(mygui, text="3",command=lambda n='3':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.4, anchor=CENTER)
b = Button(mygui, text="+",command=lambda n='+':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.4, anchor=CENTER)
b = Button(mygui, text="4",command=lambda n='4':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.5, anchor=CENTER)
b = Button(mygui, text="5",command=lambda n='5':Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.5, anchor=CENTER)
b = Button(mygui, text="6",command=lambda n='6':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.5, anchor=CENTER)
b = Button(mygui, text="-",command=lambda n='-':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.5, anchor=CENTER)
b = Button(mygui, text="7",command=lambda n='7':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.6, anchor=CENTER)
b = Button(mygui, text="8",command=lambda n='8':Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.6, anchor=CENTER)
b = Button(mygui, text="9",command=lambda n='9':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.6, anchor=CENTER)
b = Button(mygui, text="*",command=lambda n='*':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.6, anchor=CENTER)
b = Button(mygui, text="0",command=lambda n='0':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.7, anchor=CENTER)
b = Button(mygui, text="C",command=Erase, width=2, height=1)
b.place(relx=0.2, rely=0.7, anchor=CENTER)
b = Button(mygui, text="^",command=lambda n='**':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.7, anchor=CENTER)
b = Button(mygui, text="/",command=lambda n='/':Disp(n), width=2,
height=1)
b.place(relx=0.4, rely=0.7, anchor=CENTER)
b = Button(mygui, text=".",command=lambda n='.':Disp(n), width=2,
height=1)
b.place(relx=0.1, rely=0.8, anchor=CENTER)
b = Button(mygui, text="(",command=lambda n='(':Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.8, anchor=CENTER)
b = Button(mygui, text=")",command=lambda n=')':Disp(n), width=2,
height=1)
b.place(relx=0.3, rely=0.8, anchor=CENTER)
b = Button(mygui, text="=",command=Calc, width=2, height=1)
b.place(relx=0.4, rely=0.8, anchor=CENTER)

mygui.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Fr] Réflexions sur l'auto complétion dans les éditeurs Python...

2008-04-10 Thread Matthieu Brucher
Le 10/04/08, Jul <[EMAIL PROTECTED]> a écrit :
>
> Bonjour à tous,
>
> L'un des problèmes des éditeurs de code Python est qu'il ne proposent pas
> d'autocomplétion "intelligente", c'est à dire en cohérence avec l'objet en
> cours de frappe. La plupart des éditeurs se basent sur des fichiers texte
> (fichiers API) contenant la liste des méthodes et attributs susceptibles de
> compléter la frappe; mais comme ces suggestions ne sont pas créées
> dynamiquement en fonction de la variable, elles sont souvent à coté de la
> plaque.
>
> En Java, comme toutes les variables sont typées, on connait les méthodes
> et attribtus dès la déclaration de la variable et il est possible de
> proposer exactement les bonnes entrées pour l'autocomplétion.  Mais en
> Python, cela parait plus compliqué a cause du manque de typage...
>
> Pensez-vous qu'un module d'autocomplétion un peu plus "intelligent" que
> des entrées venant d'un fichier statique soit possible ?
> Existe-t-il des modules d'analyse de code permettant de proposer les
> bonnes entrées ?
>

As-tu testé IPython ? L'autocomplétion de ce shell est normalement basée sur
l'introspection du code.

Matthieu
-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: problem with using gnuplot/demo.py

2008-04-10 Thread Paul Anton Letnes

Could you include some code around line 39 in demo.py?

Also, you could try to comment out the stuff before that point, and  
see if the demo runs that far.


Paul.



hi
i want to use gnuplot with python
i installed it  seemingly successfully
but when i try to run demo.py it gives the following error


Traceback (most recent call last):
  File "C:\Python23\Lib\site-packages\Gnuplot\demo.py", line 113, in ?
demo()
  File "C:\Python23\Lib\site-packages\Gnuplot\demo.py", line 39, in  
demo

g.reset()
  File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line  
355, in reset

self('reset')
  File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line  
199, in __call__

self.gnuplot(s)
  File "C:\Python23\Lib\site-packages\Gnuplot\gp_win32.py", line  
125, in __call__

self.write(s + '\n')


im using python23 & gnuplot1.7

please help

From Chandigarh to Chennai - find friends all over India. Click  
here.--

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


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

Re: How to find documentation about methods etc. for iterators

2008-04-10 Thread cokofreedom
>
> This for me is Python's chief selling point:  dir()dir() and
> help().  Python's two selling points are dir(), help(), and very
> readable code.  Python's *three* selling points are dir(),
> help(), very readable code, and an almost fanatical devotion to
> the BFDL.  Amongst Python's selling points are such elements as
> dir(),  help()...I'll come in again. 
>

This brought a smile to my face :)
-- 
http://mail.python.org/mailman/listinfo/python-list


subprocess.Popen() output to logging.StreamHandler()

2008-04-10 Thread sven _
Version: Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)

My goal is to have stdout and stderr written to a logging handler.
This code does not work:

# START
import logging, subprocess
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
# END

Traceback (most recent call last):
  File "log.py", line 5, in 
   subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
  File "/usr/lib/python2.5/subprocess.py", line 443, in call
   return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.5/subprocess.py", line 586, in __init__
   errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python2.5/subprocess.py", line 941, in _get_handles
   c2pwrite = stdout.fileno()
AttributeError: StreamHandler instance has no attribute 'fileno'


This is because subprocess.Popen() expects file descriptors to write
to, and logging.StreamHandler() does not supply it. The StreamHandler
could supply its own stdout file descriptor, but then Popen() would
write directly to that file, bypassing all the logging fluff.

A possible solution would be to make a named pipe (os.mkfifo()), have
Popen() write to that, and then have some horrendous hack run select()
or similar on the fifo to read from it and finally pass it to
StreamHandler.

Are there better solutions?

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


Re: questions about Exceptions?

2008-04-10 Thread skanemupp
from __future__ import division
import Tkinter
from Tkinter import *

mygui = Tkinter.Tk()
mygui.title("Calculator")

l = Label(mygui, text="Answer: ")
l.place(relx=0.15, rely=0.2, anchor=CENTER)

e = Entry(mygui)
e.place(relx=0.4, rely=0.1, anchor=CENTER)

def Disp(nstr):
e.insert(END, nstr)

def Calc():
expr=e.get()
try:
b = Label(mygui, text=eval(expr))
b.place(relx=0.4, rely=0.2, anchor=CENTER)
except:
b = Label(mygui, text="Not computable")
b.place(relx=0.4, rely=0.2, anchor=CENTER)

def Erase():
e.delete(0,END)


x = 0.1
y = 0.4
for char in '123+456-789*0^./()':
b = Button(mygui, text=char,command=lambda n=char:Disp(n),
width=2, height=1)
b.place(relx=x, rely=y, anchor=CENTER)
x=x+0.1
if x==0.5:
x=0.1
y=y+0.1

b = Button(mygui, text="C",command=Erase, width=2, height=1)
b.place(relx=0.3, rely=0.8, anchor=CENTER)
b = Button(mygui, text="=",command=Calc, width=2, height=1)
b.place(relx=0.4, rely=0.8, anchor=CENTER)

mygui.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting Directories from files in a os.listdir??

2008-04-10 Thread Scott David Daniels
Soren wrote:
> Hi,
> 
> I'd like to read the filenames in a directory, but not the
> subdirectories, os.listdir() gives me everything... how do I separate
> the directory names from the filenames? Is there another way of doing
> this?
> 
> Thanks!

 import os
 base, files, dirs = iter(os.walk(dirname)).next()
 # now files is files and dirs is directories (and base == dirname)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text adventure game problem

2008-04-10 Thread corvettecraz92
On Apr 10, 3:14 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Wed, 9 Apr 2008 05:25:19 -0700 (PDT), [EMAIL PROTECTED]
> declaimed the following in comp.lang.python:
>
>
>
> > I can't even compile your code to see how it works, Dennis. I'm
> > confused about what that does.
>
>         My apologies -- it was spur of the moment pseudo-code to illustrate
> the concepts, but was never meant to be directly executable.
>
>         The concepts are that: all rooms are basically the same -- they have
> a list of objects that exist within the room (and, as I now realize, the
> "gold within the cabinet/cup" would still be an object within the room
> -- but would have an attribute "hidden=True" which would control if it
> is itemized when one "examines" the room), a list of exits, and a maybe
> a list of actions which can be performed in the room or on named objects
> (though I see the actions being common methods invoked by the command
> parser -- I illustrated a simple "verb object" command, but a good
> parser should probably accept more complex commands "throw  at
> " for example). Uh, I'm saying "list", but "dictionary" would
> be the likely implementation.
>
>         When one "examines" a room, one essentially gets back a list of the
> objects that are in the room instance. When one "examines" one of those
> objects (by name), one gets back the detailed description of that
> object. If one implements a "hidden" attribute, that object will not be
> listed in the higher level "examine". That "gold" inside another object
> does get a bit tricky -- I now see it as a hidden object in the room,
> but the description of the object has to be somewhat dynamic -- that is,
> if the object (cabinet) sees that the "gold" is in the room, examining
> the object will report the gold. But a "take gold" command still acts on
> the room -- removing the gold from the room inventory, putting it into
> the player inventory, and changing the "hidden" property so it is now
> visible.
>
>         When one does a  "move ", the player's "location"
> attribute is changed from the current room to the room connected to that
> direction.
>
>         For both objects and directions, if the player enters a term that is
> not in the relevant dictionary, a suitable message is returned to the
> user. Oh, room objects, besides that "hidden" attribute, may have a
> "portable" attribute which controls if one can "take" the object... Or
> an attribute for "throwable" which controls if one can throw an object
> at another (and the other would have a method/action for when something
> is thrown at it -- a default would be "No effect").
>
>         From what I saw of your small sample, you were treating each room as
> a discrete function. Moving from one room to another means calling the
> new room's function. But that means you are continuously nesting deeper
> in the Python stack, and someone that keeps moving back and forth
> between two rooms will eventually exceed the Python stack limit.
>
>         By making the "current location" an attribute of a "player
> instance", no recursion is involved -- you move between rooms by simply
> assigning the new room as the "current location".
>
> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         [EMAIL PROTECTED]             [EMAIL PROTECTED]
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               [EMAIL PROTECTED])
>                 HTTP://www.bestiaria.com/


okay, that explains it...
could you provide a working example of a two-room game using your
method please so I can understand it better? Thanks in advance!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting Directories from files in a os.listdir??

2008-04-10 Thread Peter Otten
Scott David Daniels wrote:

>> I'd like to read the filenames in a directory, but not the
>> subdirectories, os.listdir() gives me everything... how do I separate
>> the directory names from the filenames? Is there another way of doing
>> this?
>> 
>> Thanks!
> 
>  import os
>  base, files, dirs = iter(os.walk(dirname)).next()
>  # now files is files and dirs is directories (and base == dirname)

>>> import os
>>> os.listdir(".")
['fifo', 'dir', 'file']  # a fifo, a directory, and a file
>>> w = os.walk(".")
>>> w is iter(w) # calling iter() is a noop here
True
>>> w.next()
('.', ['dir'], ['fifo', 'file']) # base, dirs, files; everything that is not
 # a directory goes into the files list

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


tkinter, overwrite Label-text?

2008-04-10 Thread skanemupp
using python And tkinter.

i have a GUI that outputs a text among other things. after input form
user i want this text to be *)cleared and/or
*)overwritten.

what is the best way to achieve that?

also, how do i make Label-text expand to the right and not to the left?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about Exceptions?

2008-04-10 Thread skanemupp
On 10 Apr, 12:38, [EMAIL PROTECTED] wrote:
> > def Calc():
> > global nbr
> > try:
> > print eval(nbr)
> > #a = Label(mygui, text=eval(nbr))
> > #a.place(relx=0.4, rely=0.1, anchor=CENTER)
> > except:
> > print "Not computable"
> > nbr = ""
>
> > def Erase():
> > global nbr
> > nbr = ""
>
> Seems to me you could be better off passing a parameter and a return
> statement of None (or your parameter cleaned) for those functions,
> which should work. Given an input, Eval it and then return None. That
> way you wouldn't need the Erase...

i never really got what u meant by this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call python from c -> pass and return arrays/lists

2008-04-10 Thread Pieter
Thanks, this did the trick:

PyArg_Parse(ret,"O", &the_list);
if (PySequence_Check(the_list)) {
 int size = PySequence_Size(the_list);
 int *result = malloc(sizeof(int) * size);
 int i;
 for (i = 0; i < size; i++) {
PyObject *item = PySequence_GetItem(the_list, i);
if(PyInt_Check(item)) {
  result[i] = PyInt_AsLong(item);
  printf("value %d: %d", i, result[i]);
} else {
printf("Didn't work, NO INT");
}
 }
}

kind regards,

Pieter

-- Doorgestuurd bericht --
From: "Diez B. Roggisch" <[EMAIL PROTECTED]>
To: python-list@python.org
Date: Thu, 10 Apr 2008 12:23:56 +0200
Subject: Re: call python from c -> pass and return arrays/lists
Pieter wrote:

> Hi all,
>
> I'm trying to call a python function from c. I need to pass an
> 2D-array to python and the python function returns a 2D-list back to
> c. I googled arround and I found how to pass ints/strings/... back and
> forth, but didn't find anything on passing arrays.
>
> For an int it's as simple as this:
>
> PyArg_Parse(ret,"i#", &my_long);
>
> But I hacve no idea how to parse python lists to a c-array?

You return a list, parse that as object, and then work with the
sequence-protocol on them.

UNTESTED:

PyArg_Parse(ret,"o", &the_list);
if(PySequence_Check(the_list) {
 int size = PySequence_Size(the_list);
 int *result = malloc(sizof(int) * size);
 for(int i = 0; i < size; i++) {
PyObject *item = PySequence_GetItem(the_list, i);
if(PyInt_Check(item)) {
  result[i] = PyInt_AsLong(item);
} else {
  return NULL;
}
 }



Diez

-- 
Pieter Cogghe
Ganzendries 186
9000 Gent
0487 10 14 21
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am worried about Python 3

2008-04-10 Thread Roy Smith
Gerhard Häring <[EMAIL PROTECTED]> wrote:

> The difference is that Guido learnt from the mistakes of Perl 6 and set 
> much more realistic (moderate) goals for Python 3.0.

Another difference is that by the time Perl 6 was being worked on, there 
were other new things on the horizon.  People wanting something better than 
Perl 5 were looking at Python, Ruby, or Tcl.  You're not going to convince 
your customers to upgrade to a new flavor of duct tape when they're already 
playing with velcro.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: tkinter, overwrite Label-text?

2008-04-10 Thread [EMAIL PROTECTED]
On Apr 10, 2:35 pm, [EMAIL PROTECTED] wrote:
> using python And tkinter.
>
> i have a GUI that outputs a text among other things. after input form
> user i want this text to be *)cleared and/or
> *)overwritten.
>
> what is the best way to achieve that?
> [...]

Which widget do you use?

Some widgets can be connected to variables so that when the variable
changes the widget is automatically update.
Have a look http://docs.python.org/lib/node696.html>.

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


Re: tkinter, overwrite Label-text?

2008-04-10 Thread skanemupp
On 10 Apr, 15:28, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On Apr 10, 2:35 pm, [EMAIL PROTECTED] wrote:
>
> > using python And tkinter.
>
> > i have a GUI that outputs a text among other things. after input form
> > user i want this text to be *)cleared and/or
> > *)overwritten.
>
> > what is the best way to achieve that?
> > [...]
>
> Which widget do you use?
>
> Some widgets can be connected to variables so that when the variable
> changes the widget is automatically update.
> Have a look http://docs.python.org/lib/node696.html>.
>
> HTH,
> Dennis Benzinger

i use the Label-widget.
-- 
http://mail.python.org/mailman/listinfo/python-list


Code-convention checker and possibly reformatter

2008-04-10 Thread Diez B. Roggisch
Hi,

my new company requires me to adhere to some coding conventions - order of
imports, amount of whitespace between method definitions and such stuff.

Because I'm a lazy a**, I'd like to have some automatic checker that will
ensure that I'm following the conventions.

Now I know & use pylint - but the docs are sparse, and so I wonder if and
how one writes plugins for it.

Of course I also dabbled with tokenize and compiler - but those two either
are to lowlevel or already to abstract (the former forces me to re-create
trees on my own, the latter throws away to much data, e.g. comments and
whitespace)

So - any suggestions how to proceed?

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


Re: subprocess.Popen() output to logging.StreamHandler()

2008-04-10 Thread Thomas Dimson
On Apr 10, 8:11 am, "sven _" <[EMAIL PROTECTED]> wrote:
> Version: Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)
>
> My goal is to have stdout and stderr written to a logging handler.
> This code does not work:
>
> # START
> import logging, subprocess
> ch = logging.StreamHandler()
> ch.setLevel(logging.DEBUG)
> subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
> # END
>
> Traceback (most recent call last):
>   File "log.py", line 5, in 
>    subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
>   File "/usr/lib/python2.5/subprocess.py", line 443, in call
>    return Popen(*popenargs, **kwargs).wait()
>   File "/usr/lib/python2.5/subprocess.py", line 586, in __init__
>    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
>   File "/usr/lib/python2.5/subprocess.py", line 941, in _get_handles
>    c2pwrite = stdout.fileno()
> AttributeError: StreamHandler instance has no attribute 'fileno'
>
> This is because subprocess.Popen() expects file descriptors to write
> to, and logging.StreamHandler() does not supply it. The StreamHandler
> could supply its own stdout file descriptor, but then Popen() would
> write directly to that file, bypassing all the logging fluff.
>
> A possible solution would be to make a named pipe (os.mkfifo()), have
> Popen() write to that, and then have some horrendous hack run select()
> or similar on the fifo to read from it and finally pass it to
> StreamHandler.
>
> Are there better solutions?
>
> sven


What is wrong with doing something like:

import logging, subprocess
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

s = subprocess.Popen( ['ls','-la'], stdout=subprocess.PIPE )
while 1:
ch.info( s.stdout.readline() )
if s.poll() == None:
break

Perhaps not the most efficient or clean solution, but that is how I
usually do it (note: I didn't test the above code).

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


Re: tkinter, overwrite Label-text?

2008-04-10 Thread [EMAIL PROTECTED]
On Apr 10, 3:47 pm, [EMAIL PROTECTED] wrote:
> [...]
> i use the Label-widget.

Then you should be able to connect a variable to your widget like I
wrote in my previous post.
Just try out the example from the Python documentation. Of course in
your case entrythingy would be the
Label-widget. Take care to assign values to your variable by using the
set function.

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


https and POST method

2008-04-10 Thread Lorenzo Stella
Hi all,
I'm trying to write a simple script for sending sms via vyke... I have
to make a https
connection and pass some data with the POST method, like this perl
script does:

http://www.nutella.org/vyke.sms.txt

I tried to make the same, but it simply doesn't work! Any request
gives a 200 OK result... This is my code:

datah = {"act": "menulogin", "username": login, "password": passwd,
"menu_login_form": 1}
datas = urllib.urlencode(datah)
conn = httplib.HTTPSConnection("www.vyke.com")
conn.connect()
conn.request("POST", "/merchantsite/login.c?Distributor=MASKINA",
datas)
res = conn.getresponse()
print "login", res.status, res.reason
datah = {"act": "sendSMS", "from": numfrom, "to": numto, "message":
msg, "sms_form": 1}
datas = urllib.urlencode(datah)
conn.request("POST", "/merchantsite/sms.c", datas)
res = conn.getresponse()
print "send", res.status, res.reason
conn.request("GET", "/merchantsite/logout.c?Distributor=MASKINA")
res = conn.getresponse()
print "logout", res.status, res.reason
conn.close()

I don't know what to do! :-(
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter, overwrite Label-text?

2008-04-10 Thread skanemupp
On 10 Apr, 16:29, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On Apr 10, 3:47 pm, [EMAIL PROTECTED] wrote:
>
> > [...]
> > i use the Label-widget.
>
> Then you should be able to connect a variable to your widget like I
> wrote in my previous post.
> Just try out the example from the Python documentation. Of course in
> your case entrythingy would be the
> Label-widget. Take care to assign values to your variable by using the
> set function.
>
> Dennis Benzinger

i know how to do this already. the problem is i want the text to stay
in the windowa nd not start overwriting "Answer:".
i have solved this by using an Entry for the answer as well but id
prefer using a Label.


here is the code:

from __future__ import division
import Tkinter
from Tkinter import *

mygui = Tkinter.Tk()
mygui.title("Calculator")

l = Label(mygui, text="Answer: ")
l.place(relx=0.15, rely=0.2, anchor=CENTER)

e = Entry(mygui)
e.place(relx=0.4, rely=0.1, anchor=CENTER)

def Disp(nstr):
e.insert(END, nstr)

def Calc():
expr=e.get()
try:
b = Label(mygui, text=eval(expr))
b.place(relx=0.4, rely=0.2, anchor=CENTER)
except:
b = Label(mygui, text="Not computable")
b.place(relx=0.4, rely=0.2, anchor=CENTER)

def Erase():
e.delete(0,END)


x = 0.1
y = 0.4
for char in '123+456-789*0()/.':
b = Button(mygui, text=char, command=lambda n=char:Disp(n),
width=2, height=1)
b.place(relx=x, rely=y, anchor=CENTER)
x=x+0.1
if x==0.5:
x=0.1
y=y+0.1

b = Button(mygui, text="^", command=lambda n="**":Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.8, anchor=CENTER)
b = Button(mygui, text="C",command=Erase, width=2, height=1)
b.place(relx=0.3, rely=0.8, anchor=CENTER)
b = Button(mygui, text="=",command=Calc, width=2, height=1)
b.place(relx=0.4, rely=0.8, anchor=CENTER)

mygui.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: @x.setter property implementation

2008-04-10 Thread Floris Bruynooghe
On Apr 7, 2:19 pm, "Andrii V. Mishkovskyi" <[EMAIL PROTECTED]> wrote:
> 2008/4/7, Floris Bruynooghe <[EMAIL PROTECTED]>:
>
>
>
> >  Have been grepping all over the place and failed to find it.  I found
> >  the test module for them, but that doesn't get me very far...
>
> I think you should take a look at 'descrobject.c' file in 'Objects' directory.


Thanks, I found it!  So after some looking around here was my
implementation:

class myproperty(property):
def setter(self, func):
self.fset = func

But that doesn't work since fset is a read only attribute (and all of
this is implemented in C).

So I've settled with the (nearly) original proposal from Guido on
python-dev:

def propset(prop):
assert isinstance(prop, property)
@functools.wraps
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper

The downside of this is that upgrade from 2.5 to 2.6 will require code
changes, I was trying to minimise those to just removing an import
statement.

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


Re: urgent question, about filesystem-files

2008-04-10 Thread Rick King




Could you first find out if it exists with isfile(..) and then try to
open it? If it fails I *think*
it would have to be open by another process.

-Rick King

Southfield MI


bvidinli wrote:

  i started python programming a few months ago.

now i need the code to understand if a file already opened in
filesystem by another process ?

i looked at docs, howtos, but did not find related info.
note that normal file open/write operations in python, i know it.

i specificly need to know that "is a file already open by some other
process other than python".


Thank you in advance
  



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

Re: String Literal to Blob

2008-04-10 Thread Victor Subervi
Okay, here is where we find the fly in the ointment. If I run this code:

#! /usr/bin/python
import MySQLdb
print "Content-type: image/jpeg\r\n"
host = 'mysqldb2.ehost-services.com'
db = 'benobeno_bre'
user = 'benobeno'
passwd = '21122112'
connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cursor = connection.cursor()
cursor.execute('select pic1 from products where id="2";')
content = cursor.fetchall()[0][0]
content = content.tostring()
print content
f = open("2.jpg", "w")
f.write(content)
f.close()
all is well :) If, however, I change two lines to make it an html page:

#! /usr/bin/python
import MySQLdb
# print "Content-type: image/jpeg\r\n"
print "Content-type: text/html\n"
host = 'mysqldb2.ehost-services.com'
db = 'benobeno_bre'
user = 'benobeno'
passwd = '21122112'
connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cursor = connection.cursor()
cursor.execute('select pic1 from products where id="2";')
content = cursor.fetchall()[0][0]
content = content.tostring()
print '' % content
# print content
f = open("2.jpg", "w")
f.write(content)
f.close()
it prints garbage. It does not yield the image. Now, what?
TIA.
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: tkinter, overwrite Label-text?

2008-04-10 Thread [EMAIL PROTECTED]
On Apr 10, 4:37 pm, [EMAIL PROTECTED] wrote:
> [...]
> i know how to do this already. the problem is i want the text to stay
> in the windowa nd not start overwriting "Answer:".
> i have solved this by using an Entry for the answer as well but id
> prefer using a Label.
> [...]

You can set the width option of the Label. For example:

b = Label(mygui, text=eval(expr), width=20)

Then the Label will always be 20 characters wide no matter how long
the answer is.
You can read more about the options for Tk widgets in .

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


Python(x,y) - Free Python distribution for Scientists

2008-04-10 Thread Python(x,y) - Python for Scientists
Dear all,

The scientists among you may be interested in Python(x,y), a new
scientific-oriented Python distribution. This Python/Eclipse distribution
is freely available as a one-click Windows installer (a release for
GNU/Linux with similar features will follow soon):
http://www.pythonxy.com

Please do not hesitate to forward this announcement...

Thanks a lots,
PR

-- 
P. Raybaut
Python(x,y)
http://www.pythonxy.com

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


Re: PyArg_ParseTuple for structs or binary data

2008-04-10 Thread Alvin Delagon
Hello Gabriel,

I just recently discovered that struct.pack does return a string. Everything
works fine now. Thanks for the heads up!

static PyObject *
sendMessage(PyObject *self, PyObject *args)
{
  char *msg = "";
  int len;
  if (!PyArg_ParseTuple(args, "s#", &msg, &len))
return NULL;
  ret = sctp_sendmsg(connSock, msg, len, 0, 0, 0x0300, 0, 0x01, 0, 0);
  return Py_BuildValue("l", ret);
}


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

Re: Stripping scripts from HTML with regular expressions

2008-04-10 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 "Reedick, Andrew" <[EMAIL PROTECTED]> wrote:

> > -Original Message-
> > From: [EMAIL PROTECTED] [mailto:python-
> > [EMAIL PROTECTED] On Behalf Of Michel Bouwmans
> > Sent: Wednesday, April 09, 2008 3:38 PM
> > To: python-list@python.org
> > Subject: Stripping scripts from HTML with regular expressions
> > 
> > Hey everyone,
> > 
> > I'm trying to strip all script-blocks from a HTML-file using regex.
> > 
> 
> [Insert obligatory comment about using a html specific parser
> (HTMLParser) instead of regexes.]

Yah, seconded. To the OP - use BeautifulSoup or HtmlData unless you like 
to reinvent wheels.

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SWIG/C++

2008-04-10 Thread Matthieu Brucher
Hi,

The error is generated because you are asking for a u8*, but the buffer is
not a u8*, perhaps a char* or even a void*. If you change the method
signature to either char* or void*, it may work like you want it to ;)

Matthieu

2008/4/10, Bill Davy <[EMAIL PROTECTED]>:
>
> Is there a better place to post such questions?
>
> Anyway, in the hope it is something simple, I would appreciate some help.
>
> I am adding some C++ code to Python.  From Python I want to be able to
> read
> data from a target device, over USB.  My software does all the hard work
> and
> I have a class:
>
> class ViperUsbC
> {
> public:
> // snip snip
> ERROR_T ReadSlaveMemory(u8 Slave, u16 Offset, u8* pData, u16
> Length);
> // Snip,snip
> };
>
> I use swigwin-1.3.34 to wrap it into a module called SHIP.
>
> In Python, I have:
>
> import SHIP
> ViperUsb = SHIP.ViperUsbC()
> Slave =7
> Offset = 0
> Length = 64
> Buffer = 'a' * Length
> print "type(Buffer)=%s" % type(Buffer)
> print "len(Buffer)=%s" % len(Buffer)
> Result = ViperUsb.ReadSlaveMemory(Slave, Offset, Buffer, Length);
>
> That fails with:
>
> type(Buffer)=
> len(Buffer)=64
>
> Traceback (most recent call last):
>   File "H:\Husky\HostPC\V1\SHIP\test1.py", line 1970, in -toplevel-
> ViperTests()
>   File "H:\Husky\HostPC\V1\SHIP\test1.py", line 1884, in ViperTests
> Result = ViperUsb.ReadSlaveMemory(Slave, Offset, Buffer, Length);
>   File "H:\Husky\HostPC\V1\SHIP\Release\SHIP.py", line 1757, in
> ReadSlaveMemory
> def ReadSlaveMemory(*args): return
> _SHIP.ViperUsbC_ReadSlaveMemory(*args)
> TypeError: in method 'ViperUsbC_ReadSlaveMemory', argument 4 of type 'u8
> *'
>
>
> How do I provide a buffer into which to read the data?  It would not be
> intolerable to provide another layer using %extend, but I feel sure this
> should be automagic.
>
> Thanks in advance
> Bill
>
> PS This is a very small part of a much larger project so I cannot supply
> complete source code.
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Stripping scripts from HTML with regular expressions

2008-04-10 Thread Paul McGuire
On Apr 9, 2:38 pm, Michel Bouwmans <[EMAIL PROTECTED]> wrote:
> Hey everyone,
>
> I'm trying to strip all script-blocks from a HTML-file using regex.
>
> I tried the following in Python:
>
> testfile = open('testfile')
> testhtml = testfile.read()
> regex = re.compile(']*>(.*?)', re.DOTALL)
> result = regex.sub('', blaat)
> print result
>
> This strips far more away then just the script-blocks. Am I missing
> something from the regex-implementation from Python or am I doing something
> else wrong?
>
> greetz
> MFB

This pyparsing-based HTML stripper (http://pyparsing.wikispaces.com/
space/showimage/htmlStripper.py) strips *all* HTML tags, scripts, and
comments.  To pare down to just stripping scripts, just change this
line:

firstPass = (htmlComment | scriptBody | commonHTMLEntity |
 anyTag | anyClose ).transformString(targetHTML)

to:

firstPass = scriptBody.transformString(targetHTML)

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


Re: PyArg_ParseTuple for structs or binary data

2008-04-10 Thread Alvin Delagon
Hello Gabriel,

I just recently discovered that struct.pack does return a string. Everything
works fine now. Thanks for the heads up!

static PyObject *
sendMessage(PyObject *self, PyObject *args)
{
  char *msg = "";
  int len;
  if (!PyArg_ParseTuple(args, "s#", &msg, &len))
return NULL;
  ret = sctp_sendmsg(connSock, msg, len, 0, 0, 0x0300, 0, 0x01, 0, 0);
  return Py_BuildValue("l", ret);
}

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

Re: is Pylons alive?

2008-04-10 Thread Ville Vainio
On Apr 9, 2:25 pm, Mage <[EMAIL PROTECTED]> wrote:

> Before spending much time for investigating, I would like to ask you: is
> Pylons the framework I look for if I want to come back to Python and
> develop MVC web apps?

Why not play with Django and the Google App Engine that everyone is
raving about:

http://code.google.com/appengine/

Zope is also becoming a realistic choice now that it's getting easier
through Grok...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can C.L.P.handle the load?

2008-04-10 Thread Berco Beute
On Apr 9, 12:24 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Berco Beute <[EMAIL PROTECTED]> wrote:
> > On Apr 9, 7:54 am, Paddy <[EMAIL PROTECTED]> wrote:
> >> What else could we do to make c.l.p. of more use to the newbie whp may
> >> also be new to usenet whilst keeping c.l.p a usefull place for all?
>
> >> - Paddy.
>
> > Maybe create a usenet/google group for newbies? A place to ask
> > beginners questions. And post a sticky to c.l.p. redirecting newbies
> > (or experienced pythoneers with newbie questions :).
>
> Or just redirect them to the already existing 
> listhttp://mail.python.org/mailman/listinfo/tutor

I didn't know about that list. It would be nice to have that list
duplicated as a usenet/google group (just like c.l.p).

> What do you mean by 'post a sticky'? That sounds like a web forum thing.

It is. Using Google Groups some can post a post that stays on top. Not
sure if everybody would like that. :)

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


Re: subprocess.Popen() output to logging.StreamHandler()

2008-04-10 Thread Gerard Flanagan
On Apr 10, 2:11 pm, "sven _" <[EMAIL PROTECTED]> wrote:
> Version: Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)
>
> My goal is to have stdout and stderr written to a logging handler.
> This code does not work:
>
> # START
> import logging, subprocess
> ch = logging.StreamHandler()
> ch.setLevel(logging.DEBUG)
> subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
> # END
>
> Traceback (most recent call last):
>   File "log.py", line 5, in 
>subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
>   File "/usr/lib/python2.5/subprocess.py", line 443, in call
>return Popen(*popenargs, **kwargs).wait()
>   File "/usr/lib/python2.5/subprocess.py", line 586, in __init__
>errread, errwrite) = self._get_handles(stdin, stdout, stderr)
>   File "/usr/lib/python2.5/subprocess.py", line 941, in _get_handles
>c2pwrite = stdout.fileno()
> AttributeError: StreamHandler instance has no attribute 'fileno'
>
> This is because subprocess.Popen() expects file descriptors to write
> to, and logging.StreamHandler() does not supply it. The StreamHandler
> could supply its own stdout file descriptor, but then Popen() would
> write directly to that file, bypassing all the logging fluff.
>
> A possible solution would be to make a named pipe (os.mkfifo()), have
> Popen() write to that, and then have some horrendous hack run select()
> or similar on the fifo to read from it and finally pass it to
> StreamHandler.
>
> Are there better solutions?
>
> sven


When you create a StreamHandler, it is associated with a particular
stream, eg. sys.stdout.  So when you log an event, the handler picks
it up and writes it to the stream.  But you seem to think that the
reverse situation is true - when something is written to the stream
(from an arbitrary source) then the StreamHandler instance will pick
it up.  This isn't the case - it doesn't work both ways.

I think the only solution is to specifically log each line that you
get back from Popen, as suggested by Thomas Dimson.  You would perhaps
like something like the code below to work but it doesn't (well, it
runs, but the output of the subprocess call bypasses the
Streamhandler).  But then, maybe this is sufficient for you - as
you've seen, you can't set the stdout of the subprocess to the
StreamHandler, but you can set it to the Streamhandler's stream (if it
has a fileno) -

subprocess.call('svn info', stdout=ch.stream)
OR
subprocess.call('svn info', stdout=ch.stream.fileno())



import sys
import logging
import subprocess

ECHO_FORMAT = '%(levelname)-8s %(message)s'

class ReverseReverseStreamHandler(logging.StreamHandler):

def __init__(self, strm):
logging.StreamHandler.__init__(self, strm)
self.fileno = strm.fileno

def write(self, msg):
print 'This is never called!'
for line in msg.splitlines():
self.emit(logging.LogRecord(None, None, "", 0, line, (),
None, None))

root = logging.getLogger()

console = ReverseReverseStreamHandler(sys.stdout)

formatter = logging.Formatter(ECHO_FORMAT)
console.setFormatter(formatter)
root.addHandler(console)
root.setLevel(logging.DEBUG)

logging.info('-')

subprocess.call('svn info', stdout=console)

logging.info('-')



hth

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


RE: Stripping scripts from HTML with regular expressions

2008-04-10 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Michel Bouwmans
> Sent: Wednesday, April 09, 2008 5:44 PM
> To: python-list@python.org
> Subject: RE: Stripping scripts from HTML with regular expressions
> 
> 
> Thanks! That did the trick. :) I was trying to use HTMLParser but that
> choked on the script-blocks that didn't contain comment-indicators.
> Guess I
> can now move on with this script, thank you.
> 


S you asked for help with a regex workaround, but didn't ask for
help with the original problem, namely HTMLParser?  ;-)



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


Python conventions

2008-04-10 Thread MartinRinehart
I assembled a good conventions set for Java. View it at
http://www.martinrinehart.com/articles/code-conventions.html (is that
better, Steve?)

It followed a logical organization; it was built from four other
extensive (if not well-organized) convention sets and it scrupulously
avoided injecting my own biases. Where there were disagreements, they
were noted and the opposing viewpoints explained.

I'm appointing myself project secretary of a similar effort for
Python, until we can find someone better qualified (Python experience
pre-dating my late '07 start would be better qualified). The
secretary's job is to ask questions and correctly record answers.
First question:

global (e.g., what language for comments)
package
module
class
  methods
  data
function
statement
expression
variable

Is this a good outer-level organization?

For each topic, cover:

documentation
naming convention(s)
format

Second question: are the above the items we cover for each topic?
Others?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen() output to logging.StreamHandler()

2008-04-10 Thread Gerard Flanagan
On Apr 10, 5:34 pm, Gerard Flanagan <[EMAIL PROTECTED]> wrote:
> On Apr 10, 2:11 pm, "sven _" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Version: Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)
>
> > My goal is to have stdout and stderr written to a logging handler.
> > This code does not work:
>
[...]
> > Are there better solutions?
>
> > sven
>
> When you create a StreamHandler, it is associated with a particular
> stream, eg. sys.stdout.  So when you log an event, the handler picks
> it up and writes it to the stream.  But you seem to think that...

[snip didacticism]

Rereading your post, I think I've just told you what you already
knew...

Never mind.

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


Re: tkinter, overwrite Label-text?

2008-04-10 Thread Marc 'BlackJack' Rintsch
On Thu, 10 Apr 2008 07:37:08 -0700, skanemupp wrote:

> i know how to do this already. the problem is i want the text to stay
> in the windowa nd not start overwriting "Answer:".

Then don't use `place()` but let Tkinter handle the layout with the pack
and/or grid layout manager.  GUIs with `place()` are a bad idea because
the GUI may look odd or is even unusable on other peoples computers with
other screen resolutions, fonts, and font sizes.

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


Re: @x.setter property implementation

2008-04-10 Thread Arnaud Delobelle
On Apr 10, 3:37 pm, Floris Bruynooghe <[EMAIL PROTECTED]>
wrote:
> On Apr 7, 2:19 pm, "Andrii V. Mishkovskyi" <[EMAIL PROTECTED]> wrote:
>
> > 2008/4/7, Floris Bruynooghe <[EMAIL PROTECTED]>:
>
> > >  Have been grepping all over the place and failed to find it.  I found
> > >  the test module for them, but that doesn't get me very far...
>
> > I think you should take a look at 'descrobject.c' file in 'Objects' 
> > directory.
>
> Thanks, I found it!  So after some looking around here was my
> implementation:
>
> class myproperty(property):
>     def setter(self, func):
>         self.fset = func
>
> But that doesn't work since fset is a read only attribute (and all of
> this is implemented in C).
>
> So I've settled with the (nearly) original proposal from Guido on
> python-dev:
>
> def propset(prop):
>     assert isinstance(prop, property)
>     @functools.wraps
>     def helper(func):
>         return property(prop.fget, func, prop.fdel, prop.__doc__)
>     return helper
>
> The downside of this is that upgrade from 2.5 to 2.6 will require code
> changes, I was trying to minimise those to just removing an import
> statement.
>
> Regards
> Floris

Here's an implementation of prop.setter in pure python < 2.6, but
using sys._getframe, and the only test performed is the one below :)

import sys

def find_key(mapping, searchval):
for key, val in mapping.iteritems():
if val == searchval:
return key

_property = property

class property(property):
def setter(self, fset):
cls_ns = sys._getframe(1).f_locals
propname = find_key(cls_ns, self)
# if not propname: there's a problem!
cls_ns[propname] = property(self.fget, fset,
self.fdel, self.__doc__)
return fset
# getter and deleter can be defined the same way!

#  Example ---

class Foo(object):
@property
def bar(self):
return self._bar
@bar.setter
def setbar(self, x):
self._bar = '<%s>' % x

#  Interactive test -
>>> foo = Foo()
>>> foo.bar = 3
>>> foo.bar
'<3>'
>>> foo.bar = 'oeufs'
>>> foo.bar
''
>>>

Having fun'ly yours,

--
Arnaud

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


Re: How to find documentation about methods etc. for iterators

2008-04-10 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Terry Reedy <[EMAIL PROTECTED]> wrote:
| >
| > <[EMAIL PROTECTED]> wrote in message
| > news:[EMAIL PROTECTED]
| > | I'm not sure if I have even phrased that right but anyway
| > |
| > | How does one find (in the standard Python documentation) information
| > | about things like the iteritems() method and the enumerate() 
function.
| >
| > The Library Reference manual sections on builtin functions and dict
| > methods.
| >
| > Or, help(enumerate) and help({}.iteritems)
| >
|  but that doesn't address my problem really, how do I know that I
| need to look for the words enumerate and/or iteritems?  This is what
| my original question was about.

Do what Gabriel said: read chapters 2 and 3 of the Lib Manual.  You will 
not necessarily remember everything, but you will have an idea of what 
functionalities exist and know to go look again.  In a few months, read 
them again.

As for the stdlib, at least scan through the table of contents so you have 
a general idea of what there is.  The documentation of modules (as well as 
of builtins) is much improved from 10 years ago, when the only doc for some 
was the code.


tjr



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


Re: wrapping C functions in python

2008-04-10 Thread Ivan Illarionov
On Apr 10, 9:57 am, Paul Anton Letnes <[EMAIL PROTECTED]>
wrote:
[...]
>   , but as I mentioned, it seems to be a bit complicated to wrap heavy
> data structures like arrays.

Hello,

I suggest that you might take a look at how other people solved the
same problems. The great example is path.c inside PIL [1].
`PyPath_Flatten` function creates C array from Python data,
`path_to_list` converts C array into Python list and `path_map`
applies a Python function to C array.

Also take a look at Python buffer interface [2] - use array module on
Python side instead of lists and you'll have almost instant C arrays
from Python data and vice versa.

1: http://effbot.org/downloads/Imaging-1.1.6.tar.gz
2: http://docs.python.org/api/buffer-structs.html

Regards,

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


Tkinter: Entry, how to get INSERTpos?

2008-04-10 Thread skanemupp
in this function i want to be able to use the cursor and delete in the
middle of a number.
how do i get the value of anchor or insert?
i want to write:
e.delete(pos-1,pos)

def Backspace():
a=len(e.get())
e.delete(a-1,END)
#e.delete(INSERT, END)
#e.delete(ANCHOR,END)

the complete program:

from __future__ import division
import Tkinter
from Tkinter import *

mygui = Tkinter.Tk()

mygui.title("Calculator")

l = Label(mygui, text="Answer: ")
l.place(relx=0.15, rely=0.2, anchor=CENTER)

e = Entry(mygui)
e.place(relx=0.48, rely=0.1, anchor=CENTER, width=173)

c = Entry(mygui)
c.place(relx=0.6, rely=0.2, anchor=CENTER)

def Disp(nstr):
e.insert(INSERT, nstr)

def Calc():
expr=e.get()
c.delete(0, END)
try:
c.insert(END, eval(expr))
except:
c.insert(END, "Not computable")

def Erase():
e.delete(0,END)
c.delete(0, END)

def Backspace():
a=len(e.get())
e.delete(a-1,END)
#e.delete(INSERT, END)
#e.delete(ANCHOR,END)


x = 0.1
y = 0.4
for char in '123+456-789*0()/.':
b = Button(mygui, text=char, command=lambda n=char:Disp(n),
width=2, height=1)
b.place(relx=x, rely=y, anchor=CENTER)
x=x+0.1
if x==0.5:
x=0.1
y=y+0.1

b = Button(mygui, text="^", command=lambda n="**":Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.8, anchor=CENTER)
b = Button(mygui, text="C",command=Erase, width=2, height=1)
b.place(relx=0.3, rely=0.8, anchor=CENTER)
b = Button(mygui, text="c",command=Backspace, width=2, height=1)
b.place(relx=0.4, rely=0.8, anchor=CENTER)
b = Button(mygui, text="=",command=Calc, width=12, height=1)
b.place(relx=0.25, rely=0.9, anchor=CENTER)

mygui.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter, resize window, keep widgets relative placements?

2008-04-10 Thread skanemupp
the code is down below. when i click maximize window it looks terrible
since the widgets are not keeping their relative size.
i guess i could use pack or grid to do that instead of place?
but i tried with pack and grid before and had trouble making it
looking good.

is it possible to have the minimized window just being placed in the
middle without the distance between the buttons and entrys being
enlonge>?


from __future__ import division
import Tkinter
from Tkinter import *

mygui = Tkinter.Tk()

mygui.title("Calculator")

l = Label(mygui, text="Answer: ")
l.place(relx=0.15, rely=0.2, anchor=CENTER)

e = Entry(mygui)
e.place(relx=0.48, rely=0.1, anchor=CENTER, width=173)

c = Entry(mygui)
c.place(relx=0.6, rely=0.2, anchor=CENTER)

def Disp(nstr):
e.insert(INSERT, nstr)

def Calc():
expr=e.get()
c.delete(0, END)
try:
c.insert(END, eval(expr))
except:
c.insert(END, "Not computable")

def Erase():
e.delete(0,END)
c.delete(0, END)

def Backspace():
a=len(e.get())
e.delete(a-1,END)
#e.delete(INSERT, END)
#e.delete(ANCHOR,END)


x = 0.1
y = 0.4
for char in '123+456-789*0()/.':
b = Button(mygui, text=char, command=lambda n=char:Disp(n),
width=2, height=1)
b.place(relx=x, rely=y, anchor=CENTER)
x=x+0.1
if x==0.5:
x=0.1
y=y+0.1

b = Button(mygui, text="^", command=lambda n="**":Disp(n), width=2,
height=1)
b.place(relx=0.2, rely=0.8, anchor=CENTER)
b = Button(mygui, text="C",command=Erase, width=2, height=1)
b.place(relx=0.3, rely=0.8, anchor=CENTER)
b = Button(mygui, text="c",command=Backspace, width=2, height=1)
b.place(relx=0.4, rely=0.8, anchor=CENTER)
b = Button(mygui, text="=",command=Calc, width=12, height=1)
b.place(relx=0.25, rely=0.9, anchor=CENTER)

mygui.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Cyclic relative imports don't work

2008-04-10 Thread Torsten Bronger
Hallöchen!

Assume the follwing package structure:

main.py
package/
__init__.py   [empty]
moduleX.py
moduleY.py

main.py says:

from package import moduleX

moduleX.py says:

from . import moduleY

and moduleY.py says:

from . import moduleX

However, this doesn't work:

[EMAIL PROTECTED]:~/temp/packages-test$ python main.py
Traceback (most recent call last):
  File "main.py", line 1, in 
from package import moduleX
  File "/home/bronger/temp/packages-test/package/moduleX.py", line 1, in 

from . import moduleY
  File "/home/bronger/temp/packages-test/package/moduleY.py", line 1, in 

from . import moduleX
ImportError: cannot import name moduleX

If I turn the relative imports to absolute ones, it works.  But I'd
prefer the relative notation for intra-package imports.  Why is this
restriction?

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How is GUI programming in Python?

2008-04-10 Thread Peter Decker
On Wed, Apr 9, 2008 at 8:54 PM, Chris Stewart <[EMAIL PROTECTED]> wrote:

> I've always had an interest in Python and would like to dabble in it
>  further.  I've worked on a few very small command line programs but
>  nothing of any complexity.  I'd like to build a really simple GUI app
>  that will work across Mac, Windows, and Linux.  How painful is that
>  going to be?  I used to be really familiar with Java Swing a few years
>  ago.  I imagine it will be similar.
>
>  Next, what would you say is the best framework I should look into?
>  I'm curious to hear opinions on that.

I've found wxPython to be the best all-around choice: it looks right
on Mac, Win and Gtk/Linux, as it uses native controls. The one
downside is that its C++ roots show, and make for somewhat ugly and
unPythonic code.

I've been using the Dabo framework (http://dabodev.com) for over a
year now, and it's great. They use wxPython for the UI, but wrap it in
a consistent and intelligent layer that makes development much simpler
and straightforward.


-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Literal to Blob

2008-04-10 Thread Steve Holden
Victor Subervi wrote:
> Okay, here is where we find the fly in the ointment. If I run this code:
>  
> #! /usr/bin/python
> import MySQLdb
> print "Content-type: image/jpeg\r\n"
> host = 'mysqldb2.ehost-services.com '
> db = 'benobeno_bre'
> user = 'benobeno'
> passwd = '21122112'
> connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
> cursor = connection.cursor()
> cursor.execute('select pic1 from products where id="2";')
> content = cursor.fetchall()[0][0]
> content = content.tostring()
> print content
> f = open("2.jpg", "w")
> f.write(content)
> f.close()
> all is well :) If, however, I change two lines to make it an html page:
>  
> #! /usr/bin/python
> import MySQLdb
> # print "Content-type: image/jpeg\r\n"
> print "Content-type: text/html\n"
> host = 'mysqldb2.ehost-services.com '
> db = 'benobeno_bre'
> user = 'benobeno'
> passwd = '21122112'
> connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
> cursor = connection.cursor()
> cursor.execute('select pic1 from products where id="2";')
> content = cursor.fetchall()[0][0]
> content = content.tostring()
> print '' % content
> # print content
> f = open("2.jpg", "w")
> f.write(content)
> f.close()
> it prints garbage. It does not yield the image. Now, what?
> TIA.
> Victor
> 
Of course it prints garbage. Since you claim to understand HTML I have 
no idea what makes you expect that it would print anything else. That's 
because you are sending garbage to the browser instead of the HTML your 
content type promises.

THE VALUE OF THE IMG TAG'S SRC ATTRIBUTE SHOULD BE THE URL OF AN IMAGE< 
NOT THE IMAGE ITSELF. Sorry, I don't normally shout like that. So pay 
attention when I do.

First let's agree that what you are writing here is a web script to 
return an image, NOT a web page with an embedded image. So ...

Now you formulate a correct response instead. You should NOT be 
returning a content type of text/html here, you should be returning a 
content type of image/jpeg. So your code should read

#! /usr/bin/python
import MySQLdb
print "Content-type: image/jpeg\r\n"
host = 'mysqldb2.ehost-services.com'
db = 'benobeno_bre'
user = 'benobeno'
passwd = '21122112'
connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cursor = connection.cursor()
cursor.execute('select pic1 from products where id="2";')
content = cursor.fetchall()[0][0]
content = content.tostring()
print content

If you then direct your browser to the correct URL to access the output 
of this script you will see your image.

When you want to see your image in the context of some HTML, write 
*another page* and you put the URL of the image inside it like this:

   

as a reference to the image your script returns.

I think you are on your own from here. If you follow instructions you 
should not need any further help.

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

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


class

2008-04-10 Thread Arun ragini
Hi,

I have create a class file named Mysqldb.py

class Mysqldb:
def __init__(self, name):
#this where it tries to connect to database
self.ip = ip
print "Inializing session for name"

def test(self):
print "worked"

-

now i'm trying initialize this another python file called  session.py

import Mysqldb

def session():
  Sess = Mysqldb ("localbox")


when i try to run in using python session.py.

i get error message
TypeError: 'module' object is not callable

can any 1 help me on this.

Thanks & Regards
Arun


-- 
-
Fight back spam! Download the Blue Frog.
http://www.bluesecurity.com/register/s?user=YXJ1bnJhZ2luaQ%3D%3D
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How is GUI programming in Python?

2008-04-10 Thread Michel Bouwmans
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Paul Rubin wrote:

> Chris Stewart <[EMAIL PROTECTED]> writes:
>> I've always had an interest in Python and would like to dabble in it
>> further.  I've worked on a few very small command line programs but
>> nothing of any complexity.  I'd like to build a really simple GUI app
>> that will work across Mac, Windows, and Linux.  How painful is that
>> going to be?  I used to be really familiar with Java Swing a few years
>> ago.  I imagine it will be similar.
>> ...
>> Next, what would you say is the best framework I should look into?
> 
> If by "best" you mean "easiest", that is probably tkinter, which
> comes with python.  It is somewhat rudimentary and the widgets that
> come with it don't look so great.  But if you just want to put up
> GUI's with basic functionality and not much glitz, it is ok for most
> such purposes.
> out how to use

I don't quite agree with you on this. Tkinter may be easy because it is
available by standard in Python, but that's about it in my opinion. The
API, look and performance hit is horrible. You're much better of with PyQt4
which makes the job really simple.

MFB
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQFH/kjhDpaqHmOKFdQRAj+kAJ0d3aHqpv/mh7kSqtDqUFXtJsxi1gCfU5UP
2Ygw9ttRIYX+ioMyBVUNsVo=
=stR5
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Data structure recommendation?

2008-04-10 Thread Jochen Schulz
* [EMAIL PROTECTED]:
> 
> Please plug such good things. It seems the Python community is an
> endless source of interesting modules I didn't know about. Your
> (single) module looks very nice. I'll take a better look later.

Could you please send me an email with an existing From: address? I
tried to reply to you but apparently your From: is forged.

J.
-- 
I can tell a Whopper[tm] from a BigMac[tm] and Coke[tm] from Pepsi[tm].
[Agree]   [Disagree]
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Graphs in Python

2008-04-10 Thread Sanhita Mallick
Hi.

I am a newbie to Python. I am trying to implement a
Python code for graph manipulation. My graphs are
about 200-500 nodes big. Excepting for the short basic
graph implementation info on Python.org, where can I
find more in depth info about how to express graphs in
python, and how to use them in a  code?

Also, does anyone know of a easy way of creating the
dictionary for python for a 500-node graph, without
typing each and every node? I found some application
that recognize dot file Graphviz - but I am looking
for a program that can let me "draw" a graph and then
generate the lists automatically from the drawing.

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


Re: Python conventions

2008-04-10 Thread Daniel Fetchinson
> I assembled a good conventions set for Java. View it at
> http://www.martinrinehart.com/articles/code-conventions.html (is that
> better, Steve?)
>
> It followed a logical organization; it was built from four other
> extensive (if not well-organized) convention sets and it scrupulously
> avoided injecting my own biases. Where there were disagreements, they
> were noted and the opposing viewpoints explained.
>
> I'm appointing myself project secretary of a similar effort for
> Python, until we can find someone better qualified (Python experience
> pre-dating my late '07 start would be better qualified). The
> secretary's job is to ask questions and correctly record answers.
> First question:
>
> global (e.g., what language for comments)
> package
> module
> class
>   methods
>   data
> function
> statement
> expression
> variable
>
> Is this a good outer-level organization?
>
> For each topic, cover:
>
> documentation
> naming convention(s)
> format
>
> Second question: are the above the items we cover for each topic?
> Others?


I'm sorry to disappoint you but this project has already been completed:

http://www.python.org/dev/peps/pep-0008/

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


Re: subprocess.Popen() output to logging.StreamHandler()

2008-04-10 Thread Vinay Sajip
On Apr 10, 1:11 pm, "sven _" <[EMAIL PROTECTED]> wrote:
> Version: Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)
>
> My goal is to have stdout and stderr written to alogginghandler.
> This code does not work:
>
> # START
> importlogging, subprocess
> ch =logging.StreamHandler()
> ch.setLevel(logging.DEBUG)
> subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
> # END
>
> Traceback (most recent call last):
>   File "log.py", line 5, in 
>subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
>   File "/usr/lib/python2.5/subprocess.py", line 443, in call
>return Popen(*popenargs, **kwargs).wait()
>   File "/usr/lib/python2.5/subprocess.py", line 586, in __init__
>errread, errwrite) = self._get_handles(stdin, stdout, stderr)
>   File "/usr/lib/python2.5/subprocess.py", line 941, in _get_handles
>c2pwrite = stdout.fileno()
> AttributeError: StreamHandler instance has no attribute 'fileno'
>
> This is because subprocess.Popen() expects file descriptors to write
> to, andlogging.StreamHandler() does not supply it. The StreamHandler
> could supply its own stdout file descriptor, but then Popen() would
> write directly to that file, bypassing all theloggingfluff.
>
> A possible solution would be to make a named pipe (os.mkfifo()), have
> Popen() write to that, and then have some horrendous hack run select()
> or similar on the fifo to read from it and finally pass it to
> StreamHandler.
>
> Are there better solutions?
>
> sven

Thomas was almost right, but not quite - you can't call info on a
Handler instance, only on a Logger instance. The following script:

import logging
import subprocess

logging.basicConfig(level=logging.INFO) # will log to stderr of this
script

s = subprocess.Popen( ['ls','-la'], stdout=subprocess.PIPE )
while 1:
line = s.stdout.readline()
exitcode = s.poll()
if (not line) and (exitcode is not None):
break
line = line[:-1]
logging.info("%s", line)

produces the following output:

INFO:root:total 204
INFO:root:drwxr-xr-x 35 vinay vinay 4096 2008-04-10 18:06 .
INFO:root:drwxr-xr-x  3 root  root  4096 2008-03-22 07:09 ..
INFO:root:-rw---  1 vinay vinay  685 2008-04-10
17:26 .bash_history
INFO:root:-rw-r--r--  1 vinay vinay  220 2008-03-22 07:09 .bash_logout
INFO:root:-rw-r--r--  1 vinay vinay 2327 2008-03-22 07:09 .bashrc
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-04-05 02:21 .bluefish
INFO:root:drwxr-xr-x  3 vinay vinay 4096 2008-03-22 07:18 .cache
INFO:root:drwxr-xr-x  5 vinay vinay 4096 2008-03-22 07:32 .config
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-03-22 07:17 Desktop
INFO:root:-rw---  1 vinay vinay   28 2008-04-10 00:33 .dmrc
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-03-22 07:17 Documents
INFO:root:-rw---  1 vinay vinay   16 2008-03-22 07:17 .esd_auth
INFO:root:lrwxrwxrwx  1 vinay vinay   26 2008-03-22 07:09 Examples -> /
usr/share/example-content
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-04-10 00:21 .fontconfig
INFO:root:drwx--  4 vinay vinay 4096 2008-04-10 17:23 .gconf
INFO:root:drwx--  2 vinay vinay 4096 2008-04-10 17:43 .gconfd
INFO:root:-rw-r-  1 vinay vinay0 2008-03-24 19:13 .gksu.lock
INFO:root:drwx--  9 vinay vinay 4096 2008-04-10 00:31 .gnome2
INFO:root:drwx--  2 vinay vinay 4096 2008-03-22
07:17 .gnome2_private
INFO:root:drwx--  2 vinay vinay 4096 2008-04-10 00:33 .gnupg
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-04-10
00:33 .gstreamer-0.10
INFO:root:-rw-r--r--  1 vinay vinay  108 2008-04-10 00:33 .gtk-
bookmarks
INFO:root:dr-x--  2 vinay vinay0 2008-04-10 00:33 .gvfs
INFO:root:-rw---  1 vinay vinay  167 2008-04-10
00:33 .ICEauthority
INFO:root:drwxr-xr-x  3 vinay vinay 4096 2008-03-22 07:18 .local
INFO:root:drwx--  3 vinay vinay 4096 2008-03-22 07:18 .metacity
INFO:root:drwx--  4 vinay vinay 4096 2008-03-24 19:13 .mozilla
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-03-22 07:17 Music
INFO:root:drwxr-xr-x  3 vinay vinay 4096 2008-04-10 00:31 .nautilus
INFO:root:drwxr-xr-x  3 vinay vinay 4096 2008-04-05 02:09 .netbeans
INFO:root:drwxr-xr-x  3 vinay vinay 4096 2008-04-05 02:09 .netbeans-
registration
INFO:root:drwx--  3 vinay vinay 4096 2008-04-05
02:15 .openoffice.org2
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-03-22 07:17 Pictures
INFO:root:-rw-r--r--  1 vinay vinay  566 2008-03-22 07:09 .profile
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-03-22 07:17 Public
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-03-22 08:01 .pulse
INFO:root:-rw---  1 vinay vinay  256 2008-03-22 07:17 .pulse-
cookie
INFO:root:-rw-r--r--  1 vinay vinay 1973 2008-04-10 18:06 .recently-
used.xbel
INFO:root:drwx--  2 vinay vinay 4096 2008-03-22 07:17 .ssh
INFO:root:drwxr-xr-x  3 vinay vinay 4096 2008-04-05 02:09 .subversion
INFO:root:-rw-r--r--  1 vinay vinay0 2008-03-22
07:34 .sudo_as_admin_successful
INFO:root:drwxr-xr-x  4 vinay vinay 4096 2008-03-22 09:10 .sudoku
INFO:root:drwxr-xr-x  2 vinay vinay 4096 2008-03-22 07:17 Templates
INFO:root:-rw-r--r--  1 vi

Re: How is GUI programming in Python?

2008-04-10 Thread Paul Rubin
Michel Bouwmans <[EMAIL PROTECTED]> writes:
> > If by "best" you mean "easiest", that is probably tkinter, 

> I don't quite agree with you on this. Tkinter may be easy because it is
> available by standard in Python, but that's about it in my opinion. The
> API, look and performance hit is horrible. You're much better of with PyQt4
> which makes the job really simple.

Well, it's a trade-off, the person wanted a cross platform gui and the
#1 hurdle for something like PyQt4 is getting it to work on each of
the platforms you desire to run on.  With tkinter, that has already
been done.  I can walk up to any Linux, Windows, Mac, etc. box where
Python is installed and put up a simple tkinter gui in under a minute.
With anything else, I'm in installation hell for some indeterminate
amount of time before I can put up "hello world", especially if I
insist on installing from source (the alternative is accepting
binaries from yet another third party, like handing out more and more
keys to your house).  

I agree with you that tkinter gui's don't look as slick as PyQt4 etc.
Whether that's important depends on your application's requirements.
For what I've done with it so far, it's been good enough.  I haven't
compared the Python API's but have used some other gui toolokts on
other platforms and tkinter seems comparable to the others in ease of
use.  I hadn't really thought about performance for something like a
gui, though I guess it could matter for certain types of apps.

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


RE: Stripping scripts from HTML with regular expressions

2008-04-10 Thread Michel Bouwmans
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Reedick, Andrew wrote:

>> -Original Message-
>> From: [EMAIL PROTECTED] [mailto:python-
>> [EMAIL PROTECTED] On Behalf Of Michel Bouwmans
>> Sent: Wednesday, April 09, 2008 5:44 PM
>> To: python-list@python.org
>> Subject: RE: Stripping scripts from HTML with regular expressions
>> 
>> 
>> Thanks! That did the trick. :) I was trying to use HTMLParser but that
>> choked on the script-blocks that didn't contain comment-indicators.
>> Guess I
>> can now move on with this script, thank you.
>> 
> 
> 
> S you asked for help with a regex workaround, but didn't ask for
> help with the original problem, namely HTMLParser?  ;-)
> 
> 
> 
> *
> 
> The information transmitted is intended only for the person or entity to
> which it is addressed and may contain confidential, proprietary, and/or
> privileged material. Any review, retransmission, dissemination or other
> use of, or taking of any action in reliance upon this information by
> persons or entities other than the intended recipient is prohibited. If
> you received this in error, please contact the sender and delete the
> material from all computers. GA625

I don't think HTMLParser was doing anything wrong here. I needed to parse a
HTML document, but it contained script-blocks with document.write's in
them. I only care for the content outside these blocks but HTMLParser will
choke on such a block when it isn't encapsulated with HTML-comment markers
and it tries to parse the contents of the document.write's. ;)

MFB
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQFH/kvEDpaqHmOKFdQRAgHgAJ4s2YUN6yynUS+8aunhVUR94rs2yQCgrn94
tAFx/dylzEI0TclRDSTRbJI=
=k8SN
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


get array element

2008-04-10 Thread [EMAIL PROTECTED]
I have an array, and I would like to get the indice value.

a = array([13,14,15,16])

I would like something like a.getindice(15)

If I want 15 it would return 2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, resize window, keep widgets relative placements?

2008-04-10 Thread skanemupp
here i didi it with pack() but when i try to use the answerwidget it
gtes all f* up. any suggestions?


from __future__ import division
import Tkinter
from Tkinter import *

mygui = Tkinter.Tk()

mygui.title("Calculator")

##l = Label(mygui, text="Answer: ")
##l.grid(row=2, column=1, columnspan=2)

e = Entry(mygui)
e.grid(row=1, column=1, columnspan=4)

c = Entry(mygui)
c.grid(row=2, column=1, columnspan=4)

def Disp(nstr):
e.insert(INSERT, nstr)

def Calc():
expr=e.get()
c.delete(0, END)
try:
c.insert(END, eval(expr))
except:
c.insert(END, "Not computable")

def Erase():
e.delete(0,END)
c.delete(0, END)

def Backspace():
a=len(e.get())
e.delete(a-1,END)
#e.delete(INSERT, END)
#e.delete(ANCHOR,END)


x = 1
y = 4
for char in '123+456-789*0()/.':
b = Button(mygui, text=char, command=lambda n=char:Disp(n),
width=2, height=1)
b.grid(row=y, column=x)
x=x+1
if x==5:
x=1
y=y+1

b = Button(mygui, text="^", command=lambda n="**":Disp(n), width=2,
height=1)
b.grid(row=8, column=2)
b = Button(mygui, text="C",command=Erase, width=2, height=1)
b.grid(row=8, column=3)
b = Button(mygui, text="c",command=Backspace, width=2, height=1)
b.grid(row=8, column=4)
b = Button(mygui, text="=",command=Calc, width=18, height=1)
b.grid(row=9, column=1, columnspan=8)

mygui.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How is GUI programming in Python?

2008-04-10 Thread Mike Driscoll
On Apr 10, 12:05 pm, Michel Bouwmans <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
>
>
> Paul Rubin wrote:
> > Chris Stewart <[EMAIL PROTECTED]> writes:
> >> I've always had an interest in Python and would like to dabble in it
> >> further.  I've worked on a few very small command line programs but
> >> nothing of any complexity.  I'd like to build a really simple GUI app
> >> that will work across Mac, Windows, and Linux.  How painful is that
> >> going to be?  I used to be really familiar with Java Swing a few years
> >> ago.  I imagine it will be similar.
> >> ...
> >> Next, what would you say is the best framework I should look into?
>
> > If by "best" you mean "easiest", that is probably tkinter, which
> > comes with python.  It is somewhat rudimentary and the widgets that
> > come with it don't look so great.  But if you just want to put up
> > GUI's with basic functionality and not much glitz, it is ok for most
> > such purposes.
> > out how to use
>
> I don't quite agree with you on this. Tkinter may be easy because it is
> available by standard in Python, but that's about it in my opinion. The
> API, look and performance hit is horrible. You're much better of with PyQt4
> which makes the job really simple.
>
> MFB
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.7 (GNU/Linux)
>
> iD8DBQFH/kjhDpaqHmOKFdQRAj+kAJ0d3aHqpv/mh7kSqtDqUFXtJsxi1gCfU5UP
> 2Ygw9ttRIYX+ioMyBVUNsVo=
> =stR5
> -END PGP SIGNATURE-

I see a lot of people recommend using pyQt, but they never mention the
controversy that surrounds its licensing. There have been many posts
on the subject already, but if the OP ever decides to sell anything
they create, I've heard that QT's licensing is kind of squirrelly.
Maybe this has been straightened out?

I looked at the website and found it fairly confusing. And don't you
need to download QT itself?

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


Re: Module Conflicts

2008-04-10 Thread Jose
On Apr 9, 10:36 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> On Apr 9, 5:33 pm, Jose <[EMAIL PROTECTED]> wrote:
>
> > I have a module named math.py in a package with some class
> > definitions.  I am trying to import the standard python math module
> > inside of math.py but It seems to be importing itself.  Is there any
> > way around this problem without renaming my math.py file?
>
> Not without some unpythonic magic. It's really not good style to name
> a module the same as a stdlib one. It'll also confuse people reading
> your code.

Yeah but I thought since math.py was in a package, it would be okay.
It's no big deal.  I'll just rename my module :(
-- 
http://mail.python.org/mailman/listinfo/python-list


from __future__ import print

2008-04-10 Thread [EMAIL PROTECTED]
Am I the only one that thinks this would be useful?  :)

I'd really like to be able to use python 3.0's print statement in
2.x.  Is this at least being considered as an option for 2.6?  It
seems like it would be helpful with transitioning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PROBLEMS WITH PYTHON IN SOME VARIABLE,FUNCTIONS,ETC.

2008-04-10 Thread John Nagle
[EMAIL PROTECTED] wrote:
> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.
> 1310 32 bit (Intel)] on win32 with IDLE 1.2.1
> My O/S is Windows XP SP2 I use 512 MB RAM.
> I am encountering the following problems:
> (i) a1=1
> a2=2
> a3=a1+a2
> print a3
> # The result is coming sometimes as 3 sometimes as vague numbers.

 Are you pasting that code into IDLE with cut and paste?
IDLE doesn't process multiple-line paste operations properly,
and usually ignores all lines after the first.  When it does
this, it does not produce an error message.  That may be
your first problem.

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


Re: String Literal to Blob

2008-04-10 Thread Victor Subervi
Well, what I did was this:

content = col_fields[0][14].tostring()
pic = "tmp" + str(i) + ".jpg"
img = open(pic, "w")
img.write(content)
print '' % pic
img.close()
where I am incrementing i. Ugly. Stupid. But if it is the only way to do it
in python, and I do not want to invest the time doing it in php, which I
think would be prettier in this instance, then I guess it will do. Your
thoughts appreciated.
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >