Re: eof

2007-11-21 Thread Wayne Brehaut
On Wed, 21 Nov 2007 17:06:15 -0800 (PST), braver
<[EMAIL PROTECTED]> wrote:

>On Nov 22, 3:41 am, Wayne Brehaut <[EMAIL PROTECTED]> wrote:
>> If you have PythonWin 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310
>> 32 bit (Intel)] on win32.for example, using Help, Index, eof gives:
>>

8< ===

>
> HTH?

>Nope!  I don't want to buffer input myself, and don't want to store
>look-ahead and push it back.  f.read()/readline() is not a non-
>destructive check, and thus won't do.

Your original statement was: "I'd like to check, for a filehandle f,
that EOF has been reached on it." You now appear to be "upping the
ante" as though you're more interested in attacking what you perceive
as an omission in Python than in doing what you originally stated.

>Well folks compare scripting languages all the time, and surely Ruby
>is closer to Python than C++.  

If I  didn't abhor smileys and text substitutes you might have caught
on that this was partly "just kidding", but not completely: since
Python is implemented in C/C++ it makes perfect sense to see what's
readily available there that might account for how one would do it in
Python if he really thought it necessary. (As others have noted, it's
not necessary.)

So what Python is "closer to" is not the point--and there's no
standard way of measuring that that I know of?

>Since Ruby can do f.eof, which is
>easily found in its references, and Python can't, or its EOF can't
>easily be found -- the one *equivalent* to a semantically clear
>Ruby's, or Pascal's IIRC, f.eof -- something's missing here...
>Why do I have to count sizes of lines read and compare it to some
>filesize 

Why would you think that it's you doing the counting? If you insist,
write your own trivial eof() and call it so you won't have to fret
about how it's discovering whether you're at EOF.

>or do other weird tricks just to see, in a way not changing
>my input stream, whether it's at the, well, EOF?

As others have already pointed out, "because it's seldom necessary in
Python". If you really think you need to do it the way you're implying
in Python, you're probably mistaken. You should do it the pythonic way
instead of complaining about not finding the exact equivalent to how
you would do it in some other language. 

"Python is not Ruby."

wwwayne


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


Re: having problem using xlrd

2007-11-21 Thread Kelie
FYI, this question has been answered in python-excel group. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the function to evaluate code object returned byPyParser _SimpleParseString function?

2007-11-21 Thread grbgooglefan
On Nov 16, 7:11 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Borse, Ganesh" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | Py_CompileString takes the sourcecodefrom file, isn't it?
>
> No.
>
> | As can be seen from the syntax of thisfunction: "PyObject*
> Py_CompileString(char *str, char *filename, int start)"
>
> I am rather sure that the filename param is the same as for the
> Python-level builtinfunctioncompile:
>   compile( string, filename, kind[, flags[, dont_inherit]])
>
> Compile the string into acodeobject.Codeobjects can be executed by an
> exec statement or evaluated by acallto eval(). The filename argument
> should give the file from which thecodewas read; pass some recognizable
> value if it wasn't read from a file ('' is commonly used).
>
> The filename is used for exception traceback messages.

Hi,
I want to put this code in a function & call it.
I am now facing a problem that, I am able to compile a function using
Py_CompileString. That generates a "*definition*" of that function.
I am stuck at a road block & not able to execute this function
definition which is part of "*codeObject*" returned by
Py_CompileString.

What should I do to transform this 'code' object to 'callable' or
'function' object, so that I can call it?

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


Please help in creating Python function in C ++ program

2007-11-21 Thread gagsl-py2
Forwarded to python-list@python.org

--- "Borse, Ganesh" <[EMAIL PROTECTED]>
escribió:

> Hi,
> 
> I am new to Python. I would like to use Python for
> the specialized purpose of dynamic expressions
> parsing & evaluation in my C++ application.
> I would like to encapsulate the expressions to be
> evaluated in Python function & compile that function
> at runtime, somewhat as below.
>   Expression to eval put in Python function 
>   def isSizeSmall(size,vol,ADV,prod):
> if ( (size < 1000) & (vol < (0.001 * ADV)) &
> (prod=="Stock")): print "OK"; return 10
> else: print "NOK"; return 11
> 
> Then, I want to evaluate the PyObject returned by
> Py_CompileString multiple times in my program using
> the user input as the variables to the above
> function.
> This I tried using two different approaches - 1)
> PyEval_evalCode, & 2) PyObject_CallObject.
> 
> 1) When using PyEval_evalCode: The function call to
> PyEval_evalCode was ok, but it did not return any
> output.
> 2) Whereas, when I used this object with
> PyObject_CallObject, it failed with error as "".
> 
> Any help will be great. Many thanks in advance for
> your help.
> 
> Warm Regards,
> Ganesh
> 
> //***//
> Output of my test program:
> Expression to eval = 
> [def isSizeSmall(size,vol,ADV,prod):
>   if ( (size < 1000) & (vol < (0.001 * ADV)) &
> (prod=="Stock")): print "OK"; return 10
>   else: print "NOK"; return 11
> 
> ]
> str compiled fine with stdin & Py_file_input,
> calling PyEval_EvalCode
> None ok [0] size [-1]
> 
> str compiled fine with stdin & Py_file_input,
> calling PyFunction_New & then PyObject_CallObject
> Getting PyFunction_New
> Calling PyObject_CallObject
> func is callable
> TypeError: ?() takes no arguments (4 given)
> 
> My test program having both above approaches is as
> below:
> main(int argc, char **argv)
> {
>/* Pass argv[0] to the Python interpreter */
>Py_SetProgramName(argv[0]);
>/* Initialize the Python interpreter.  Required.
> */
>Py_Initialize();
>PyRun_SimpleString("import sys\n");
> 
>char szExpr[2048];
>memset(szExpr,'\0',sizeof(szExpr));
>sprintf(szExpr,"def
> isSizeSmall(size,vol,ADV,prod):\n  if ( (size <
> 1000) & (vol < (0.001 * ADV)) & (prod==\"Stock\")):
> print \"OK\"; return 10\n  else: print \"NOK\";
> return 11\n\n\n");
> 
>printf("Expression to eval = \n[%s]\n",szExpr);
> 
>OrderValues ordval;
>ordval.size = 100;
>ordval.ADV  = 10;
>ordval.vol  = 1000;
>memset(ordval.prod,'\0',sizeof(ordval.prod));
>sprintf(ordval.prod,"Stock");
> 
> 
>PyObject *glb, *loc;
> 
>glb = PyDict_New();
>PyDict_SetItemString(glb, "__builtins__",
> PyEval_GetBuiltins());
> 
>loc = PyDict_New();
> 
>PyObject* tuple = PyTuple_New(4);
>PyObject* val = 0;
> 
>val = PyInt_FromLong(ordval.size);
>PyTuple_SetItem(tuple,0,val);
>PyDict_SetItemString(loc,"size",val);
> 
>val = PyInt_FromLong(ordval.vol);
>PyTuple_SetItem(tuple,1,val);
>PyDict_SetItemString(loc,"vol",val);
> 
>val = PyInt_FromLong(ordval.ADV);
>PyTuple_SetItem(tuple,2,val);
>PyDict_SetItemString(loc,"ADV",val);
> 
>val = PyString_FromString(ordval.prod);
>PyTuple_SetItem(tuple,3,val);
>PyDict_SetItemString(loc,"prod",val);
> 
> 
> /*** with string & Py_file_input ***/
>PyObject* result = NULL;
>result = Py_CompileString(szExpr,"",
> Py_file_input);
>if(result!=NULL && !PyErr_Occurred()){
>  printf("str compiled fine with stdin &
> Py_file_input, calling PyEval_EvalCode\n");
> 
>  PyCodeObject *pyCo = (PyCodeObject *)result;
>  PyObject* evalret = NULL;
>  evalret = PyEval_EvalCode(pyCo,glb,loc);
>  if(!evalret || PyErr_Occurred())
>PyErr_Print();
>  else
> printf("ok [%d] size
>
[%d]\n",PyObject_Print(evalret,stdout,0),PyObject_Size(evalret));
> 
>  // Try to get function obj of this...
>  printf("Getting PyFunction_New\n");
>  PyObject* func = PyFunction_New(result,glb);
>  if(!func || PyErr_Occurred()){
>printf("Failed to get Function..\n");
>PyErr_Print();
>  } else {
>  printf("Calling PyObject_CallObject\n");
>  if(PyCallable_Check(func))
>printf("func is callable\n");
>  PyObject* ret = PyObject_CallObject(func,
> tuple);
>  //PyObject* ret = PyObject_CallObject(func,
> NULL);
>  if(!ret || PyErr_Occurred())
>PyErr_Print();
>  else
>printf("PyObject_CallObject
> evaluated..\n");
>  }
>} else {
>  printf("Py_CompileString-1 returned
> NULL\n");
>  PyErr_Print();
>}
>exit(100);
> }

Remember that when you execute the Python source code,
you get the function *definition*; you are not
executing the function itself.

I travel until Dec. so unfortunately I can't provide
more help now. See the docs for Extending and
Embedding.

-- 
Gabriel Genellina

Gabriel Genellina
So

Re: why it is invalid syntax?

2007-11-21 Thread Zara
On Thu, 22 Nov 2007 00:00:16 -0600, alf <[EMAIL PROTECTED]> wrote:

>Hi,
>
>I wonder why it is an invalid syntax:
>
>
> >>> if 1: if 1: if 1: print 1
>   File "", line 1
> if 1: if 1: if 1: print 1
>
>
>or
>
> >>> if 1: for i in range(10): print i
>   File "", line 1
> if 1: for i in range(10): print i
>
>I would expect one could nest :
>

You may take a look at python documentation, Language reference, 7.
Compound statement. It clearly states that what follows the : of
if,while,for... if it is not a new line, it should be a list of simple
statements. Son no there is no : nesting.


>compound_stmt ::= if_stmt 
>  | while_stmt 
>  | for_stmt 
>  | try_stmt 
>  | with_stmt 
>  | funcdef 
>  | classdef 
>suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT 
>statement ::= stmt_list NEWLINE | compound_stmt 
>stmt_list ::= simple_stmt (";" simple_stmt)* [";"] 
>

Regards,

Zara

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


Re: Next float?

2007-11-21 Thread Steven D'Aprano
On Thu, 22 Nov 2007 00:44:34 -0600, Robert Kern wrote:

> Steven D'Aprano wrote:
>> Is there a simple, elegant way in Python to get the next float from a
>> given one? By "next float", I mean given a float x, I want the smallest
>> float larger than x.
> 
> Heh:
> 
>   http://mail.python.org/pipermail/python-list/2005-December/357771.html

Damn, I don't remember writing that!

:-/



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


Re: why it is invalid syntax?

2007-11-21 Thread Marc 'BlackJack' Rintsch
On Thu, 22 Nov 2007 00:00:16 -0600, alf wrote:

> I wonder why it is an invalid syntax:
> 
> 
>  >>> if 1: if 1: if 1: print 1
>File "", line 1
>  if 1: if 1: if 1: print 1
> 
> or
> 
>  >>> if 1: for i in range(10): print i
>File "", line 1
>  if 1: for i in range(10): print i
> 
> I would expect one could nest :

It's quite unreadable and if this would be allowed you would have to
introduce a special rule to forbid ``else``, ``except`` and ``finally``
because it can lead to ambiguities. To which ``if`` does the ``else``
belong to here? ::

  if 1: print 1 if: 1 print 1 else: print 1

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


Re: Next float?

2007-11-21 Thread Robert Kern
Steven D'Aprano wrote:
> Is there a simple, elegant way in Python to get the next float from a 
> given one? By "next float", I mean given a float x, I want the smallest 
> float larger than x.

Heh:

  http://mail.python.org/pipermail/python-list/2005-December/357771.html

-- 
Robert Kern

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

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


Issue with reading and writing into .ini files using python

2007-11-21 Thread tarun
Hello,

I am using config approach as mentioned in the below link to read and write
into setup (.ini) files:
http://www.voidspace.org.uk/python/configobj.html

I've a key named 'SELECTED' in my .ini file.

Sometimes I get the following error on trying to read the .ini file:val
= dict.__getitem__(self, key)
KeyError: 'SELECTED'

Can anyone help.

Thanks in advance

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

Re: Next float?

2007-11-21 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> Is there a simple, elegant way in Python to get the next float from a 
> given one? By "next float", I mean given a float x, I want the smallest 
> float larger than x.

I think you have to do it by bit twiddling.  But something like bisection
search could come pretty close, for well-behaved values of x:

def nextfloat(x):
dx = (x, x/2.0)
while x+dx[1] != x:
dx = (dx[1], dx[1]/2.0)
return dx[0]+x
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next float?

2007-11-21 Thread Robert Kern
Steven D'Aprano wrote:
> Is there a simple, elegant way in Python to get the next float from a 
> given one? By "next float", I mean given a float x, I want the smallest 
> float larger than x.

Courtesy of Tim Peters:

  http://mail.python.org/pipermail/python-list/2001-August/099152.html

> Bonus points if I can go in either direction (i.e. the "previous float" 
> as well as the next).

Left as an exercise for the reader.  :-)

-- 
Robert Kern

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

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


**SMALL BUSINESS**PLAN FOR A LOAN**

2007-11-21 Thread Pressly
**SMALL BUSINESS**PLAN FOR A LOAN**
**BPM SOFTWARE**
**INTERNET SOFTWARE**
**SOFTWARE DEVELOPMENT**
**PROCESS MODELLING SOFTWARE**
http://regantame.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


why it is invalid syntax?

2007-11-21 Thread alf
Hi,

I wonder why it is an invalid syntax:


 >>> if 1: if 1: if 1: print 1
   File "", line 1
 if 1: if 1: if 1: print 1


or

 >>> if 1: for i in range(10): print i
   File "", line 1
 if 1: for i in range(10): print i

I would expect one could nest :


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


Re: logging and propagation

2007-11-21 Thread Vinay Sajip
On Nov 21, 11:38 am, oj <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I want to setuploggingwith two loggers:
>
> The child logger is used when something different needs to be done
> with the log record, and the log record will propagate and be logged
> by the root logger as usual.
>
> However, there are certain times when I don't want a log record to
> propagate from the child to the parent.
>
> I don't really want to add a filter to the root logger, as it should
> be up to the child whether the record propagates or not.
>
> I've tried setting the child to a lower level then the parent, but if
> a record is dealt with by the child, the parent deals with it anyway
> regardless of its own log level.
>
> Also, filters only apply particular handlers and do not affect
> propagation.
>
> Can anyone suggest a simple way to achieve this?
>
> Currently, the only thing I can think of, is overriding the
> callHandlers method in a custom Logger class.

Do you already have a Logger subclass? Where and when is the decision
being made about whether to propagate or not?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next float?

2007-11-21 Thread Mark T

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Is there a simple, elegant way in Python to get the next float from a
> given one? By "next float", I mean given a float x, I want the smallest
> float larger than x.
>
> Bonus points if I can go in either direction (i.e. the "previous float"
> as well as the next).
>
> Note to maths pedants: I am aware that there is no "next real number",
> but floats are not reals.
>
>
> -- 
> Steven

Here's some functions to get the binary representation of a float.  Then 
just manipulate the bits (an exercise for the reader):

import struct

def f2b(f):
return struct.unpack('I',struct.pack('f',f))[0]

def b2f(b):
return struct.unpack('f',struct.pack('I',b))[0]

>>> f2b(1.0)
1065353216
>>> hex(f2b(1.0))
'0x3f80'
>>> b2f(0x3f80)
1.0
>>> b2f(0x3f81)
1.001192092896
>>> b2f(0x3f7f)
0.9994039535522

-Mark 

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


Re: Next float?

2007-11-21 Thread Alex Holkner
On Nov 22, 2007 2:04 PM, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> Is there a simple, elegant way in Python to get the next float from a
> given one? By "next float", I mean given a float x, I want the smallest
> float larger than x.
>
> Bonus points if I can go in either direction (i.e. the "previous float"
> as well as the next).

Not so elegant, but you could use ctypes to manipulate the bits
(assumes machine uses IEEE 754 doubles for Python floats, I'm not sure
if that's guaranteed on esoteric platforms):

import ctypes

def inc_float(f):
# Get an int64 pointer to the float data
fv = ctypes.c_double(f)
pfv = ctypes.pointer(fv)
piv = ctypes.cast(pfv, ctypes.POINTER(ctypes.c_uint64))

# Check for NaN or infinity, return unchanged
v = piv.contents.value
if not ~(v & (11 << 52)): # exponent is all 1's
return f

if v == 1 << 63:# -0, treat as +0
v = 1
elif v & (1 << 63): # negative
v -= 1
else:   # positive or +0
v += 1

# Set int pointer and return changed float
piv.contents.value = v
return fv.value

def dec_float(f):
# Get an int64 pointer to the float data
fv = ctypes.c_double(f)
pfv = ctypes.pointer(fv)
piv = ctypes.cast(pfv, ctypes.POINTER(ctypes.c_uint64))

# Check for NaN or infinity, return unchanged
v = piv.contents.value
if not ~(v & (11 << 52)): # exponent is all 1's
return f

if v == 0:  # +0, treat as -0
v = (1 << 63) | 1
elif v & (1 << 63): # negative
v += 1
else:   # positive
v -= 1

# Set int pointer and return changed float
piv.contents.value = v
return fv.value
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-21 Thread Steven D'Aprano
On Wed, 21 Nov 2007 15:51:56 -0800, braver wrote:

> Is there any trick to get rid of having to type the annoying,
> character-eating "self." prefix everywhere in a class?


Oh I know! It' uch a pain. Sinc writing a hug cla lat wk, I'v had a 
trribl hortag o lowrca S E L and F charactr. It mak writing vry annoying.


> Sometimes I avoid OO just not to deal with its verbosity.

There are other values than brevity. In fact, brevity is one of the less 
important values.


> In fact, I try to use
> Ruby anywhere speed is not crucial especially for @ prefix is better-
> looking than self.

Well, it takes all sorts I suppose. Who would those with good taste mock 
if everybody liked the same things?


> But things grow -- is there any metaprogramming tricks or whatnot we can
> throw on the self?

Oh yeah, that's just what I like to see! Complicated, brittle, hard to 
debug, difficult to understand metaprogramming tricks in preference to a 
simple, easy-to-read naming convention.



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


Re: Introspect the class name of object?

2007-11-21 Thread Steven D'Aprano
On Wed, 21 Nov 2007 18:55:21 -0800, Davy wrote:

> Hi all,
> 
> How to get the class name of an object from an introspect way? For
> example,
> Class cls:pass
> 
> obj = cls()
> 
> I want to get function(obj) = 'cls'


obj.__class__ returns the class itself.

obj.__class__.__name__ returns the name of the class as a string.





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


how terminate console(not Ctrl-C)

2007-11-21 Thread NoName
Is it possible to interrupt loop (program) by pressing Q key like Ctrl-
C?
how can i hook user's keypress while program running?

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


Buffer type

2007-11-21 Thread Benjamin
What's the point of the built in buffer type? The documentation
(http://docs.python.org/lib/typesseq.html) is not very enlightening.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-21 Thread Steven D'Aprano
On Wed, 21 Nov 2007 15:17:14 -0800, braver wrote:

> I'd like to check, for a filehandle f, that EOF has been reached on it. 
> What's the way to do it?  I don't want to try/except on EOF, I want to
> check, after I read a line, that now we're in the EOF state.

Why? For some file-like objects, the OS can't tell if you're at EOF until 
you actually try to read.

The usual way to deal with EOF in Python is not to bother.

fp = open("filename", "r")
for line in fp:
do_something_with(line)
# When we exit the loop, we're at EOF.


What are you doing that needs more hands-on control?



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


Next float?

2007-11-21 Thread Steven D'Aprano
Is there a simple, elegant way in Python to get the next float from a 
given one? By "next float", I mean given a float x, I want the smallest 
float larger than x.

Bonus points if I can go in either direction (i.e. the "previous float" 
as well as the next).

Note to maths pedants: I am aware that there is no "next real number", 
but floats are not reals.


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


Introspect the class name of object?

2007-11-21 Thread Davy
Hi all,

How to get the class name of an object from an introspect way?
For example,
Class cls:pass

obj = cls()

I want to get function(obj) = 'cls'

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


Re: eof

2007-11-21 Thread I V
On Wed, 21 Nov 2007 17:06:15 -0800, braver wrote:
> Why do I have to count sizes of lines read and compare it to some
> filesize or do other weird tricks just to see, in a way not changing my
> input stream, whether it's at the, well, EOF?

Because you can't, generally, tell whether or not a stream is at the end 
of the file without reading from it; the C standard library doesn't 
guarantee that the EOF status is set until _after_ you've tried to read 
past the end of the file. I don't know, but I suspect that may be why 
python doesn't support querying files for EOF status - the fact that EOF 
can be false when you've read all the data in the file is a source of 
confusion to lots of C programmers.

It looks like ruby internally buffers the stream itself, which is how 
come it can support this. According to the docs:

"Note that IO#eof? reads data to a input buffer."

http://www.ruby-doc.org/core/classes/IO.html#M002309

I'd imagine that's inefficient in a lot of cases; and I don't think it 
provides much benefit. What's the hardship in checking the return values 
of your IO calls? Or iterating over the file, which is a more elegant 
solution in many cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-21 Thread Neil Cerutti
On 2007-11-21, braver <[EMAIL PROTECTED]> wrote:
> I'd like to check, for a filehandle f, that EOF has been reached on
> it.  What's the way to do it?  I don't want to try/except on EOF, I
> want to check, after I read a line, that now we're in the EOF state.
> In Ruby it's f.eof:
>
> In Ruby:
>>> f = File.open("jopa")
>=> #
>>> f.read()
>=> "jopa\n"
>>> f.eof
>=> true
>
> Is there a Python analog?

Yes.

>>> f = file('jopa')
>>> f.read()
'jopa\n'

...and in both Ruby and Python you are at EOF by definition.
There's no need to check.

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


RE: the annoying, verbose self

2007-11-21 Thread Looney, James B
There are always tricks.  If 5 characters is really too much to type,
how about 2 characters "s.".  Though I would recommend against that
since
it violates standard Python convention.

def foo( self ):

becomes

def foo( s ):

Otherwise, if you happen to be using self.something a lot, just
assign it to a variable, and use that.  But be careful as that
can become a lot more difficult to read/maintain than simply
leaving self along to begin with.

ss = self.something
ss.foo()

To me, using 'self' in Python is no different than using some other
variable pointing to a class instance in a static C++ class function.

-James

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED]
> ] On Behalf Of braver
> Sent: Wednesday, November 21, 2007 4:52 PM
> To: python-list@python.org
> Subject: the annoying, verbose self
> 
> Is there any trick to get rid of having to type the annoying,
> character-eating "self." prefix everywhere in a class?  Sometimes I
> avoid OO just not to deal with its verbosity.  In fact, I try to use
> Ruby anywhere speed is not crucial especially for @ prefix is better-
> looking than self.
> 
> But things grow -- is there any metaprogramming tricks or whatnot we
> can throw on the self?
> 
> Cheers,
> Alexy
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-21 Thread braver
On Nov 22, 3:41 am, Wayne Brehaut <[EMAIL PROTECTED]> wrote:
> If you have PythonWin 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310
> 32 bit (Intel)] on win32.for example, using Help, Index, eof gives:
>
> eof
> Token used to determine end of file. This will be set to the empty
> string (''), in non-POSIX mode, and to None in POSIX mode. New in
> version 2.3.
>
> If you don't use Active State Python--and even of you do--it helps to
> have these  three "official" references handy:
> If the end of the file has been reached, f.read() will return an empty
> string ("").
>
> 3.9 File Objects
>
> There, and checking for "EOF"  you'll note that both read( [size]) and
> readline( [size]) include:
>
> "An empty string is returned only when EOF is encountered
> immediately."
>
> HTH?

Nope!  I don't want to buffer input myself, and don't want to store
look-ahead and push it back.  f.read()/readline() is not a non-
destructive check, and thus won't do.

> >In Ruby it's f.eof:
>
> It also is not nice to talk Ruby here--nor Perl. Refer to C/C++ if
> necessary.

Well folks compare scripting languages all the time, and surely Ruby
is closer to Python than C++.  Since Ruby can do f.eof, which is
easily found in its references, and Python can't, or its EOF can't
easily be found -- the one *equivalent* to a semantically clear
Ruby's, or Pascal's IIRC, f.eof -- something's missing here...

Why do I have to count sizes of lines read and compare it to some
filesize or do other weird tricks just to see, in a way not changing
my input stream, whether it's at the, well, EOF?

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


Re: eof

2007-11-21 Thread Wayne Brehaut
Hi braver,

On Wed, 21 Nov 2007 15:17:14 -0800 (PST), braver
<[EMAIL PROTECTED]> wrote:

>I'd like to check, for a filehandle f, that EOF has been reached on
>it.  What's the way to do it?  I don't want to try/except on EOF, I
>want to check, after I read a line, that now we're in the EOF state.

It would be nicer to check the reference manual than ask here.  If you
have PythonWin 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310
32 bit (Intel)] on win32.for example, using Help, Index, eof gives: 

eof 
Token used to determine end of file. This will be set to the empty
string (''), in non-POSIX mode, and to None in POSIX mode. New in
version 2.3. 

If you don't use Active State Python--and even of you do--it helps to
have these  three "official" references handy:

===
http://docs.python.org/ref/ref.html

Python Reference Manual
Guido van Rossum

Python Software Foundation 
Email: [EMAIL PROTECTED] 

Fred L. Drake, Jr., editor

Release 2.5
19th September, 2006
===
http://docs.python.org/lib/lib.html

Python Library Reference
Guido van Rossum

Python Software Foundation 
Email: [EMAIL PROTECTED] 

Fred L. Drake, Jr., editor

Release 2.5
19th September, 2006
===
http://docs.python.org/tut/tut.html

Python Tutorial
Guido van Rossum

Python Software Foundation 
Email: [EMAIL PROTECTED] 

Fred L. Drake, Jr., editor

Release 2.5
19th September, 2006
===

The tutorial gives simpler explanations and examples, including:

7. Input and Output 
7.2.1 Methods of File Objects 

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
===

If the end of the file has been reached, f.read() will return an empty
string (""). 

By browsing the index or TOC, or searching, or guessing, you should
conclude that you want 

3.9 File Objects

There, and checking for "EOF"  you'll note that both read( [size]) and
readline( [size]) include:

"An empty string is returned only when EOF is encountered
immediately."

HTH?

>In Ruby it's f.eof:

It also is not nice to talk Ruby here--nor Perl. Refer to C/C++ if
necessary.

wwwayne


>
>In Ruby:
>>> f = File.open("jopa")
>=> #
>>> f.read()
>=> "jopa\n"
>>> f.eof
>=> true
>
>Is there a Python analog?
>
>Cheers,
>Alexy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-21 Thread Farshid Lashkari
braver wrote:
> Is there any trick to get rid of having to type the annoying,
> character-eating "self." prefix everywhere in a class?  Sometimes I
> avoid OO just not to deal with its verbosity.  In fact, I try to use
> Ruby anywhere speed is not crucial especially for @ prefix is better-
> looking than self.
> 
> But things grow -- is there any metaprogramming tricks or whatnot we
> can throw on the self?

The most common answer you are going to get is that explicit is better 
than implicit, which I tend to agree with. Some people use 's' instead 
of 'self'. This shortens the number of characters you have to type, and 
is only one character more than the Ruby '@' prefix.

Here is a metaprogramming technique that removes self, but I don't 
recommend these sorts of things, especially if other people are going to 
be looking at your code in the future. So use it at your own risk!

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

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


the annoying, verbose self

2007-11-21 Thread braver
Is there any trick to get rid of having to type the annoying,
character-eating "self." prefix everywhere in a class?  Sometimes I
avoid OO just not to deal with its verbosity.  In fact, I try to use
Ruby anywhere speed is not crucial especially for @ prefix is better-
looking than self.

But things grow -- is there any metaprogramming tricks or whatnot we
can throw on the self?

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


twisted client.getPage threading safety

2007-11-21 Thread sndive
I found nothing better to do than to start a new thread from c and run
twisted event loop there.

my question is: how can i safely call client.getPage() from another
thread? could i?
i have compiled python without threading support and am wondering what
the repercussions will be
(i don't want to enable threading for python space)
-- 
http://mail.python.org/mailman/listinfo/python-list


eof

2007-11-21 Thread braver
I'd like to check, for a filehandle f, that EOF has been reached on
it.  What's the way to do it?  I don't want to try/except on EOF, I
want to check, after I read a line, that now we're in the EOF state.
In Ruby it's f.eof:

In Ruby:
>> f = File.open("jopa")
=> #
>> f.read()
=> "jopa\n"
>> f.eof
=> true

Is there a Python analog?

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


Re: Clean way to get one's network IP address?

2007-11-21 Thread Steven D'Aprano
On Wed, 21 Nov 2007 12:00:52 -0500, Joe Riopel wrote:

> On Nov 21, 2007 10:15 AM, Gilles Ganault <[EMAIL PROTECTED]> wrote:
>> I know about socket.gethostbyname, but this relies on what's in
>> /etc/hosts, and I'd rather have a more independent solution.
> 
> I might be missing something in your question, but on a Windows XP
> machine, I can get the IP address of my machine using:
 from socket import gethostname, gethostbyname
 gethostbyname(gethostname())
> '192.168.0.11'



Just out of curiosity, what part of the Original Poster's comment that he 
already knew about socket.gethostbyname did you not understand?



-- 
Steven
who seems to be making a lot of snarky comments lately.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: s[i:j:t] = t stipulation

2007-11-21 Thread Terry Reedy

"Neil Cerutti" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| On 2007-11-20, Terry Reedy <[EMAIL PROTECTED]> wrote:
| > No, it should be defined as resulting in
| >
| > ['a', 1, 'a', 2, 'a', 3, None, 5, None, 7, None, 9] # ;-)

Note smiley.

| I thought deletion of elements would be more similar to slice
| assignment, e.g.:
|
| x[5:] = []
|  --> [0, 1, 2, 3, 4]
|  -/ /-> [0, 1, 2, 3, 4, None, None, None, None, None]
|
| > Or better yet, require the programmer to specify by modifying
| > either the target or source spec, as is done now.
|
| It seems a shame to accept iterators but to build a sequence out
| of them, if it can be avoided. But if there's too much confusion
| about what it should mean, I guess that kills the idea.

For the core, we agree.  For your personal use, completing
def repdel(museq, slise, source):
"Replace or delete museq[slise] with items from source"
...
with the behavior you want should not be too difficult.

tjr



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


Re: sendmail a long message

2007-11-21 Thread Helmut Jarausch
Laszlo Nagy wrote:
> Helmut Jarausch wrote:
>> Hi,
>>
>> to send a possibly long email I have seen a solution
>> which does os.popen to an external sendmail program and
>> then writes the message into that pipe.
>>
>> I wonder if it possible to use smtplib.SMTP.sendmail
>> but this requires building the complete body as one long
>> string in memory before calling this.
>>
>> Is there an alternative solution, e.g. where
>> smtplib.SMTP.sendmail calls a generator.
>>   
> using socket.connect, and feed the message body into it in smaller chunks.
> 
> Of course, you need to create the message body first, but it was not 
> your question - I suppose you already have the message stored on disk?
> 

Thanks,
it's a mail filter, the message is read in smaller chunks from sys.stdin .
Helmut.


-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python safe scripting

2007-11-21 Thread i3dmaster
On Nov 21, 12:44 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> 2007/11/21, Vladimir Rusinov <[EMAIL PROTECTED]>:
>
> > Hello!
>
> > In one my project (it's logfile manager) I want to implement 'smart'
> > configuration files, e.g.
>
> > logfile("/var/log/messages")
> > if (size() > 10*1024*1024) and (lavg() < 5):
> > execute("my_log_alerter")
> >rotate(save=10, compress='bzip2')
>
> > how can I safely do this?
>
> > --
> > Vladimir Rusinov
> > GreenMice Solutions: IT-ÒÅÛÅÎÉÑ ÎÁ ÂÁÚÅ Linux
> >  http://greenmice.info/
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> logging already provides the rotating
>
> from logging.handlers import RotatingFileHandler
> help(RotatingFileHandler)
>
> --
> -- Guilherme H. Polo Goncalves

But the original RotatingFileHanlder does not offer compressing
facility where the sample code that the author provides seems to
indicate that he wants some sort of handling on that... Extends the
class and override the doRollover method would probably do what you
need.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sendmail a long message

2007-11-21 Thread Laszlo Nagy
Helmut Jarausch wrote:
> Hi,
>
> to send a possibly long email I have seen a solution
> which does os.popen to an external sendmail program and
> then writes the message into that pipe.
>
> I wonder if it possible to use smtplib.SMTP.sendmail
> but this requires building the complete body as one long
> string in memory before calling this.
>
> Is there an alternative solution, e.g. where
> smtplib.SMTP.sendmail calls a generator.
>   
using socket.connect, and feed the message body into it in smaller chunks.

Of course, you need to create the message body first, but it was not 
your question - I suppose you already have the message stored on disk?

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


Re: python safe scripting

2007-11-21 Thread Guilherme Polo
2007/11/21, Vladimir Rusinov <[EMAIL PROTECTED]>:
> Hello!
>
> In one my project (it's logfile manager) I want to implement 'smart'
> configuration files, e.g.
>
> logfile("/var/log/messages")
> if (size() > 10*1024*1024) and (lavg() < 5):
> execute("my_log_alerter")
>rotate(save=10, compress='bzip2')
>
> how can I safely do this?
>
> --
> Vladimir Rusinov
> GreenMice Solutions: IT-решения на базе Linux
>  http://greenmice.info/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
logging already provides the rotating

from logging.handlers import RotatingFileHandler
help(RotatingFileHandler)


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list

sendmail a long message

2007-11-21 Thread Helmut Jarausch
Hi,

to send a possibly long email I have seen a solution
which does os.popen to an external sendmail program and
then writes the message into that pipe.

I wonder if it possible to use smtplib.SMTP.sendmail
but this requires building the complete body as one long
string in memory before calling this.

Is there an alternative solution, e.g. where
smtplib.SMTP.sendmail calls a generator.

Many thanks for a hint,


Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


python safe scripting

2007-11-21 Thread Vladimir Rusinov
Hello!

In one my project (it's logfile manager) I want to implement 'smart'
configuration files, e.g.

logfile("/var/log/messages")
if (size() > 10*1024*1024) and (lavg() < 5):
   execute("my_log_alerter")
   rotate(save=10, compress='bzip2')

how can I safely do this?

-- 
Vladimir Rusinov
GreenMice Solutions: IT-решения на базе Linux
http://greenmice.info/
-- 
http://mail.python.org/mailman/listinfo/python-list

Dictionary vs binary search lookups [was: Populating a dictionary, fast [SOLVED]]

2007-11-21 Thread Francesc Altet
A Tuesday 20 November 2007, Istvan Albert escrigué:
> On Nov 19, 2:33 pm, Francesc Altet <[EMAIL PROTECTED]> wrote:
> > Just for the record.  I was unable to stop thinking about this, and
> > after some investigation, I guess that my rememberings were
> > gathered from some benchmarks with code in Pyrex (i.e. pretty near
> > to C speed).
>
> Pretty interesting and quite unexpected.

Yeah, and also bogus :(

It turned out that in my previous benchmark, I've used plain numpy int 
arrays to do measurements, and when you extract an element out of a 
numpy array what you obtain is a *numpy scalar*, which is a different 
beast than a python (long) integer.  Unfortunately, pyrex does swallow 
it and happily converted to a long long C, but produces a wrong result.  
This looks like a pyrex fault, and I should report it to the pyrex 
list.

At any rate, with the corrected benchmarks using plain python lists 
instead (attached), the numbers are:

Calibrating loop...
Calibrating time: 1.458
Creating the dictionary...
Time for dict creation: 15.305
Timing queries with a dict...
Time for dict query: 11.632
Creating BinarySearch object...
Time for BinarySearch creation: 8.648
Timing queries with a BinarySearch...
Time for BinarySearch queries: 19.393

That is, dictionaries do lookups 1.7x faster than a binary lookup (1.42 
us/lookup vs 2.37 us/lookup), which is, I suppose, what is expected.  
Well, this seems the end of my 'peculiar' theory, but at least served 
to uncover what it seems a bug in pyrex :P

-- 
>0,0<   Francesc Altet     http://www.carabos.com/
V   V   Cárabos Coop. V.   Enjoy Data
 "-"
# BinarySearch class to demonstrate that binary search is competitive
# against dictionaries based on hashes

import numpy

# In order to access the data area in NumPy objects
cdef extern from "numpy/arrayobject.h":

  ctypedef extern class numpy.ndarray [object PyArrayObject]:
cdef char *data

  void import_array()

import_array()


cdef long bisect_left(long long *a, long long x, long lo, long hi):
cdef long mid

while lo < hi:
mid = (lo+hi)/2
if a[mid] < x: lo = mid+1
else: hi = mid
return lo


cdef class BinarySearch:
cdef long len
cdef object values
cdef long *revidd
cdef long long *sidd
cdef ndarray sid, revid

def __new__(self, object keys, object values):
self.sid = numpy.array(keys)
self.revid = self.sid.argsort()
self.revidd = self.revid.data
self.sid.sort()
self.sidd = self.sid.data
self.values = values
self.len = len(values) - 1

def __getitem__(self, x):
cdef long pos, idx

pos = bisect_left(self.sidd, x, 0, self.len)
idx = self.revidd[pos]
return self.values[idx]


gq-binary-search.py
Description: application/python


setup.py
Description: application/python
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: import pysqlite2 or import sqlite3?

2007-11-21 Thread Hertha Steck
Hertha Steck wrote:

> Hello,
> 
> I'm using Python 2.5.1, Pysqlite 2.3.5 and SQLite 3.4.1 on Gentoo Linux.
> I've always imported pysqlite using
> 
> from pysqlite2 import dbapi2
> 
> and that works. If I try
> 
> import sqlite3
> 
> I get
> 
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/sqlite3/__init__.py", line 24, in 
> from dbapi2 import *
>   File "/usr/lib/python2.5/sqlite3/dbapi2.py", line 27, in 
> from _sqlite3 import *
> ImportError: No module named _sqlite3
> 
> And I thought that's normal, there is no Python module called sqlite3.
> 

After a second look at the error message: when I installed Gentoo, Python
2.4 was installed, I got the new version a little later. And I think I
installed Pysqlite 2.3.5 separately. 

Python 2.5 comes with pysqlite - should I uninstall my version?


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


import pysqlite2 or import sqlite3?

2007-11-21 Thread Hertha Steck
Hello,

I'm using Python 2.5.1, Pysqlite 2.3.5 and SQLite 3.4.1 on Gentoo Linux.
I've always imported pysqlite using

from pysqlite2 import dbapi2

and that works. If I try

import sqlite3

I get

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/sqlite3/__init__.py", line 24, in 
from dbapi2 import *
  File "/usr/lib/python2.5/sqlite3/dbapi2.py", line 27, in 
from _sqlite3 import *
ImportError: No module named _sqlite3

And I thought that's normal, there is no Python module called sqlite3. 

Then, after a discussion in the Gentoo forum, I saw this in the Python
library reference:

> To use the module, you must first create a Connection object that
represents the database. Here the data will be stored in the /tmp/example
file: 
> 
> conn = sqlite3.connect('/tmp/example')
> 

No import statement, though, so the module might have been renamed in that
statement. Possibly not a really good idea in the documentation. 

But now I see an old post to c.p.l:

> I'm using Ubuntu Feisty: 
>  * Python 2.5.1 (r251:54863, May  2 2007, 16:56:35) 
>  [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 
>  * SQLite version 3.3.13 
>  
> Suppose I run the following program: 
>  import sqlite3 
>  
> conn = sqlite3.connect('example') 
...

And from the rest of the posting that import seems to work. Has that module
different names for different Linux distributions? Or what's the matter
here?

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


Re: regex problem with re and fnmatch

2007-11-21 Thread Fabian Braennstroem
Hi John,

John Machin schrieb am 11/20/2007 09:40 PM:
> On Nov 21, 8:05 am, Fabian Braennstroem <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I would like to use re to search for lines in a files with
>> the word "README_x.org", where x is any number.
>> E.g. the structure would look like this:
>> [[file:~/pfm_v99/README_1.org]]
>>
>> I tried to use these kind of matchings:
>> #org_files='.*README\_1.org]]'
>> org_files='.*README\_*.org]]'
>> if re.match(org_files,line):
> 
> First tip is to drop the leading '.*' and use search() instead of
> match(). The second tip is to use raw strings always for your
> patterns.
> 
>> Unfortunately, it matches all entries with "README.org", but
>> not the wanted number!?
> 
> \_* matches 0 or more occurrences of _ (the \ is redundant). You need
> to specify one or more digits -- use \d+ or [0-9]+
> 
> The . in .org matches ANY character except a newline. You need to
> escape it with a \.
> 
 pat = r'README_\d+\.org'
 re.search(pat, 'README.org')
 re.search(pat, 'README_.org')
 re.search(pat, 'README_1.org')
> <_sre.SRE_Match object at 0x00B899C0>
 re.search(pat, 'README_.org')
> <_sre.SRE_Match object at 0x00B899F8>
 re.search(pat, 'README_Zorg')


Thanks a lot, works really nice!

>> After some splitting and replacing I am able to check, if
>> the above file exists. If it does not, I start to search for
>> it using the 'walk' procedure:
> 
> I presume that you mean something like: """.. check if the above file
> exists in some directory. If it does not, I start to search for  it
> somewhere else ..."""
> 
>> for root, dirs, files in
>> os.walk("/home/fab/org"):
> 
>> for name in dirs:
>> dirs=os.path.join(root, name) + '/'
> 
> The above looks rather suspicious ...
> for thing in container:
> container = something_else
> 
> What are you trying to do?
> 
> 
>> for name in files:
>>  files=os.path.join(root, name)
> 
> and again 
> 
>> if fnmatch.fnmatch(str(files), "README*"):
> 
> Why str(name) ?
> 
>> print "File Found"
>> print str(files)
>> break
> 
> 
> fnmatch is not as capable as re; in particular it can't express "one
> or more digits". To search a directory tree for the first file whose
> name matches a pattern, you need something like this:
> def find_one(top, pat):
>for root, dirs, files in os.walk(top):
>   for fname in files:
>  if re.match(pat + '$', fname):
> return os.path.join(root, fname)
> 
> 
>> As soon as it finds the file,
> 
> "the" file or "a" file???
> 
> Ummm ... aren't you trying to locate a file whose EXACT name you found
> in the first exercise??
> 
> def find_it(top, required):
>for root, dirs, files in os.walk(top):
>   if required in files:
> return os.path.join(root, required)

Great :-) Thanks a lot for your help... it can be so easy :-)
Fabian


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


Re: Clean way to get one's network IP address?

2007-11-21 Thread poltrone
> What would be a good way to do this?

using 'netifaces'?
see http://pypi.python.org/pypi/netifaces/0.3


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


computer programming

2007-11-21 Thread lawry_jim
http://computer-programmings.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Contextmenu in a QTreeWidget with PyQT

2007-11-21 Thread [EMAIL PROTECTED]
I apologize in advance if this is not the correct forum to ask this
and if someone knows a better place, please let me know.  But, I am
trying to create a Contextmenu (a right-click popup menu) from within
a QTreeWidget.  I tried setting the contextMenuPolicy to
CustomContextMenu and then handling the signal
customContextMenuRequested() but nothing seems to be happening.  ie:
   self.tree = QTreeWidget()
   self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
 
self.connect(self.tree,SIGNAL('customContextMenuRequested()'),self.newContext)

Does anyone have a sample or tutorial on how to do this?  One other
question, whe I right click, it changes the selection in the
TreeWidget, would I need to remove the handler for right clicks to get
the menu?  Thanks!!

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


having problem using xlrd

2007-11-21 Thread Kelie
Hello,

I tried using xlrd to read an Excel file and kept getting this error:

AttributeError: 'Book' object has no attribute 'mem'

>>> import xlrd
>>> p = r'C:\2.xls'
>>> wb = xlrd.open_workbook(p)
>>> wb.get_sheets()
AttributeError: 'Book' object has no attribute 'mem'

>>> wb.get_record_parts()
AttributeError: 'Book' object has no attribute 'mem'

Any hint?

Thanks!

p.s. i tried posting the question at the python-excel mailing list.
but it seems failed. if it shows up later, sorry for crossposting.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create thumbnail image (jpg/png) of PDF file using Python

2007-11-21 Thread sophie_newbie
On Nov 20, 5:36 pm, sophie_newbie <[EMAIL PROTECTED]> wrote:
> Is there any way to do this directly within python?
>
> If not is there any other good way to achieve it?
>
> Thanks in advance for any help!

I think I've solved this problem using a piece of software called
imageMagick. Good stuff so it is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatting question.

2007-11-21 Thread mike5160
On Nov 21, 11:36 am, mike5160 <[EMAIL PROTECTED]> wrote:
> On Nov 21, 1:22 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Tue, 20 Nov 2007 15:11:38 -0800 (PST), mike5160 <[EMAIL PROTECTED]>
> > declaimed the following in comp.lang.python:
>
> > > Hi all,
>
> > > My input file looks like this : ( the data is separated by tabs )
>
> > > 11/26/2007 56.366  898.90  -10.086 23.11   1212.3
> > > 11/26/2007 52.25   897.6   -12.5   12.61.5
> > > 11/26/2007 52.25   897.6   -12.5   12.6133.5
>
> > > The output I'm trying to get is as follows :
>
> > >  ( Insert NBUSER.Grochamber Values
> > > '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', )
> > >  ( Insert NBUSER.Grochamber Values
> > > '11/26/2007','52.25','897.6','-12.5','12.6','1.5', )
> > >  ( Insert NBUSER.Grochamber Values
> > > '11/26/2007','52.25','897.6','-12.5','12.6','133.5', )
>
> > 
>
> > > 2. How do I avoid the "," symbol after the last entry in the line?
> > > (this are supposed to be sql-queries - importing excel based tabbed
> > > data to sql database)
>
> > If those are SQL inserts, the ( is in the wrong place...
>
> > insert into NBUSER.Grochamber values (v1, v2, ... , vx)
>
> > > 3. What do I do when the data is missing? Like missing data?
>
> > First, for reading the file, recommend you look at the CSV module,
> > which can be configured to use TABS rather than COMMAS.
>
> > For SQL -- if you are going to be writing raw text strings to an
> > output file for later batching, YOU are going to have to supply some
> > means to properly escape the data. The better way is to have the program
> > connect to the database, using the applicable database adapter: MySQLdb
> > for MySQL, pysqlite2 (or some variant) for SQLite3, some generic ODBC
> > adapter if going that route... Let IT do the escaping.
>
> > Now, since MySQLdb just happens to expose the escaping function, AND
> > just uses %s formatting of the results, one could easily get stuff to
> > write to a file.
>
> > >>> import MySQLdb
> > >>> con = MySQLdb.connect(host="localhost", user="test", passwd="test", 
> > >>> db="test")
> > >>> data = [   "11/26/200756.366  898.90  -10.086 23.11   1212.3",
>
> > ... "11/26/2007897.6   O'Reilly12.6
> > 1.5",
> > ... "11/26/200752.25   897.6   -12.5   12.6133.5"   
> >   ]
>
> > Note how I left out a field (two tabs, nothing between), and how I
> > put in a data item with a ' in it.
>
> > >>> for ln in data:
>
> > ... flds = ln.split("\t")
> > ... placeholders = ", ".join(["%s"] * len(flds))
> > ... sql = BASE % placeholders
> > ... sql = sql % con.literal(flds)
> > ... print sql
> > ...
> > insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90',
> > '-10.086', '23.11', '1212.3')
> > insert into NBUSER.Grochamber values ('11/26/2007', '', '897.6',
> > 'O\'Reilly', '12.6', '1.5')
> > insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6',
> > '-12.5', '12.6', '133.5')
>
> > Note how the empty field is just '' (If you really need a NULL,
> > you'll have to do some games to put a Python None entity into that empty
> > string field). Also note how the single quote string value has been
> > escaped.
>
> > Something like this for NULL in STRING DATA -- if a field were
> > numeric 0 it would get substituted with a NULL too...
>
> > >>> for ln in data:
>
> > ... flds = ln.split("\t")
> > ... placeholders = ", ".join(["%s"] * len(flds))
> > ... sql = BASE % placeholders
> > ... flds = [(fld or None) for fld in flds]
> > ... sql = sql % con.literal(flds)
> > ... print sql
> > ...
> > insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90',
> > '-10.086', '23.11', '1212.3')
> > insert into NBUSER.Grochamber values ('11/26/2007', NULL, '897.6',
> > 'O\'Reilly', '12.6', '1.5')
> > insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6',
> > '-12.5', '12.6', '133.5')
>
> > --
> > WulfraedDennis Lee Bieber   KD6MOG
> > [EMAIL PROTECTED]  [EMAIL PROTECTED]
> > HTTP://wlfraed.home.netcom.com/
> > (Bestiaria Support Staff:   [EMAIL PROTECTED])
> > HTTP://www.bestiaria.com/98143
>
> Hi Dennis,
>
> Thanks to you for your reply. I  am a newbie to Python and appreciate
> you helping me. Now, I am importing data from an excel sheet and
> getting it ready for a derby database. I am to use netbeans, since our
> research team uses that. However, derby database uses sql entries to
> update the database. And I m trying to format all the excel data I
> have, which I got from using labview. I suggested that we use awk/perl/
> python etc. and finally after looking at the documentation available I
> figured Python would be best. However, (see my reply above) I am
> looking for a sample book/docume

Re: new is missing in module hmac SHA-based encryption function in Python

2007-11-21 Thread Chris Mellon
On Nov 21, 2007 10:50 AM, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> Hailong Wang wrote:
> > Matt,
> >
> > Thanks for response, I changed my script to hw_hmac.py, but still does
> > not work.
> >
> > Traceback (most recent call last):
> >   File "C:/Python25/hw_script/my_hmac.py", line 1, in 
> > import hmac
> >   File "C:\Python25\hw_script\hmac.py", line 4, in 
> > myhmac = hmac.new("test")
> > AttributeError: 'module' object has no attribute 'new'
> 
>
> (Note to anyone else: He responded off-list saying he got it to work. :-) )
>

And for the information of anyone searching the list archives: The
problem was almost certainly that while he'd renamed hmac.py, hmac.pyc
was still around.

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


Re: Python web frameworks

2007-11-21 Thread Steven Bethard
Jeff wrote:
> On Nov 21, 6:25 am, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
>> joe jacob a écrit :
>> (snip)
>>
>>> Thanks everyone for the response. From the posts I understand that
>>> Django and pylons are the best. By searching the net earlier I got the
>>> same information that Django is best among the frameworks so I
>>> downloaded it and I found it very difficult to configure.
>> ???
>>
>> It's been a couple of years since I last used Django, but I don't
>> remember any specific complexity wrt/ configuration.
> 
> The only difficulties I have had have been with serving static media.
> Specifically, in the differences in setup between the development
> environment and production, and setting it up so that I don't have to
> make any changes to the code in order to roll out upgrades to a
> product.

I ran into this same problem. I wish it was simply a matter of starting 
the django project on another server, but a bunch of paths and URLs 
always seem to need to be changed.  (I end up having to modify my 
urls.py files because I go from being at the URL root on the development 
server to being in a subdirectory on the actual server.)

Other that those issues though, I've really enjoyed working in Django.

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


Re: Clean way to get one's network IP address?

2007-11-21 Thread Joe Riopel
On Nov 21, 2007 10:15 AM, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> I know about socket.gethostbyname, but this relies on what's in
> /etc/hosts, and I'd rather have a more independent solution.

I might be missing something in your question, but on a Windows XP
machine, I can get the IP address of my machine using:
>>> from socket import gethostname, gethostbyname
>>> gethostbyname(gethostname())
'192.168.0.11'
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python web frameworks

2007-11-21 Thread BartlebyScrivener
On Nov 21, 4:42 am, joe jacob <[EMAIL PROTECTED]> wrote:
> Django is best among the frameworks so I
> downloaded it and I found it very difficult to configure. I referred
> the djangobook.

It's not a turnkey type thing like WordPress or Joomla. It's a
webframework. Also watch versions. The book examples work only in .
96.  It's easy in the tutorial to stray into docs for .95 or SVN. I
think that's part of the confusion.

rd


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


Re: Python too complex ?!?!?!

2007-11-21 Thread Chris Mellon
On Nov 20, 2007 2:43 PM, John J. Lee <[EMAIL PROTECTED]> wrote:
> "Chris Mellon" <[EMAIL PROTECTED]> writes:
> [...]
> > These modules exist, but aren't that common. Certainly anything you're
> > likely to be using in an introductory compsci course is well packaged.
> > And even if it's not, it's really not that hard to create packages or
> > installers - a days work of course prep would take care of the
> > potential problem.
>
> "A day's worth of course prep" for beginners would let them debug all
> the crap that building MySQLdb on Windows might throw at them, for
> example?  I think not! (MySQLdb, last time I looked, was one of the
> not-so-obscure modules that don't have a Windows installer available
> and kept up to date.  Maybe it does now, but that's not really the
> point.)
>

A days worth of course prep would allow the professor (or his TA, more
likely) to produce a set of installers that's suitable for use with
the course. This is a comp sci course, not a "how to sysadmin a Python
installation" course.

For the record, it took me less than 3 minutes to install MySqldb, the
first time I've ever needed to do it - I don't like or approve of
MySql. Steps required: Google for "mysql python" and click through 3
or 4 links to the SF download page. Download the binary installer,
from March 2007. Not exactly rocket science.

On a similar note, I have or create executable installers for all the
third party modules I use, because I need to provide them to the
people who do our deployments. This has never been much of a burden.

> I certainly don't recognise what some people have been saying, though.
> It's a rare thing that I have any real pain installing a Python module
> on Linux.  That's not to say you don't need some background knowledge
> about distributions and Python if doing it "by hand", of course
> (rather than with a packaging tool like apt-get).  Occasionally you'll
> want the newest version of something, which will in turn occasionally
> get you into some grim automake issue or similar.  But all of this can
> be entirely avoided in an introductory course -- simply restrict
> yourself to what can be installed with apt-get (if the instructor
> feels they *must* make some new library available, they can always
> package it themselves).
>
>
The obstacles as presented in the OP seem pretty bogus to me. Of
course, it's third hand anecdotal evidence, so there's not much of a
reason to believe that the original statement really preserves the
essence of the problem.

I'd be pretty interested if the OP could ask his associate to chime in
with some of the actual issues he encountered
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new is missing in module hmac SHA-based encryption function in Python

2007-11-21 Thread Matt Nordhoff
Hailong Wang wrote:
> Matt,
> 
> Thanks for response, I changed my script to hw_hmac.py, but still does
> not work.
> 
> Traceback (most recent call last):
>   File "C:/Python25/hw_script/my_hmac.py", line 1, in 
> import hmac
>   File "C:\Python25\hw_script\hmac.py", line 4, in 
> myhmac = hmac.new("test")
> AttributeError: 'module' object has no attribute 'new'


(Note to anyone else: He responded off-list saying he got it to work. :-) )
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clean way to get one's network IP address?

2007-11-21 Thread Jean-Paul Calderone
On Wed, 21 Nov 2007 16:15:43 +0100, Gilles Ganault <[EMAIL PROTECTED]> wrote:
>Hello
>
>I need to get the local computer's IP address, ie. what's displayed
>when running "ifconfig" in Linux:
>
># ifconfig
>eth0  Link encap:Ethernet  HWaddr 00:15:58:A1:D5:6F
>  inet addr:192.168.0.79  Bcast:192.168.0.255
>Mask:255.255.255.0
>
>I know about socket.gethostbyname, but this relies on what's in
>/etc/hosts, and I'd rather have a more independent solution.
>
>What would be a good way to do this?

You can generally get the local address which will be used for traffic
to a particular host by getting ready to send traffic to it with a UDP
socket:

>>> from socket import socket, SOCK_DGRAM, AF_INET
>>> s = socket(AF_INET, SOCK_DGRAM)
>>> s.connect(('google.com', 0))
>>> s.getsockname()
('192.168.1.113', 43711)

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


Re: new is missing in module hmac SHA-based encryption function in Python

2007-11-21 Thread Hailong Wang
Matt,

Thanks for response, I changed my script to hw_hmac.py, but still does not
work.

Traceback (most recent call last):
  File "C:/Python25/hw_script/my_hmac.py", line 1, in 
import hmac
  File "C:\Python25\hw_script\hmac.py", line 4, in 
myhmac = hmac.new("test")
AttributeError: 'module' object has no attribute 'new'
>>>



On Nov 21, 2007 8:35 AM, Matt Nordhoff <[EMAIL PROTECTED]> wrote:

> Hailong Wang wrote:
> > I have small hmac encryption programm by python, but always complain
> > that hmac module does not have attribute new, do I need to install
> > anything additinal in my laptop? I am using python 2.5.1
> >
> > import hmac
> > import md5
> > import sha
> > myhmac = hmac.new("test")
> >
> >
> > Traceback (most recent call last):
> >   File "C:\Python25\hw_script\hmac.py", line 1, in 
> > import hmac
> >   File "C:\Python25\hw_script\hmac.py", line 4, in 
> > myhmac = hmac.new("test")
> > AttributeError: 'module' object has no attribute 'new'
>
> Your script is called "hmac.py", so it's importing itself. You need to
> name it something else.
> --
>



-- 
Best regards,

Harold(Hailong) Wang
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Clean way to get one's network IP address?

2007-11-21 Thread Roy Smith
Gilles Ganault <[EMAIL PROTECTED]> wrote:

> I know about socket.gethostbyname, but this relies on what's in
> /etc/hosts, and I'd rather have a more independent solution.

The system I'm currently working on uses exactly this strategy -- we get 
the hostname then do a name lookup on it.  We've gone around and around on 
this, and ended up with that being the best solution.  For us, anyway.  
Your mileage may vary.

As others have pointed out, it's entirely possible to have multiple IP 
addresses.  In addition, your IP address(es) can change as connections come 
up and down, especially in a mobile environment (WiFi, VPN, cellular, etc).  
There is no single correct answer here.

Oh, BTW, did you mean IPv4 or IPv6?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatting question.

2007-11-21 Thread mike5160
On Nov 21, 1:22 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Tue, 20 Nov 2007 15:11:38 -0800 (PST), mike5160 <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>
>
> > Hi all,
>
> > My input file looks like this : ( the data is separated by tabs )
>
> > 11/26/2007 56.366  898.90  -10.086 23.11   1212.3
> > 11/26/2007 52.25   897.6   -12.5   12.61.5
> > 11/26/2007 52.25   897.6   -12.5   12.6133.5
>
> > The output I'm trying to get is as follows :
>
> >  ( Insert NBUSER.Grochamber Values
> > '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', )
> >  ( Insert NBUSER.Grochamber Values
> > '11/26/2007','52.25','897.6','-12.5','12.6','1.5', )
> >  ( Insert NBUSER.Grochamber Values
> > '11/26/2007','52.25','897.6','-12.5','12.6','133.5', )
>
> 
>
> > 2. How do I avoid the "," symbol after the last entry in the line?
> > (this are supposed to be sql-queries - importing excel based tabbed
> > data to sql database)
>
> If those are SQL inserts, the ( is in the wrong place...
>
> insert into NBUSER.Grochamber values (v1, v2, ... , vx)
>
> > 3. What do I do when the data is missing? Like missing data?
>
> First, for reading the file, recommend you look at the CSV module,
> which can be configured to use TABS rather than COMMAS.
>
> For SQL -- if you are going to be writing raw text strings to an
> output file for later batching, YOU are going to have to supply some
> means to properly escape the data. The better way is to have the program
> connect to the database, using the applicable database adapter: MySQLdb
> for MySQL, pysqlite2 (or some variant) for SQLite3, some generic ODBC
> adapter if going that route... Let IT do the escaping.
>
> Now, since MySQLdb just happens to expose the escaping function, AND
> just uses %s formatting of the results, one could easily get stuff to
> write to a file.
>
> >>> import MySQLdb
> >>> con = MySQLdb.connect(host="localhost", user="test", passwd="test", 
> >>> db="test")
> >>> data = [   "11/26/200756.366  898.90  -10.086 23.11   1212.3",
>
> ... "11/26/2007897.6   O'Reilly12.6
> 1.5",
> ... "11/26/200752.25   897.6   -12.5   12.6133.5" 
> ]
>
> Note how I left out a field (two tabs, nothing between), and how I
> put in a data item with a ' in it.
>
> >>> for ln in data:
>
> ... flds = ln.split("\t")
> ... placeholders = ", ".join(["%s"] * len(flds))
> ... sql = BASE % placeholders
> ... sql = sql % con.literal(flds)
> ... print sql
> ...
> insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90',
> '-10.086', '23.11', '1212.3')
> insert into NBUSER.Grochamber values ('11/26/2007', '', '897.6',
> 'O\'Reilly', '12.6', '1.5')
> insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6',
> '-12.5', '12.6', '133.5')
>
>
>
> Note how the empty field is just '' (If you really need a NULL,
> you'll have to do some games to put a Python None entity into that empty
> string field). Also note how the single quote string value has been
> escaped.
>
> Something like this for NULL in STRING DATA -- if a field were
> numeric 0 it would get substituted with a NULL too...
>
> >>> for ln in data:
>
> ... flds = ln.split("\t")
> ... placeholders = ", ".join(["%s"] * len(flds))
> ... sql = BASE % placeholders
> ... flds = [(fld or None) for fld in flds]
> ... sql = sql % con.literal(flds)
> ... print sql
> ...
> insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90',
> '-10.086', '23.11', '1212.3')
> insert into NBUSER.Grochamber values ('11/26/2007', NULL, '897.6',
> 'O\'Reilly', '12.6', '1.5')
> insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6',
> '-12.5', '12.6', '133.5')
>
>
>
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED]  [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/98

Hi Dennis,

Thanks to you for your reply. I  am a newbie to Python and appreciate
you helping me. Now, I am importing data from an excel sheet and
getting it ready for a derby database. I am to use netbeans, since our
research team uses that. However, derby database uses sql entries to
update the database. And I m trying to format all the excel data I
have, which I got from using labview. I suggested that we use awk/perl/
python etc. and finally after looking at the documentation available I
figured Python would be best. However, (see my reply above) I am
looking for a sample book/document etc. somebody suggested we try
Python Phrasebook. But that one covers a lot of different fields
whereas for my purposes I need a book with examples on using Python in
the above manner. If you or anybody knows about this kind of book
plea

Re: new is missing in module hmac SHA-based encryption function in Python

2007-11-21 Thread Matt Nordhoff
Hailong Wang wrote:
> I have small hmac encryption programm by python, but always complain
> that hmac module does not have attribute new, do I need to install
> anything additinal in my laptop? I am using python 2.5.1
> 
> import hmac
> import md5
> import sha
> myhmac = hmac.new("test")
> 
> 
> Traceback (most recent call last):
>   File "C:\Python25\hw_script\hmac.py", line 1, in 
> import hmac
>   File "C:\Python25\hw_script\hmac.py", line 4, in 
> myhmac = hmac.new("test")
> AttributeError: 'module' object has no attribute 'new'

Your script is called "hmac.py", so it's importing itself. You need to
name it something else.
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [regex] Basic rewriting

2007-11-21 Thread Mohammad Tayseer
It's also preferred if you use \d{2} instead of repeating \d
 
Mohammad Tayseer
http://spellcoder.com/blogs/tayseer





  

Be a better pen pal. 
Text or chat with friends inside Yahoo! Mail. See how.  
http://overview.mail.yahoo.com/-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Fwd: Formatting question.

2007-11-21 Thread mike5160
On Nov 20, 9:13 pm, "Sergio Correia" <[EMAIL PROTECTED]> wrote:
> Hey Mike,
> Welcome to Python!
>
> About your first issue, just change the line
> outfile.write( "'%s'," % (LoL[x][y]))
> With
> outfile.write( "'%s'," % (LoL[x][y][:-1]))
>
> Why? Because when you do the line.split, you are including the '\n' at
> the end, so a new line is created.
>
> Now, what you are doing is not very pythonic (batteries are included
> in python, so you could just use the CSV module). Also, the for x in
> range(len(somelist)) is not recommended, you can just do something
> like:
>
> 
> import csv
>
> infile = open("mydata.txt", "rb")
> outfile = open("out.txt", "wb")
>
> reader = csv.reader(infile, delimiter='\t')
> writer = csv.writer(outfile, quotechar=None, delimiter = "\\")
>
> for row in reader:
> data = "'" + "', '".join(row) + "'"
> base = " ( Insert NBUSER.Grochamber Values %s, )"
> writer.writerow([base % data])
>
> infile.close()
> outfile.close()
> 
> The above lines works like your program, writing exactly what you asked.
> Again, all lists are iterable, you don't need to iterate an integer
> from 1 to len(list). (isn't python wonderful?)
>
> HTH,
> Sergio
>
> On Nov 20, 2007 6:11 PM, mike5160 <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
>
> > My input file looks like this : ( the data is separated by tabs )
>
> > 11/26/2007  56.366  898.90  -10.086 23.11   1212.3
> > 11/26/2007  52.25   897.6   -12.5   12.61.5
> > 11/26/2007  52.25   897.6   -12.5   12.6133.5
>
> > The output I'm trying to get is as follows :
>
> >  ( Insert NBUSER.Grochamber Values
> > '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', )
> >  ( Insert NBUSER.Grochamber Values
> > '11/26/2007','52.25','897.6','-12.5','12.6','1.5', )
> >  ( Insert NBUSER.Grochamber Values
> > '11/26/2007','52.25','897.6','-12.5','12.6','133.5', )
>
> > The following is the program i have written so far :
>
> > LoL = []
>
> > for line in open('mydata.txt'):
> > LoL.append(line.split("\t"))
>
> > print "read from a file: ", LoL,
>
> > outfile = open("out.dat", "w")
>
> > lilength = len(LoL)
> > liwidelength = len(LoL[1])
>
> > print "length of list is " , lilength, "long"
> > print "length of list is " , liwidelength, "long"
>
> > for x in range(lilength):
> > outfile.write(" ( ")
> > outfile.write('Insert NBUSER.Grochamber Values ')
> > for y in range(liwidelength):
> > outfile.write( "'%s'," % (LoL[x][y]))
> > outfile.write(" ) \n")
>
> > outfile.close()
>
> > I have 3 questions :
>
> > 1. The formatting in the first line comes out wrong all the time. I m
> > using windows python 2.5.1. The last part of the first line is always
> > on the second line.
>
> > 2. How do I avoid the "," symbol after the last entry in the line?
> > (this are supposed to be sql-queries - importing excel based tabbed
> > data to sql database)
>
> > 3. What do I do when the data is missing? Like missing data?
>
> > Thanks for all your help!
>
> > Mike
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list76

HI Sergio,

First of all, thanks for your reply and yes I'm new to Python.
Did a google on CSV and I am reading the documentation about it right
now. In the post I mentioned I was using Windows. I also have a laptop
with linux installed on it. When I ran the same program on my linux
laptop I did see the \n included in the list. Somehow, I did not see
it on windows, or missed it. So that cleared up the first problem.
Also, I will be doing a lot of this data importing from excel etc. can
you point me to a tutorial/document/book etc. where I can find
snippets of using various python utilities. For eg. something which
has the sample for using "line.split("\t") " or "
outfile.write( "'%s'," % (LoL[x][y][:-1])) " , explaining the various
options available. The default "Idle  gui help" is not too informative
to a newbie like me.

Thanks again for your reply,
Mike.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write iso 9660 with python

2007-11-21 Thread Avell Diroll
bryan rasmussen wrote:
> Hi,
> 
> I need to read in a system of files and write them to an iso 9660, any
> libraries suited to this task that are up to date? Python 2.4 or 2.5
> should be assumed.

You could subprocess a call to cdrecord ...
There are also python bindings for libburn ...
http://icculus.org/burn/
but i never tested them

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


Re: google earth / pythoncom

2007-11-21 Thread John Walsh

Tom, Meff,

Thanks for your replies - very useful.

Meff - we already have the GSM/GPS module, but we will take
a look at Round and track4free.


Tom - yes, got the win32 extension working, and the com interface
to google earth is working fine...

John.


>>> I'd like to write a python script to control Google Earth,
>>> and I've read that Google Earth provides a COM api, and that
>>> Python has a COM module 'pythoncom'.
> 
>> Io ho fatto prima ad acquistarne uno d'importazione molto ben fatto e
>> professionale, costo 250euro
> 
> What about Euro 108,90 for an AarLogic C05/03?
> 
> GE863-GPS-LP on PCB Easy integration into your tracking solution
> includes:
> - Combinde GPRS / GPS modules GE863-GPS-LP
> - SIM card holder
> - Power supply (6-40V)
> - 2x UF.L antenna connector for GPS+GSM
> - License free Python interpreter:
> 
> Price list here
> http://www.roundsolutions.com/pdf/Round%20Price-GSM%2BAcc-Euros.pdf
> Further details on Aarlogic are mentioned here:
> http://roundsolutions.com/pdf/Designing-mobile-devices.pdf
> 
> Free of charger test server for tracking http://www.track4free.com
> The Python binary file is for free as well. If you upload it to
> AarLogic C05/03, then you will have a PCB that starts with
> transmitting of postion to Track4free.
> 
> http://www.roundsolutions.com/uk_track4free.htm
> Innovative positioning package from Round Solutions:
> 
> Website and starter kit for tracking applications
> 
> Dreieich, March 15th 2007 - Round Solutions, a specialist and value-
> added distributor for M2M applications, is now offering its customers
> an attractive developer package. This includes the access to the
> www.track4free.com website and a starter kit based on what is
> currently the world's smallest GPRS GPS module. The package assists
> system integrators in the development of compact and inexpensive
> tracking solutions.
> The latest positioning package from Round Solutions is based in the
> customer's access to the www.track4free.com website. This track4free
> server relies on Google Maps and offers free global GPS positioning.
> To use the online platform, a function-enabled GPS device is needed
> that can transmit geographical data via HDCSD, GPRS, EDGE or UMTS.
> Following registration with track4free, the user is shown examples of
> a map that illustrates his or her positional data along with a range
> of other information. This is enhanced by extensive documentation
> about the movements made by the user's device. Users can register up
> to two applications per account.
> Starter kit promotes development
> System integrators also have the option of using the Round Solutions
> starter kit when developing their tracking application. The Basic
> Board S3 is based on what is currently the world's smallest combined
> GPRS-GPS module, equipped with extremely small embedded antennas. The
> starter kit's core component is a licence-free Phython interpreter
> with a free-of-charge Phython code. This transmits the device's GPS
> position to the track4free server. The HTTP protocol is provided free
> of charge.
> The starter kit has been developed completely as a BGA design. It
> assists developers in their mission to create very small and
> inexpensive positioning devices for various fields of application.
> Extensive additional services
> Round Solutions supports system integrators with design-in services
> and bespoke adaptations for integrated antennas. If developers have
> any queries, they can access 24-hour support from the world's biggest
> GSM / GPRS / UMTS / GPS user community, which has more than 3,000
> members from all over the globe.
> Premium customers can also have their designs and devices checked and
> tested free of charge by Round Solutions. The package is supplemented
> by a free marketing service, which establishes contact with several
> thousand companies. "Our services make it significantly easier for our
> customers to sell their products," explains Ben Hoelke, CEO of Round
> Solutions.
> 
> About Round Solutions
> Round Solutions is a leading, internationally active supplier of
> products, services and concepts for industrial users of electronic
> components. The focus lies on wireless technologies such as GSM, UMTS,
> GPS, Bluetooth, ZigBee, WIFI, UWB and ISM. The product portfolio
> ranges from starter kits to components for mass production. Round
> Solutions offers a wide range of electronic components such as radio
> modules, HF cables and ultra-sensitive antennas. Round Solutions
> currently has the world's largest range of quad-band and penta-band
> antennas. Unlike its competitors, integrated antennas are already
> available in small quantities at Round Solutions. Its stock also
> includes lithium polymer, lithium-ion and nickel-metal hydride
> batteries. Moreover, Round Solutions offers a global express delivery
> service. With the compact and innovative components from Round
> Solutions, system integrators can develop their solutions quickly,
> easily 

Re: logging.SocketHandler connections

2007-11-21 Thread oj
On Nov 20, 8:32 pm, Vinay Sajip <[EMAIL PROTECTED]> wrote:
> On Nov 20, 1:47 pm, oj <[EMAIL PROTECTED]> wrote:
>
> > On Nov 20, 12:26 pm, Vinay Sajip <[EMAIL PROTECTED]> wrote:
>
> > > Can you confirm that if you add the while loop back in, all messages
> > > are seen by the server? It worked for me.
>
> > Yes, it works in that case. This was meant to be implied by my earlier
> > messages, but on reflection, isn't obvious.
>
> > As I said previously, the point is sorta moot, but if you do have an
> > explanation as to why it behaves that way, or how I'm causing it, I
> > would be interested.
>
> > -Oliver
>
> How can you be sure that buffering is not happening at the server end?
>
> Vinay

Because the server closes the connection after receiving the first
message, which is before the client has even sent the second message.

Although a packet capture is revealing something more interesting.
After receiving the first message, the server sends a FIN/ACK back to
the client, and the client responds with an ACK. However, the client
doesn't send a FIN/ACK back, it tries to maintain the connection and
at the next message sends a packet on the same connection (with PSH/
ACK flags set), to which the server responds RST, which is reasonable,
since as far as it's concerned, it's closed that connection.

So the client has tried, and failed to send the second message.

The client makes no attempt to send the third message.

So basically, the client, the SocketHandler, isn't closing the
connection when the server closes the connection, which isn't
necessarily a problem, but there is still at least one message that
the client logs that generates no network traffic at all.

These tests were done with the time between messages set at 2 seconds.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python web frameworks + adobe flex

2007-11-21 Thread SamFeltus
I never used the Django AMF, I use JSON to go between Python and
Flex.  It works well, but lacks easy 2 way communication of course.
Interfacing with Flex is a gaping hole in the Python libraries.
Python needs a web framework that embraces Flex from the ground up,
HTML being such a limited web display technology.  There's not much of
a standard for Python and Flex, and in a short period of time, you
have to start rolling your own.

That being said, Django and Flex do blend well.


On Nov 21, 7:25 am, "Sells, Fred" <[EMAIL PROTECTED]>
wrote:
> slight shift of topic here.
>
> I'm a newbie at standard web stuff.  Mostly java webstart and a little 
> mod_python.
>
> I experimented with Adobe Flex and really loved it for doing the front end.  
> The backend needs to provide xml, json or AMF (an adobe proprietary binary 
> format). For prototyping, I was able to put xml or json responses in text 
> files and used that to work out the UI and do some cool demos.  But I never 
> got past prototyping, getting stuck in the "which python webfamework is best" 
> mobius loop.
>
> My Question: Does anyone have experience with Flex+Python and especially with 
> Adobe's AMF.  I've got some time to try to setup a "standard" and am a bit 
> short on hands-on experinece.

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


Re: Clean way to get one's network IP address?

2007-11-21 Thread Gilles Ganault
On Wed, 21 Nov 2007 07:20:45 -0800 (PST), Paul McGuire
<[EMAIL PROTECTED]> wrote:
>Be aware that it is very possible to have multiple IP addresses from
>which to choose

Yup, but this is the local host, and it only has a single interface.
Should I look into os.environ() or something like that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compiling python 2.5, missing zlib

2007-11-21 Thread mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
On Nov 19, 8:22 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Those headers are already installed, according to "up2date". Is there
> > a way to specify the header files used?
>
> It will automatically use them if they are good. What's the value of
> ZLIB_VERSION in /usr/include/zlib.h?
>
> Regards,
> Martin

I got my Python compile to work, by setting recompiling the zlib
source I downloaded with a --shared configure option.

Now I'm having trouble getting the Python MySQL module to install.
That'll be a separate post!

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


Re: Clean way to get one's network IP address?

2007-11-21 Thread Paul McGuire
On Nov 21, 9:15 am, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> Hello
>
> I need to get the local computer's IP address, ie. what's displayed
> when running "ifconfig" in Linux:
>
> # ifconfig
> eth0  Link encap:Ethernet  HWaddr 00:15:58:A1:D5:6F  
>   inet addr:192.168.0.79  Bcast:192.168.0.255
> Mask:255.255.255.0
>
> I know about socket.gethostbyname, but this relies on what's in
> /etc/hosts, and I'd rather have a more independent solution.
>
> What would be a good way to do this?
>
> Thank you.

Be aware that it is very possible to have multiple IP addresses from
which to choose (systems have multiple network adapters, VPNs,
wireless, etc.), so the question might not be how to get THE IP
address, but how to get THE RIGHT IP address.  Selecting the right IP
address from among several is not always clear cut.

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


new is missing in module hmac SHA-based encryption function in Python

2007-11-21 Thread Hailong Wang
Hi,

I have small hmac encryption programm by python, but always complain that
hmac module does not have attribute new, do I need to install anything
additinal in my laptop? I am using python 2.5.1

import hmac
import md5
import sha
myhmac = hmac.new("test")


Traceback (most recent call last):
  File "C:\Python25\hw_script\hmac.py", line 1, in 
import hmac
  File "C:\Python25\hw_script\hmac.py", line 4, in 
myhmac = hmac.new("test")
AttributeError: 'module' object has no attribute 'new'


Thank you very much,


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

Clean way to get one's network IP address?

2007-11-21 Thread Gilles Ganault
Hello

I need to get the local computer's IP address, ie. what's displayed
when running "ifconfig" in Linux:

# ifconfig
eth0  Link encap:Ethernet  HWaddr 00:15:58:A1:D5:6F  
  inet addr:192.168.0.79  Bcast:192.168.0.255
Mask:255.255.255.0

I know about socket.gethostbyname, but this relies on what's in
/etc/hosts, and I'd rather have a more independent solution.

What would be a good way to do this?

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


Re: Python too complex ?!?!?!

2007-11-21 Thread BlueBird



On Nov 20, 9:36 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> FWIW it's trivial to run pyflakes on your code (automatically behind
> the scenes) to get syntax checking; in vim, my syntax errors get
> underlined immediately for python code.

Can you describe your setup a bit more precisely ? I'm interested in
this kind of development help. I had a quick look at pyflakes but I
haven't found any signs of vim integration.

> I also get function prototypes on the status line

I'm interested in that as well !

   regards,

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


Re: how to change current working directory while using pdb within emacs

2007-11-21 Thread Diez B. Roggisch
duyanning wrote:

> I have written a pyhton script that will process data file in current
> working directory.
> My script is in an different directory to data file.
> When I debug this script using pdb within emacs, emacs will change the
> current working directory to the directory which include the script,
> so my script cannot find the data file.
> 
> I think this is the problem of emacs because when I start pdb from
> console directly, it will not change current working directory to the
> one of script being debugged.

Just issue

import os
os.chdir('whatever')

inside the pdb-session. Unfortunate, but should work.

Diez


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


RE: Python web frameworks + adobe flex

2007-11-21 Thread Sells, Fred
slight shift of topic here.

I'm a newbie at standard web stuff.  Mostly java webstart and a little 
mod_python.

I experimented with Adobe Flex and really loved it for doing the front end.  
The backend needs to provide xml, json or AMF (an adobe proprietary binary 
format). For prototyping, I was able to put xml or json responses in text files 
and used that to work out the UI and do some cool demos.  But I never got past 
prototyping, getting stuck in the "which python webfamework is best" mobius 
loop.

My Question: Does anyone have experience with Flex+Python and especially with 
Adobe's AMF.  I've got some time to try to setup a "standard" and am a bit 
short on hands-on experinece.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: s[i:j:t] = t stipulation

2007-11-21 Thread Neil Cerutti
On 2007-11-20, Terry Reedy <[EMAIL PROTECTED]> wrote:
> "Neil Cerutti" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>| s[i:j:t] = t (1) t must have the same length as the slice it is 
> replacing.
>
> This is essentially the same rule as requiring a proper length
> of t for
>
> a,b,c = t # for whatever number of targets
>
> And people have made similar suggestions as below for that case
> also.
>
>|  Why?
>
> A mismatch could be intentional or accidental.  In most cases
> of this sort, Python assumes 'accident', especially when intent
> can easily be indicated otherwise.

Thanks. Assignment to slices are a convenient way to insert,
assign, and delete elements, but extended slices are only good
for assignment. Perhaps I was searching for consistency in the
wrong place, though.

>| >>> def foo():
>| ...   while True:
>| ... yield 'a'
>| ...
>| >>> foo()
>| >>> x = range(10)
>| >>> x[::2] = foo()
>|
>| This is infinite loop due to Python building a sequence out of
>| the iterator to check its length.
>|
>| I think it might be more useful for
>|
>| x[::2] = foo()
>|
>| to result in an x of
>|
>| ['a', 1, 'a', 3, 'a', 5, 'a', 7, 'a', 9]
>|
>| In other words, take (j-i)//k elements from t for abs(k) != 1.
>
> Use the appropriate itertools function to take the proper
> number of elements.

And anyway my math was quite wrong. :(

>| A problem, though, arises when t is too short--the sequence
>| could be corrupted before an exception is thrown if you omit the
>| length check.
>|
>| So you'd also have to define
>|
>| x[::2] = 'aaa'
>|
>| as resulting in
>|
>| ['a', 1, 'a', 2, 'a', 3, 5, 7, 9]
>
> No, it should be defined as resulting in
>
> ['a', 1, 'a', 2, 'a', 3, None, 5, None, 7, None, 9] # ;-)

I thought deletion of elements would be more similar to slice
assignment, e.g.:

x[5:] = [] 
  --> [0, 1, 2, 3, 4]
  -/ /-> [0, 1, 2, 3, 4, None, None, None, None, None]

> Or better yet, require the programmer to specify by modifying
> either the target or source spec, as is done now.

It seems a shame to accept iterators but to build a sequence out
of them, if it can be avoided. But if there's too much confusion
about what it should mean, I guess that kills the idea.

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


Re: Python web frameworks

2007-11-21 Thread Joe Riopel
On Nov 21, 2007 5:42 AM, joe jacob <[EMAIL PROTECTED]> wrote:
> Thanks everyone for the response. From the posts I understand that
> Django and pylons are the best. By searching the net earlier I got the
> same information that Django is best among the frameworks so I
> downloaded it and I found it very difficult to configure. I referred
> the djangobook. Is pylons better in terms of performance and ease of
> study compared to Django.

I have only used Pylons for the simplest of applications (Not because
I don't think it can handle complex applications, but because I am
trying to learn the framework) and find it very easy to configure.
That said, I think it's definitely worth your time to to either give
Pylons a try, or give Django more time.

This thread has been going for only a few days now, and I wouldn't
expect you'd have very intimate knowledge with any framework.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python web frameworks

2007-11-21 Thread Jeff
On Nov 21, 6:25 am, Bruno Desthuilliers  wrote:
> joe jacob a écrit :
> (snip)
>
> > Thanks everyone for the response. From the posts I understand that
> > Django and pylons are the best. By searching the net earlier I got the
> > same information that Django is best among the frameworks so I
> > downloaded it and I found it very difficult to configure.
>
> ???
>
> It's been a couple of years since I last used Django, but I don't
> remember any specific complexity wrt/ configuration.

The only difficulties I have had have been with serving static media.
Specifically, in the differences in setup between the development
environment and production, and setting it up so that I don't have to
make any changes to the code in order to roll out upgrades to a
product.

My employer (a large local newspaper) has been using Django for about
while now.  We get a decent amount of traffic and it has scaled very
nicely.  The only area where there were any problems was with our
MySQL server; abstracting your DB code with an ORM is not as efficient
as doing your own custom SQL, at least in terms of performance (in
terms of development time, it certainly outweighs the performance hit
in most cases).  However, we were running quite a few sites off of
that database at the time, and that had a lot to do with it as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python web frameworks

2007-11-21 Thread Sells, Fred

-snip--
> 
> Thanks everyone for the response. From the posts I understand that
> Django and pylons are the best. By searching the net earlier I got the
> same information that Django is best among the frameworks so I
> downloaded it and I found it very difficult to configure. I referred
> the djangobook. Is pylons better in terms of performance and ease of
> study compared to Django.
> -- 
I too was confused by the setup, but I got help from the django site and found 
it was worth the effort.  I'm also not too experienced at web "stuff" with 
python FWIW. 
-- 
http://mail.python.org/mailman/listinfo/python-list


how to change current working directory while using pdb within emacs

2007-11-21 Thread duyanning
I have written a pyhton script that will process data file in current
working directory.
My script is in an different directory to data file.
When I debug this script using pdb within emacs, emacs will change the
current working directory to the directory which include the script,
so my script cannot find the data file.

I think this is the problem of emacs because when I start pdb from
console directly, it will not change current working directory to the
one of script being debugged.

please help me.
thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging and propagation

2007-11-21 Thread Diez B. Roggisch
Paul Rudin wrote:

> oj <[EMAIL PROTECTED]> writes:
> 
>> On Nov 21, 11:48 am, Paul Rudin <[EMAIL PROTECTED]> wrote:
> 
>>> Loggers have a "propagate" attribute. If you set this to False in the
>>> child then you should get what you want I think.
>>
>> No, because I want message to propagate usually. There are only
>> specific instances when I don't want it to propagate.
> 
> Can't you set propagate to False during those specific instances and 1
> the rest of the time?

That calls for concurrency-issues, doesn't it?

I think he will have to go down the subclass-route.

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


Re: logging and propagation

2007-11-21 Thread Paul Rudin
oj <[EMAIL PROTECTED]> writes:

> On Nov 21, 11:48 am, Paul Rudin <[EMAIL PROTECTED]> wrote:

>> Loggers have a "propagate" attribute. If you set this to False in the
>> child then you should get what you want I think.
>
> No, because I want message to propagate usually. There are only
> specific instances when I don't want it to propagate.

Can't you set propagate to False during those specific instances and 1
the rest of the time?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging and propagation

2007-11-21 Thread oj
On Nov 21, 11:48 am, Paul Rudin <[EMAIL PROTECTED]> wrote:
> oj <[EMAIL PROTECTED]> writes:
> > Hi,
>
> > I want to setup logging with two loggers:
>
> > The child logger is used when something different needs to be done
> > with the log record, and the log record will propagate and be logged
> > by the root logger as usual.
>
> > However, there are certain times when I don't want a log record to
> > propagate from the child to the parent.
>
> > I don't really want to add a filter to the root logger, as it should
> > be up to the child whether the record propagates or not.
>
> > I've tried setting the child to a lower level then the parent, but if
> > a record is dealt with by the child, the parent deals with it anyway
> > regardless of its own log level.
>
> > Also, filters only apply particular handlers and do not affect
> > propagation.
>
> > Can anyone suggest a simple way to achieve this?
>
> > Currently, the only thing I can think of, is overriding the
> > callHandlers method in a custom Logger class.
>
> Loggers have a "propagate" attribute. If you set this to False in the
> child then you should get what you want I think.

No, because I want message to propagate usually. There are only
specific instances when I don't want it to propagate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging and propagation

2007-11-21 Thread Paul Rudin
oj <[EMAIL PROTECTED]> writes:

> Hi,
>
> I want to setup logging with two loggers:
>
> The child logger is used when something different needs to be done
> with the log record, and the log record will propagate and be logged
> by the root logger as usual.
>
> However, there are certain times when I don't want a log record to
> propagate from the child to the parent.
>
> I don't really want to add a filter to the root logger, as it should
> be up to the child whether the record propagates or not.
>
> I've tried setting the child to a lower level then the parent, but if
> a record is dealt with by the child, the parent deals with it anyway
> regardless of its own log level.
>
> Also, filters only apply particular handlers and do not affect
> propagation.
>
> Can anyone suggest a simple way to achieve this?
>
> Currently, the only thing I can think of, is overriding the
> callHandlers method in a custom Logger class.

Loggers have a "propagate" attribute. If you set this to False in the
child then you should get what you want I think.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting a list of list

2007-11-21 Thread Matt Nordhoff
Tim Chase wrote:
>> are there available library or pythonic algorithm for sorting a list
>> of list depending on the index of the list inside the list of my
>> choice?
> 
> The built-in sorted() function and the sort() method on various
> collections take an optional "key=function" keyword paramater
> with which you can pass a function (lambdas are convenient) to
> extract the bit on which you want to compare:
> 
 d_list = [
> ... ['a', 1, 9],
> ... ['b', 2, 8],
> ... ['c', 3, 7],
> ... ['d', 4, 6],
> ... ['e', 5, 5],
> ... ]
 print sorted.__doc__
> sorted(iterable, cmp=None, key=None, reverse=False) --> new
> sorted list
 sorted(d_list, key=lambda x: x[2]) # sort by the 3rd item
> [['e', 5, 5], ['d', 4, 6], ['c', 3, 7], ['b', 2, 8], ['a', 1, 9]]
 sorted(d_list, key=lambda x: x[1]) # sort by the 2nd item
> [['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5]]
 sorted(d_list, key=lambda x: x[0]) # sort by the 1st item
> [['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5]]

Not to be too complicated, but there are functions that return a
callable that is faster than a lambda.

>>> import operator

Then, instead of "lambda x: x[2]" use "operator.itemgetter(2)" and
instead of "lambda x: x.foo" use "operator.attrgetter('foo')".
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


logging and propagation

2007-11-21 Thread oj
Hi,

I want to setup logging with two loggers:

The child logger is used when something different needs to be done
with the log record, and the log record will propagate and be logged
by the root logger as usual.

However, there are certain times when I don't want a log record to
propagate from the child to the parent.

I don't really want to add a filter to the root logger, as it should
be up to the child whether the record propagates or not.

I've tried setting the child to a lower level then the parent, but if
a record is dealt with by the child, the parent deals with it anyway
regardless of its own log level.

Also, filters only apply particular handlers and do not affect
propagation.

Can anyone suggest a simple way to achieve this?

Currently, the only thing I can think of, is overriding the
callHandlers method in a custom Logger class.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python web frameworks

2007-11-21 Thread Bruno Desthuilliers
joe jacob a écrit :
(snip)
> Thanks everyone for the response. From the posts I understand that
> Django and pylons are the best. By searching the net earlier I got the
> same information that Django is best among the frameworks so I
> downloaded it and I found it very difficult to configure.

???

It's been a couple of years since I last used Django, but I don't 
remember any specific complexity wrt/ configuration.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging module: removing handlers

2007-11-21 Thread Michele Simionato
On Nov 21, 11:08 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Having thought more about this, it _has_ to be that way - think of one
> handler attached to several loggers. Removing AND closing it from one would
> render it useless for others. You can't want that to happen.

You have a point.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python web frameworks

2007-11-21 Thread joe jacob
On Nov 21, 10:15 am, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> On Nov 21, 1:37 pm, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Nov 20, 3:39 pm, Graham Dumpleton <[EMAIL PROTECTED]>
> > wrote:
>
> > > This only holds if actually hosted on Apache. As Django these days
> > > supports WSGI interface there is nothing to stop it being run with
> > > other hosting solutions that support WSGI. So, you could host it under
> > > paster or CherryPy WSGI servers. You could even run it under CGI if
> > > you were really desperate using a CGI-WSGI adapter. So, it isn't
> > > strictly correct to say it is as a multiprocess framework specifically
> > > for mod_python, although the developers will admit in the first
> > > instance that they didn't design the internals with multithreading in
> > > mind. That said, there aren't believed to be any multithreading issues
> > > in Django itself at this time.
>
> > > People keep pushing this barrow about the GIL and multithreading being
> > > a huge problem, when in the context of Apache it is isn't, at least
> > > not to the degree people make out. The reason for this is that when
> > > using worker MPM it sill acts as a multi process web server even
> > > though each process is also multithreaded. Within those worker MPM
> > > child processes there is also a lot going on that doesn't involve
> > > Python code nor the GIL, for example initial request process and
> > > serving up of static files etc.
>
> > > Result is that the Python GIL is no impediment when using Apache on
> > > UNIX to making good use of multiple processors or cores, even when
> > > Apache worker MPM is used.
>
> > I understand about a fifth of this exchange but I'm glad it's here so
> > I can follow links and search on the terminology. I couldn't tell from
> > earlier posts if mod_python was good or bad.
>
> Version 3.3 of mod_python fixed up a lot of issues that existed with
> older versions of mod_python. There are still a lot of issues in
> mod_python unfixed.
>
>  https://issues.apache.org/jira/browse/MODPYTHON
>
> In the main people will not run into these issues, of if they do, the
> incidence of them causing a direct or significant impact is low, or
> with people just tolerating the problems.
>
> If you want to be where hosting with Apache is heading, then look at
> mod_wsgi (http://www.modwsgi.org) instead. People will say I am biased
> because I wrote it, but I was also the main person who did the more
> recent work on fixing up mod_python and am more aware than others of
> what problems still exist in mod_python.
>
> To be frank, unless some white knight comes along and dives into
> mod_python and fixes up the remaining issues, then you probably will
> not see any significant future updates to mod_python and it will just
> stagnate. I certainly will not be devoting much time to mod_python any
> more.
>
> Part of the problem with mod_python is that the code base has grown
> over time and is long overdue for a complete rethink, which is in part
> what mod_wsgi was about, ie., making the code and configuration a lot
> simpler and safer for use in web hosting environments.
>
> Thus mod_wsgi takes aspects of what mod_python does, combining it with
> aspects of how FASTCGI solutions work. This gives the option of
> embedding a Python application in Apache for maximum speed, or using
> daemon processes as means of being able to better separate multiple
> applications.
>
> Most importantly, mod_wsgi supports WSGI directly, making it
> reasonably trivial to run any Python web framework or application
> which supports the WSGI standard.
>
> > The Django book says: "Apache with mod_python currently is the most
> > robust setup for using Django on a production server."
>
> > Is that true?
>
> I would say that that is now debatable. Overall mod_wsgi is probably a
> better package in terms of what it has to offer. Only thing against
> mod_wsgi at this point is peoples willingness to accept something that
> is new in conjunction with Linux distributions and web hosting
> companies being slow to adopt new packages.
>
> Various people are quite happily using mod_wsgi. Users of mod_wsgi
> range from people trying to run it in memory constrained VPS systems,
> right up to major sites serving up to between 3-4 million hits a day.
>
> There have been a few odd things come up since the initial release
> which have since been fixed, but the core is showing itself to be very
> solid.
>
> Graham

Thanks everyone for the response. From the posts I understand that
Django and pylons are the best. By searching the net earlier I got the
same information that Django is best among the frameworks so I
downloaded it and I found it very difficult to configure. I referred
the djangobook. Is pylons better in terms of performance and ease of
study compared to Django.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Management

2007-11-21 Thread Jens
On 21 Nov., 05:34, Ben Finney <[EMAIL PROTECTED]>
wrote:

>
> I hope the above makes it clearer what I prefer for this situation.
>

It does. You've been most helpful - thanks a lot! I'll bookmark this
thread and keep it under my pillow :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging module: removing handlers

2007-11-21 Thread Diez B. Roggisch
Michele Simionato wrote:

> On Nov 21, 10:23 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> 
>> I can only guess - but I'd say if you can do
>>
>> foo.removeHandler(h)
>>
>> you can do
>>
>> foo.removeHandler(h)
>> h.close()
>>
>> easily. But not
>>
>> foo.removeHandler(h) # implicit closing
>> bar.addHandler(h)
>>
>> It does kind of make sense if you decouple the life-cycles IMHO.
>>
>> Diez
> 
> But what is the use case for removing an handler without closing it?

Having thought more about this, it _has_ to be that way - think of one
handler attached to several loggers. Removing AND closing it from one would
render it useless for others. You can't want that to happen.

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


Re: logging module: removing handlers

2007-11-21 Thread Michele Simionato
On Nov 21, 10:23 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> I can only guess - but I'd say if you can do
>
> foo.removeHandler(h)
>
> you can do
>
> foo.removeHandler(h)
> h.close()
>
> easily. But not
>
> foo.removeHandler(h) # implicit closing
> bar.addHandler(h)
>
> It does kind of make sense if you decouple the life-cycles IMHO.
>
> Diez

But what is the use case for removing an handler without closing it?

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


Re: logging module: removing handlers

2007-11-21 Thread Diez B. Roggisch
Michele Simionato schrieb:
> I have just discovered a bug in my code using the logging module, due
> to
> handlers not being closed properly. The issue was that I called the
> function
> removeHandler and I assumed that it took care of closing the handler,
> but it did not.
> Looking at the source code of logging/__init__.py I discovered that it
> is
> implemented as follows:
> 
> def removeHandler(self, hdlr):
> """
> Remove the specified handler from this logger.
> """
> if hdlr in self.handlers:
> #hdlr.close()
> hdlr.acquire()
> try:
> self.handlers.remove(hdlr)
> finally:
> hdlr.release()
> 
> The question is: why in the hell the "hdlr.close()" line is
> commented??
> I discovered this because we had locks in our production database
> (we were logging on the DB) and it was not easy to spot the source of
> the problem, so I would like to know the rationale for not closing
> the handler in removeHandler.

I can only guess - but I'd say if you can do

foo.removeHandler(h)

you can do

foo.removeHandler(h)
h.close()

easily. But not

foo.removeHandler(h) # implicit closing
bar.addHandler(h)

It does kind of make sense if you decouple the life-cycles IMHO.

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


Re: Recursive insertion of a line

2007-11-21 Thread Francesco Pietra

--- Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

> On Tue, 20 Nov 2007 01:16:53 -0800 (PST), Francesco Pietra
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
> 
> > 
> > Now, "file .out" had "TER" inserted where I wanted. It might well be that
> it
> > was my incorrect use of your script.
> >
>   Well, it looks like, for purposes of demonstration, the supplied
> program is using "print" statements, which write to stdout. Not sure why
> you needed some sort of pipe/tee call, a simple "> new.output.file"
> redirection would have done.

I used "2>&1 | tee" because in many cases I want to check the screen. That in
ab initio computations, where solving the matrix allows ample vision of the
screen. I agree that for the scope of this python script it is redundant.
>   
> > (2) An extra line is inserted (which was not a problem of outputting the
> file
> > as I did), except between "TER" and the next line, as shown below:
> >
>   A result of using "print"... "print" adds a newline on the data --
> but ".readline()" does not /remove/ the newline on the input data -- so
> unmodified lines now end with two newlines..
> 
>   A common .strip() call on those lines might be sufficient...

It is indeed. After a few trials (I am quite new to Python and I rarely find
time for programming, but this attitude might change with Python), the
following script fulfills the scope:


f=open("output.pdb", "r")
for line in f:
line=line.rstrip()
if line:
print line
f.close()



Thanks
francesco

> Or
> change the "print" statements to "sys.stdout.write(...)", and ensure
> that the "TER" is written /with/ a newline ("TER\n").
> -- 
>   WulfraedDennis Lee Bieber   KD6MOG
>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/
>   (Bestiaria Support Staff:   [EMAIL PROTECTED])
>   HTTP://www.bestiaria.com/
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



  

Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-- 
http://mail.python.org/mailman/listinfo/python-list


logging module: removing handlers

2007-11-21 Thread Michele Simionato
I have just discovered a bug in my code using the logging module, due
to
handlers not being closed properly. The issue was that I called the
function
removeHandler and I assumed that it took care of closing the handler,
but it did not.
Looking at the source code of logging/__init__.py I discovered that it
is
implemented as follows:

def removeHandler(self, hdlr):
"""
Remove the specified handler from this logger.
"""
if hdlr in self.handlers:
#hdlr.close()
hdlr.acquire()
try:
self.handlers.remove(hdlr)
finally:
hdlr.release()

The question is: why in the hell the "hdlr.close()" line is
commented??
I discovered this because we had locks in our production database
(we were logging on the DB) and it was not easy to spot the source of
the problem, so I would like to know the rationale for not closing
the handler in removeHandler.

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


Re: Web update library in python?

2007-11-21 Thread Jorgen Bodde
Thanks everybody,

You gave me plenty of information to go on and look for something that
might give me a sound and solid solution to my problem!
I will look into bzr I've heard good things about it, and maybe I can
use it in my app!

Regards,
- Jorgen

On Nov 21, 2007 9:05 AM, A.T.Hofkamp <[EMAIL PROTECTED]> wrote:
> On 2007-11-20, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> > Jorgen Bodde wrote:
> >
> >> Hi, A.T.Hofkamp (sorry for not knowing your first name ;-),
>
> Well Jorgen, it is at the bottom of each post (usually)... ;-)
>
> >> SCM sounds like a term I can google for, if the tool needed is very
> >> easy to install, maybe even accompany with my application to run as a
> >> service for the updating, it is worth a try to find something that can
> >> handle the synchronizing of distributed repositories.
> >>
> >> Talking a bit more about it and hearing various solutions gave me more
> >> insight in how it might be solved. Thanks everybody for your input!
> >
> > SCM mean source code management - like SVN or CVS.
> >
> > Diez
>
> Diez is right, except my choice of the phrase 'SCM' was not exactly right. SCM
> is a general term for two kinds of activities, namely version control (VC) and
> configuration control.
> VC is what everybody does with SVN, CVS, darcs, bzr, git, mercurial, etc in 
> the
> context of software development (hence these tools are known as version 
> control
> systems (VCS)).
>
> You may want to add 'distributed' to your search term.
>
>
> Configuration management is much less often done. It is about controlling
> deployment of some system or software. Imagine you are managing a few
> (hundreds) of web sites. They all use LAMP, but exactly what Apache, Py-Mod,
> Linux, hardware, is different each time. This of course also holds for the
> various initialization and configuration files.
> Keeping track of this data over time is called configuration management.
> (and if you think this is complicated, consider what Boeing is doing for all
> its air-planes... :) ).
>
>
> > SVN isn't distributed, but AFAIK darcs is.
> >
>
> As Diez already guessed, SVN and CVS are organized around a central 
> repository,
> darcs, bzr, git, and mercurial do not need a central repository (although they
> often can handle one if the project wants it).
>
> The nice thing is that at least bzr and mercurial are written in Python!!
>
>
> What I found very enlightening was to find the web-site of these tools, and
> then read the docs about their strong and weak points w.r.t. their 
> competitors.
> Of course each of these is biased, but if you read them all, it kind of
> balances out :)
> Also, they all explain what their world model is, you should check whether 
> that
> matches with your problem.
>
> Good luck with your search,
> Albert
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web update library in python?

2007-11-21 Thread A.T.Hofkamp
On 2007-11-20, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Jorgen Bodde wrote:
>
>> Hi, A.T.Hofkamp (sorry for not knowing your first name ;-),

Well Jorgen, it is at the bottom of each post (usually)... ;-)

>> SCM sounds like a term I can google for, if the tool needed is very
>> easy to install, maybe even accompany with my application to run as a
>> service for the updating, it is worth a try to find something that can
>> handle the synchronizing of distributed repositories.
>> 
>> Talking a bit more about it and hearing various solutions gave me more
>> insight in how it might be solved. Thanks everybody for your input!
>
> SCM mean source code management - like SVN or CVS.
>
> Diez

Diez is right, except my choice of the phrase 'SCM' was not exactly right. SCM
is a general term for two kinds of activities, namely version control (VC) and
configuration control. 
VC is what everybody does with SVN, CVS, darcs, bzr, git, mercurial, etc in the
context of software development (hence these tools are known as version control
systems (VCS)).

You may want to add 'distributed' to your search term.


Configuration management is much less often done. It is about controlling
deployment of some system or software. Imagine you are managing a few
(hundreds) of web sites. They all use LAMP, but exactly what Apache, Py-Mod,
Linux, hardware, is different each time. This of course also holds for the
various initialization and configuration files.
Keeping track of this data over time is called configuration management.
(and if you think this is complicated, consider what Boeing is doing for all
its air-planes... :) ).


> SVN isn't distributed, but AFAIK darcs is.
>

As Diez already guessed, SVN and CVS are organized around a central repository,
darcs, bzr, git, and mercurial do not need a central repository (although they
often can handle one if the project wants it).

The nice thing is that at least bzr and mercurial are written in Python!!


What I found very enlightening was to find the web-site of these tools, and
then read the docs about their strong and weak points w.r.t. their competitors.
Of course each of these is biased, but if you read them all, it kind of
balances out :)
Also, they all explain what their world model is, you should check whether that
matches with your problem.

Good luck with your search,
Albert

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