Re: no cleanup on TERM signal

2008-05-01 Thread Marc 'BlackJack' Rintsch
On Fri, 02 May 2008 04:36:06 +, Yves Dorfsman wrote:

> x.del() gets executed if:
> -I del x, then run gc.collect()
> -simply exit the script
> -get the script to abort on an exception
> 
> But if I kill it with the default signal TERM, the script dies, but I don't 
> get the message, so I am assuming that python isn't taking the time to 
> cleanup, even though that is (was) what TERM was intended for.
> 
> Has this been discussed before ? Is worth a suggestion (PEP) ?

There is the docs for `__del__()` saying this method is not guaranteed to
be called at all.  Don't use it if you *need* that method to be called. 
Just like `finalize()` in Java, it can't be used for deterministic
destruction, so it's not that useful after all.

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


Re: help with list comprehension

2008-05-01 Thread Matimus
On May 1, 10:50 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On May 1, 11:46 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
>
>
>
> > Yves Dorfsman wrote:
>
> > > In the following script, m1() and m2() work fine. I am assuming m2() is
> > > faster although I haven't checked that (loops through the list twice
> > > instead of once).
>
> > Well, let's check it:
>
> > $ python -m timeit -s "import x" "x.m1()"
> > 10 loops, best of 3: 6.43 usec per loop
>
> > $ python -m timeit -s "import x" "x.m2()"
> > 10 loops, best of 3: 8.34 usec per loop
>
> > As it turns out, m1 is faster than m2. The reason is that list
> > comprehensions do the loop in C, whereas the for-append pattern does the
> > loop on the Python level.
>
> > > Now what I am trying to do is something like m3(). As currently written
> > > it does not work, and I have tried different ways, but I haven't managed
> > > to make it work.
>
> > > Is there a possibility ? Or is m2() the optimum ?
>
> > > [...]
> > > def m1():
> > >   colours = [ e['colour'] for e in l ]
> > >   nums= [ e['num']for e in l ]
>
> > > def m2():
> > >   colours = []
> > >   nums= []
> > >   for e in l:
> > > colours.append(e['colour'])
> > > nums.append(e['num'])
>
> > > #def m3():
> > > #  colours, nums = [ e['colour'], e['num'] for e in l ]
>
> > m3 doesn't work because you're building a list of 10 color/number pairs
> > that you're trying to unpack that into just two names. The working
> > "derivative" of m3 is m1, which is the most natural, fastest and
> > clearest solution to your problem.
>
> Another alternative is:
>
> from operator import itemgetter
>
> def m3():
> colours, nums = zip(*map(itemgetter('colour','num'), l))
>
> It's slower than m1() but faster than m2(); it's also the most
> concise, especially if you extract more than two keys.
>
> George

Why deal with zip and unpacking? This seems more obvious to me:

colours, nums = map(itemgetter('colour'), l), map(itemgetter('num'),
l)

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread Ben Finney
"D'Arcy J.M. Cain" <[EMAIL PROTECTED]> writes:

> On Fri, 02 May 2008 13:24:01 +1000
> Ben Finney <[EMAIL PROTECTED]> wrote:
> > I much prefer "#! /usr/bin/python" because I want my Python
> > programs to, by default, be run with the default Python, and
> > depend on Python being installed by the operating system's package
> > manager. On systems that use shebang lines and that actually have
> > standardised filesystem locations, the default Python is found at
> > '/usr/bin/python'.
> 
> You have lived a sheltered life.  Not every packaging system puts the
> executible in /usr/bin.  Many systems use /usr/local/bin.

They use that for the operating-system-installed default Python
interpreter? Colour me incredulous.

-- 
 \   “[The RIAA] have the patience to keep stomping. They’re |
  `\playing whack-a-mole with an infinite supply of tokens.” |
_o__)  —kennon, http://kuro5hin.org/ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: help with list comprehension

2008-05-01 Thread George Sakkis
On May 1, 11:46 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> Yves Dorfsman wrote:
>
> > In the following script, m1() and m2() work fine. I am assuming m2() is
> > faster although I haven't checked that (loops through the list twice
> > instead of once).
>
> Well, let's check it:
>
> $ python -m timeit -s "import x" "x.m1()"
> 10 loops, best of 3: 6.43 usec per loop
>
> $ python -m timeit -s "import x" "x.m2()"
> 10 loops, best of 3: 8.34 usec per loop
>
> As it turns out, m1 is faster than m2. The reason is that list
> comprehensions do the loop in C, whereas the for-append pattern does the
> loop on the Python level.
>
>
>
> > Now what I am trying to do is something like m3(). As currently written
> > it does not work, and I have tried different ways, but I haven't managed
> > to make it work.
>
> > Is there a possibility ? Or is m2() the optimum ?
>
> > [...]
> > def m1():
> >   colours = [ e['colour'] for e in l ]
> >   nums    = [ e['num']    for e in l ]
>
> > def m2():
> >   colours = []
> >   nums    = []
> >   for e in l:
> >     colours.append(e['colour'])
> >     nums.append(e['num'])
>
> > #def m3():
> > #  colours, nums = [ e['colour'], e['num'] for e in l ]
>
> m3 doesn't work because you're building a list of 10 color/number pairs
> that you're trying to unpack that into just two names. The working
> "derivative" of m3 is m1, which is the most natural, fastest and
> clearest solution to your problem.

Another alternative is:

from operator import itemgetter

def m3():
colours, nums = zip(*map(itemgetter('colour','num'), l))

It's slower than m1() but faster than m2(); it's also the most
concise, especially if you extract more than two keys.

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread Ben Finney
Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]> writes:

> -On [20080502 05:26], Ben Finney ([EMAIL PROTECTED]) wrote:
> >I've never clearly understood why people want to use "#!
> >/usr/bin/env python", which is prone to finding a different Python
> >from the one installed by the operating system. I'd be interested
> >to see what responses are in favour of it, and what the reasoning
> >is.
> 
> Simple, some systems are not as peculiar as a lot of Linux boxes
> which chug everything into /usr/bin, which is OS territory (as has
> been decreed long ago by hier(7)), but rather use /usr/local/bin
> (all BSD Unix and derivatives) or /opt or whatever convention a
> particular operating system has.

To my mind, the Python interpreter installed by a package as
distributed with the OS *is* OS territory and belongs in /usr/bin/.

> As such, your script with #!/usr/bin/python is as bad as an ash
> shell script with #!/bin/bash.

Clearly if the program is written to be interpreted by the Ash shell,
it should not declare Bash as the interpreter.

I don't see how declaring Python as the interpreter for a Python
program is supposed to be "as bad" as that.

-- 
 \ "Don't be afraid of missing opportunities. Behind every failure |
  `\  is an opportunity somebody wishes they had missed."  -- Jane |
_o__)  Wagner, via Lily Tomlin |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread Tim Roberts
Yves Dorfsman <[EMAIL PROTECTED]> wrote:
>
>On UNIX, some people use
>#!/usr/bin/env python
>
>While other use
>#!/usr/bin/python
>
>Why is one preferred over the other one ?

The /usr/bin/env solution finds the Python interpreter anywhere on the
PATH, whether it be /usr/bin or /usr/local/bin, or whatever.  With
/usr/bin/python, it MUST be in /usr/bin.

Way back when, Python wasn't included in Linux distributions by default, so
it was difficult to predict where it would be.  /usr/bin/env, on the other
hand, is well-established at that location.

These days, since Python is nearly ubiquitous, I suspect it is not so
important.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: portable fork+exec/spawn

2008-05-01 Thread Brendan Miller
On Fri, 02 May 2008 13:25:55 +1000, Ben Finney wrote:

> URL:http://docs.python.org/lib/module-subprocess.html

Awesome. This is exactly what I was hoping existed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: help with list comprehension

2008-05-01 Thread Karthik Gurusamy
On May 1, 8:01 pm, Yves Dorfsman <[EMAIL PROTECTED]> wrote:
> In the following script, m1() and m2() work fine. I am assuming m2() is
> faster although I haven't checked that (loops through the list twice instead
> of once).
>
> Now what I am trying to do is something like m3(). As currently written it
> does not work, and I have tried different ways, but I haven't managed to
> make it work.
>
> Is there a possibility ? Or is m2() the optimum ?
>
> Thanks.
>
> #!/usr/bin/python
>
> l = [ { 'colour': 'black',   'num': 0},
>{ 'colour': 'brown',   'num': 1},
>{ 'colour': 'red', 'num': 2},
>{ 'colour': 'orange',  'num': 3},
>{ 'colour': 'yellow',  'num': 4},
>{ 'colour': 'green',   'num': 5},
>{ 'colour': 'blue','num': 6},
>{ 'colour': 'violet',  'num': 7},
>{ 'colour': 'grey','num': 8},
>{ 'colour': 'white',   'num': 9}
>  ]
>
> def m1():
>colours = [ e['colour'] for e in l ]
>nums= [ e['num']for e in l ]
>
> def m2():
>colours = []
>nums= []
>for e in l:
>  colours.append(e['colour'])
>  nums.append(e['num'])
>
> #def m3():
> #  colours, nums = [ e['colour'], e['num'] for e in l ]
>

Looks like m1 is the cleanest; if you really want to run list-
comprehension once, one possible way:

>>> p = [ (e['colour'], e['num']) for e in l ]
>>> import operator
>>> map(operator.itemgetter(0), p)
['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue',
'violet', 'grey', 'white']
>>> map(operator.itemgetter(1), p)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Karthik
> --
> Yves.http://www.SollerS.ca

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread Jeroen Ruigrok van der Werven
-On [20080502 05:26], Ben Finney ([EMAIL PROTECTED]) wrote:
>I've never clearly understood why people want to use "#! /usr/bin/env
>python", which is prone to finding a different Python from the one
>installed by the operating system. I'd be interested to see what
>responses are in favour of it, and what the reasoning is.

Simple, some systems are not as peculiar as a lot of Linux boxes which
chug everything into /usr/bin, which is OS territory (as has been decreed
long ago by hier(7)), but rather use /usr/local/bin (all BSD Unix and
derivatives) or /opt or whatever convention a particular operating system
has.

And prone to find the wrong Python, it all depends upon proper $PATH
administration.

As such, your script with #!/usr/bin/python is as bad as an ash shell script
with #!/bin/bash. #!/usr/bin/env python is more cross-OS friendly, there's
more than just Linux you know.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
I dream of Love as Time runs through my hand...
--
http://mail.python.org/mailman/listinfo/python-list

Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Torsten Bronger
Hallöchen!

Ivan Illarionov writes:

> On Fri, 02 May 2008 01:21:38 +0200, Torsten Bronger wrote:
>
>> [...]
>> 
>> In contrast to many other areas of software, configuration files
>> needn't be compatible with anything except the user's brain.  So
>> even if the rest of the world uses config format X, you can
>> safely stick with config format Y.
>
> There are several reasons for compatibility:
>
> 1. The user or another developer might want to write GUI front-end
> to configure your app. With standard format this would be easier.

The libraries are there after all -- I don't speak about an own
format.

> [...]
>
> 3. Bigger applications that include your sofware as one of its
> components may need to automate configuration process and update
> several config files of different smaller apps from one global
> setting.

If you do something complex like this, porting an application to
another config format is the smallest problem.  Or in other words:
This is not something I'd optimise config handling for.

> That's precisely why first XML and now YAML became popular for
> config files.

I can't speak for YAML, but XML was not used for the config files I
have in mind, but as a machine-readable serialisation format for
apps settings that you can set in the app itself.

Tschö,
Torsten.

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread D'Arcy J.M. Cain
On Fri, 02 May 2008 13:24:01 +1000
Ben Finney <[EMAIL PROTECTED]> wrote:
> I much prefer "#! /usr/bin/python" because I want my Python programs
> to, by default, be run with the default Python, and depend on Python
> being installed by the operating system's package manager. On systems
> that use shebang lines and that actually have standardised filesystem
> locations, the default Python is found at '/usr/bin/python'.

You have lived a sheltered life.  Not every packaging system puts the
executible in /usr/bin.  Many systems use /usr/local/bin.  NetBSD
uses /usr/pkg/bin but allows you to define your own pkg root.
Using /usr/bin/env allows your code to run on all these systems.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


no cleanup on TERM signal

2008-05-01 Thread Yves Dorfsman

I did a few tests with this script:

class byebye:

  def __del__(self):
print 'Bye, bye...'


x = byebye()


x.del() gets executed if:
-I del x, then run gc.collect()
-simply exit the script
-get the script to abort on an exception

But if I kill it with the default signal TERM, the script dies, but I don't 
get the message, so I am assuming that python isn't taking the time to 
cleanup, even though that is (was) what TERM was intended for.


Has this been discussed before ? Is worth a suggestion (PEP) ?


--
Yves.
http://www.SollerS.ca
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Ben Finney <[EMAIL PROTECTED]> wrote:

> I've never clearly understood why people want to use "#! /usr/bin/env
> python", which is prone to finding a different Python from the one
> installed by the operating system. I'd be interested to see what
> responses are in favour of it, and what the reasoning is.
> 
> One possible reason is that the programmer is attempting to allow for
> systems where Python has been installed, but not from an operating
> system package.

You've got it exactly.

I'm currently using Python to write unit tests as part of a build system.  
Many of our development boxes don't have python installed in /usr/bin (or 
perhaps at all).  And even if they did, we might want to use a different 
version of Python on different branches of the code.

We've got Python built for all our platforms and the binaries stored in our 
source control system.  When you check out a particular branch, you get the 
right version of Python for that branch.  By having the Python scripts 
start with #!/usr/bin/env python, I can select the version of Python I want 
just by changing the environment.

Then, of course, I recently ran across a machine where env was installed in 
/opt/gnu/bin instead of /usr/bin.  Sigh.  Sometimes you just can't win.
--
http://mail.python.org/mailman/listinfo/python-list


Re: help with list comprehension

2008-05-01 Thread Carsten Haese

Yves Dorfsman wrote:


In the following script, m1() and m2() work fine. I am assuming m2() is 
faster although I haven't checked that (loops through the list twice 
instead of once).


Well, let's check it:

$ python -m timeit -s "import x" "x.m1()"
10 loops, best of 3: 6.43 usec per loop

$ python -m timeit -s "import x" "x.m2()"
10 loops, best of 3: 8.34 usec per loop

As it turns out, m1 is faster than m2. The reason is that list 
comprehensions do the loop in C, whereas the for-append pattern does the 
loop on the Python level.


Now what I am trying to do is something like m3(). As currently written 
it does not work, and I have tried different ways, but I haven't managed 
to make it work.


Is there a possibility ? Or is m2() the optimum ?

[...] 
def m1():

  colours = [ e['colour'] for e in l ]
  nums= [ e['num']for e in l ]

def m2():
  colours = []
  nums= []
  for e in l:
colours.append(e['colour'])
nums.append(e['num'])

#def m3():
#  colours, nums = [ e['colour'], e['num'] for e in l ]


m3 doesn't work because you're building a list of 10 color/number pairs 
that you're trying to unpack that into just two names. The working 
"derivative" of m3 is m1, which is the most natural, fastest and 
clearest solution to your problem.


HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to pass C++ object to another C++ function via Python function

2008-05-01 Thread grbgooglefan
On Apr 22, 7:54 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
>
> If you have a C function that receives a PyCObject, just include the  
> relevant headers (cobject.h) and you can retrieve the original pointer  
> using PyCObject_AsVoidPtr:
>
> void foo(PyObject *pyobj)
> {
>    TOriginalType *porig;
>    porig = (TOriginalType *)PyCObject_AsVoidPtr(pyobj);
>    // do something with porig
> }
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -

This works. But only once, means if I try to use this object second
time in Python function it causes crash.

What I am doing in my program is that I am putting STL map in a
structure & passing that structure as object to a Python function
alongwith other agurments of that Python function. This briefly as
below:

// In pyinterface.h file:---
typedef hash_map Elements;
typedef hash_map
PerExchGroupsElementsTable;
typedef struct capsule {
PerExchGroupsElementsTable* refgrps;
} *pcapsule;

// In pyinterface.cpp file:---
numvars = // value set depending on number of variables of that python
function
PyObject *pTuple = PyTuple_New(numvars);

// Set variables as below:
for(nCtr = 0; nCtr < numvars; nCtr++){
 slot = prul->pVarLst[nCtr].slot;
 ndtyp = ordvars[slot].dtype;
 switch(ndtyp){
   case(INT_T):
 
PyTuple_SetItem(pTuple,nCtr,PyInt_FromLong(ordvars[slot].nvalue));
   break;
   case(FLOAT_T):
 
PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(ordvars[slot].fvalue));
   break;
   case(STRING_T):
 
PyTuple_SetItem(pTuple,nCtr,PyString_FromString(ordvars[slot].cvalue));
   break;
   default:
   printf("\nUnknown data type [%d] for %s\n",ndtyp,prul-
>pVarLst[nCtr].var);
   bUnknownDataType = true;
   break;
 }
 if(bUnknownDataType){
ret = -1;
break;
 }
}

// Then set the C++ object as below:
if(ret == 0){
capsule grpob;
if(pGroups){
  grpob.refgrps = pGroups; // pGroups is pointer to
PerExchGroupsElementsTable map & is global.
  int ret = PyTuple_SetItem(pTuple,
(numvars-1),PyCObject_FromVoidPtr((void *)&grpob, NULL));
}
PyObject *pResult = PyObject_CallObject(pfunc,pTuple);
if(PyErr_Occurred()){
   printf("error occured in PyObject_CallObject for %s\n",prul-
>pyobj.szPyRouteName);
   PyErr_Print();
} else {
printf("Python function passed, use its result for other
purposes as designed\n");
}
Py_XDECREF(pResult);
Py_XDECREF(pTuple);
}

//-- My Pythong module & functions in it ---
//PyObject* pfunc is a Python function which I compile dynamically &
add to my Python module as below:
// One of such dynamically compiled function is as below:
char pyfunction[]=\
"def TSE581(t22,t52,t1012,ob):
   if(co1(ob,t22,\"TSE_FUTURE_GRP\") and
like1(ob,t52,\"TSE_SECID_LST2\")):\n\
  print \"result is pass\"\n\
  return 1\n\
   else:\n\
  print \"result is fail\"\n\
  return 0\n";

// function parameter "ob" in this function definition is the one
which Im passing as CObject.

PyObject *result = NULL;
result =
PyRun_String(pyfunction,Py_file_input,_pPyDictionary,_pPyDictionary);
if(PyErr_Occurred() || result == NULL){
printf("Failed to compile function [%s]\n",func);
PyErr_Print();
return;
}
Py_XDECREF(result);
result = NULL;
PyObject *ptr = PyObject_GetAttrString(_pPyModule,fname);
if(PyErr_Occurred() || *ptr == NULL){
printf("PyObject_GetAttrString failed:%s",fname);
return;
}
if(!PyCallable_Check(*ptr)){
   printf("%s not a callable Python code\n",fname);
   Py_XDECREF(*ptr);
   *ptr = NULL;
   return;
}

// I've created dynamically loadble Python module & multiple functions
similar to above gets added dynamically to this module.
// Module has functions "co1" & "like1" in module's .cpp file. These
functions then use CObject - the struct capsule & map pointer in it.
static PyObject* merorderrouter_co1(PyObject* self, PyObject* args)
{
printf("Contains function\n");
int ret=0;
char *arg1=NULL, *arg2=NULL;
PyObject* voidcap=NULL;
if(!PyArg_ParseTuple(args, "Oss", &voidcap,&arg1,&arg2)){
   printf("failed to get args\n");
   if(PyErr_Occurred())
 PyErr_Print();
   return(PyInt_FromLong(ret));
}
printf("key=%s, grpname=[%s]\n",arg1,arg2);
if(voidcap && PyCObject_Check(voidcap))
   printf("valid Py-C-Object\n");
else
   printf("NOT a valid Py-C-Object\n");
pcapsule pobj = (pcapsule)PyCObject_AsVoidPtr(voidcap);
if(pobj){
   PerExchGroupsElementsTable grpmap = *pobj->refgrps;
   if(grpmap.count(arg2)){
 PerExchGroupsElementsTable::iterator grpmi =
grpmap.find(arg2);
 Elements grpelems = *(Elements*)grpmi->second;
 Elements::iterator ei = grpelems.find(arg1);
 if(ei != grpelems.end()){
printf("has elm.\n");
ret=

Re: portable fork+exec/spawn

2008-05-01 Thread Ben Finney
Brendan Miller <[EMAIL PROTECTED]> writes:

> Is there an actual portable means of asynchronously spawning a
> process and getting a handle to it, being able to write stdin and
> read stdout, or does everyone just write their own wrapper for fork
> and spawn?

You're looking for the 'subprocess' module in the standard library
http://docs.python.org/lib/module-subprocess.html>.

-- 
 \ "If you can't annoy somebody there is little point in writing." |
  `\  -- Kingsley Amis |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread Ben Finney
Yves Dorfsman <[EMAIL PROTECTED]> writes:

> On UNIX, some people use
> #!/usr/bin/env python
> 
> While other use
> #!/usr/bin/python

You haven't indicated your understanding of what the difference in
meaning is, so I'll explain it for those who might not know.

The shebang line (the initial line of the file beginning with "#!")
takes advantage of OS kernels that determine how to execute a file
based on the first few bytes of the file. The shebang line tells the
kernel that this file should be executed by passing it as input to
a process started by another command.

The specified command takes the form of a fully-qualified file path,
and zero or one arguments to the program. That command is then
executed by the kernel, and the Python program file is passed as input
to the resulting process.

The difference between the two is thus what command is executed to
interpret the Python program.

* "#! /usr/bin/env python" will run the command "/usr/bin/env python".
  The 'env(1)' manual page says its purpose is to "run a program in a
  modified environment", but it also has the effect that the command
  is searched on the current PATH variable, and executed based on the
  first occurrence.

* "#! /usr/bin/python" will run the command "/usr/bin/python", which
  is of course the system Python instance as installed by most OS
  packaging systems. That command is run, and the result is the Python
  interpreter.

> Why is one preferred over the other one ?

I've never clearly understood why people want to use "#! /usr/bin/env
python", which is prone to finding a different Python from the one
installed by the operating system. I'd be interested to see what
responses are in favour of it, and what the reasoning is.

One possible reason is that the programmer is attempting to allow for
systems where Python has been installed, but not from an operating
system package.

I much prefer "#! /usr/bin/python" because I want my Python programs
to, by default, be run with the default Python, and depend on Python
being installed by the operating system's package manager. On systems
that use shebang lines and that actually have standardised filesystem
locations, the default Python is found at '/usr/bin/python'.

-- 
 \  "Any sufficiently advanced bug is indistinguishable from a |
  `\  feature." —Rich Kulawiec |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

help with list comprehension

2008-05-01 Thread Yves Dorfsman


In the following script, m1() and m2() work fine. I am assuming m2() is 
faster although I haven't checked that (loops through the list twice instead 
of once).


Now what I am trying to do is something like m3(). As currently written it 
does not work, and I have tried different ways, but I haven't managed to 
make it work.


Is there a possibility ? Or is m2() the optimum ?


Thanks.



#!/usr/bin/python

l = [ { 'colour': 'black',   'num': 0},
  { 'colour': 'brown',   'num': 1},
  { 'colour': 'red', 'num': 2},
  { 'colour': 'orange',  'num': 3},
  { 'colour': 'yellow',  'num': 4},
  { 'colour': 'green',   'num': 5},
  { 'colour': 'blue','num': 6},
  { 'colour': 'violet',  'num': 7},
  { 'colour': 'grey','num': 8},
  { 'colour': 'white',   'num': 9}
]

def m1():
  colours = [ e['colour'] for e in l ]
  nums= [ e['num']for e in l ]

def m2():
  colours = []
  nums= []
  for e in l:
colours.append(e['colour'])
nums.append(e['num'])

#def m3():
#  colours, nums = [ e['colour'], e['num'] for e in l ]





--
Yves.
http://www.SollerS.ca
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread J Sisson
The first method allows python to be installed in an alternate location
(i.e. /usr/local/bin).  "env" in this case is being used to launch python
from whatever location python is installed to.

I like to think of it as an "abstraction" of the python location to make it
"multiplatform-friendly" since not all Unix systems put python in /usr/bin.

On Fri, May 2, 2008 at 1:36 AM, Yves Dorfsman <[EMAIL PROTECTED]> wrote:

> On UNIX, some people use
> #!/usr/bin/env python
>
> While other use
> #!/usr/bin/python
>
> Why is one preferred over the other one ?
>
> Thanks.
>
> --
> Yves.
> http://www.SollerS.ca
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Computers are like air conditioners...
They quit working when you open Windows.
--
http://mail.python.org/mailman/listinfo/python-list

portable fork+exec/spawn

2008-05-01 Thread Brendan Miller
I want to spawn a child process based on an external executable that I have
the path for. I then want to wait on that executable, and capture it's
output.

In the os module, fork is only supported on unix, but spawn is only
supported on windows.

The os.system call is implemented by calling the C system call, which is of
course inefficient and has portability gotchas because it calls the
underlying system shell (sh for unix, cmd for windows, and who knows what
on non unix, non windows platforms like VMS and mac os9). Most importantly,
os.system forces you to wait on the process.

Is there an actual portable means of asynchronously spawning a process and
getting a handle to it, being able to write stdin and read stdout, or does
everyone just write their own wrapper for fork and spawn?

Sorry if this post sounds a little complainy. I was just surprised to find
the os module lacking in portable abstractions over system services.

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


#!/usr/bin/env python vs. #!/usr/bin/python

2008-05-01 Thread Yves Dorfsman

On UNIX, some people use
#!/usr/bin/env python

While other use
#!/usr/bin/python

Why is one preferred over the other one ?

Thanks.

--
Yves.
http://www.SollerS.ca
--
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType'

2008-05-01 Thread Ben Finney
"Jordan Harry" <[EMAIL PROTECTED]> writes:

> I'm trying to write a simple program to calculate permutations. I
> created a file called "mod.py" and put the following in it:
>  
> def factorial(n):
> a = n
> b = n
> while a>0 and b>1:
> n = (n)*(b-1)
> b = b-1

A function that does some calculations internally, but has no 'return'
statement and thus implicitly returns 'None'.

> def perm(n, r):
> a = factorial(n)
> b = factorial(n-r)

These statements bind the 'None' returned by the 'factorial' function
to the names 'a' and 'b'.

> q = a / b

This attempts to use the '/' operator on 'None' with 'None', which
raises the exception you saw.

(good sigmonster, have a cookie)

-- 
 \ "Pinky, are you pondering what I'm pondering?" "I think so, |
  `\Brain, but Zero Mostel times anything will still give you Zero |
_o__)   Mostel."  -- _Pinky and The Brain_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType'

2008-05-01 Thread Sean DiZazzo
On May 1, 5:21 pm, "Jordan Harry" <[EMAIL PROTECTED]> wrote:
> I'm trying to write a simple program to calculate permutations.  I created a 
> file called "mod.py" and put the following in it:
>
> def factorial(n):
>     a = n
>     b = n
>     while a>0 and b>1:
>         n = (n)*(b-1)
>         b = b-1
>
> def perm(n, r):
>     a = factorial(n)
>     b = factorial(n-r)
>     q = a / b
>     print q
>
> Then I went back to IDLE and input the following:
>
> >>> import mod
> >>> mod.perm(5, 4)
>
> I recieved the following error message:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>     mod.perm(5, 4)
>   File "C:\Python25\mod.py", line 27, in perm
>     q = a / b
> TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType'
>
> I have no idea how to fix it.  I'm pretty new to Python.  I have IDLE 1.2.2 
> and Python 2.5.2,
>
> Please help.

Your factorial function needs to return something.

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


Re: RegEx for matching brackets

2008-05-01 Thread George Sakkis
On May 1, 7:44 pm, NevilleDNZ <[EMAIL PROTECTED]> wrote:

> Below is a (flawed) one line RegEx that checks curly brackets (from
> awk/c/python input) are being matched.  Is there a one liner for doing
> this in python?

There is not even a 1000-liner regular expression for this; it's a
context-free language [1], not a regular one [2]. Either do it
manually or use a parser generator [3].

George

[1] http://en.wikipedia.org/wiki/Context-free_language
[2] http://en.wikipedia.org/wiki/Regular_language
[3] http://wiki.python.org/moin/LanguageParsing
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Carl Banks
On May 1, 7:54 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> No, all I want is to give the OP a useful alternative

Fair enough, I can't argue with that.


Carl Banks

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


TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType'

2008-05-01 Thread Jordan Harry
I'm trying to write a simple program to calculate permutations.  I created a 
file called "mod.py" and put the following in it:
 
def factorial(n):
a = n
b = n
while a>0 and b>1:
n = (n)*(b-1)
b = b-1
 
def perm(n, r):
a = factorial(n)
b = factorial(n-r)
q = a / b
print q

Then I went back to IDLE and input the following:
 
>>> import mod
>>> mod.perm(5, 4)
 
I recieved the following error message:
 
Traceback (most recent call last):
  File "", line 1, in 
mod.perm(5, 4)
  File "C:\Python25\mod.py", line 27, in perm
q = a / b
TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType'
 
I have no idea how to fix it.  I'm pretty new to Python.  I have IDLE 1.2.2 and 
Python 2.5.2,
 
Please help.
--
http://mail.python.org/mailman/listinfo/python-list


Problems with psycopg2

2008-05-01 Thread David Anderson
Hi all
I have this function:
def checkName(self, name):
cur = self.conn.cursor()

sql = "SELECT * from patient WHERE fn_pat = '" + name + "'"
cur.execute(sql)
rows = cur.fetchall()

if rows == "[]":
self.insert()

It seems to work fine, But I'm getting this exception:
psycopg2.ProgrammingError: current transaction is aborted, commands ignored
until end of transaction block
at: cur.execute(sql)

What's the problem?
thx

ps: fn_pat is the column of the db, name is the string passed in the
function parameter
--
http://mail.python.org/mailman/listinfo/python-list

Re: RegEx for matching brackets

2008-05-01 Thread John Machin
On May 2, 9:44 am, NevilleDNZ <[EMAIL PROTECTED]> wrote:
> Below is a (flawed) one line RegEx that checks curly brackets (from
> awk/c/python input) are being matched.  Is there a one liner for doing
> this in python?
>
> ThanX
> N
>
> re_open_close="(((\{))[^{}]*((?(0)\})))+"
> re_open_close=re.compile(re_open_close)
> tests="""
>   { this is a test  BAD
>   { this is a test } OK
>   { this is a test } { this is a test } OK
>   { this is a test } { this { this is a test } is a test } OK
>   { this is a test  { this { this is a test } is a test } missing
> close BAD
> """.splitlines()[1:]
> for test in tests:
>   if bool(re_open_close.search(test)) == bool(re.search("OK",test)):
> print "DETECTED:",test
>   else:
> print "MISSED:",test
> [linux]$ python ./re_matching.py
> DETECTED:   { this is a test  BAD
> DETECTED:   { this is a test } OK
> DETECTED:   { this is a test } { this is a test } OK
> DETECTED:   { this is a test } { this { this is a test } is a test }
> OK
> MISSED:   { this is a test  { this { this is a test } is a test }
> missing close BAD

Regexes can't count.

To check for balanced braces, you need to write code e.g.

# untested
def balanced_braces(s):
   n = 0
   for c in s:
  if c == '{':
 n += 1
  elif c == '}':
 n -= 1
 if n < 0:
return False
   return n == 0

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Fri, 02 May 2008 01:21:38 +0200, Torsten Bronger wrote:

> Hallöchen!
> 
> Ivan Illarionov writes:
> 
>> [...]
>>
>> For me it looks more like an old-school/new-school thing than use-case
>> thing. I may be wrong, but I see more and more new projects use things
>> like reST and YAML/JSON and it feels like they are gradually replacing
>> traditional old-school solutions.
>>
>> And I've got very strong impression that YAML is a the future of
>> configuration files when Google released their App Engine.
> 
> In contrast to many other areas of software, configuration files needn't
> be compatible with anything except the user's brain.  So even if the
> rest of the world uses config format X, you can safely stick with config
> format Y.

There are several reasons for compatibility:

1. The user or another developer might want to write GUI front-end to 
configure your app. With standard format this would be easier.

2. Similar apps might want to have a feature like "import settings" from 
other apps. Traditional config files made this PITA -- and that's why 
this feature is extremely rare.

3. Bigger applications that include your sofware as one of its components 
may need to automate configuration process and update several config 
files of different smaller apps from one global setting.

That's precisely why first XML and now YAML became popular for config 
files.

> I mean, YAML is not really a complex thing, yet it was conceived not
> before 2001.  The reason is that traditional config files do a good job.
> 
> Tschö,
> Torsten.

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

Re: where do I begin with web programming in python?

2008-05-01 Thread Paul Rubin
jmDesktop <[EMAIL PROTECTED]> writes:
> I am aware there are various frameworks (Django, Pylons, etc.),
> but I would like to know how to create web pages without these.  If I
> have mod_python or fastcgi on apache, where do I start?  I don't have
> clue where to begin to create a web page from scratch in python.  I am
> sure I will want to access database, etc., all the "normal" stuff, I
> just want to do it myself as opposed to the frameworks, for learning.

I didn't notice anyone mentioning the simplest answer of them all:
write an old fashioned cgi using python's cgi module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 16:32:00 -0700, Carl Banks wrote:

> On May 1, 4:50 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> On Thu, 01 May 2008 11:56:20 -0700, Carl Banks wrote:
>> > On May 1, 1:30 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> >> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:
>> >> > On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]>
>> >> > wrote:
>> >> >> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>>
>> >> >> > IMO .ini-like config files are from the stone age. The modern
>> >> >> > approach is to use YAML (http://www.yaml.org).
>>
>> >> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
>> >> >> and so comprehensively and completely fails to achieve its stated
>> >> >> main goal of being "readable by humans", that I had assumed it
>> >> >> was an April Fool along the lines of Intercal or brainf***.
>>
>> >> > YAML, ISTM, took a simple concept that worked for small,
>> >> > straightforward data, and tried to make into a format that could
>> >> > anything anywhere, with disastrous results.  It's not unlike Perl
>> >> > in this regard.  It's quite ridiculous.
>>
>> >> > My recommendation to the OP would be:
>>
>> >> > If you intend to write a GUI that completely sets all the options,
>> >> > use XML.  You can bet there are some users who would prefer text
>> >> > editing options files, and XML, while not the most readable format
>> >> > available, at least gives users the option.
>>
>> >> > If you don't intend to write a GUI to do that, write a simple text
>> >> > file parser (if the options are simple), use ConfigParser, or use
>> >> > a Python file that you exec.
>>
>> >> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
>> >> > ApplicationData/Appname/config.ext on Windows.  I don't recommend
>> >> > using the Windows registry to store options; use it to modify
>> >> > Windows behavior (like file associations) but keep your own
>> >> > program's options in your own file.
>>
>> >> If you don't like YAML, use JSON or something similar -- XML is
>> >> overkill and .INI is too limited.
>>
>> > I don't think you know the OP's requirements enough to know whether
>> > INI or XML is suitable. You're welcome to suggest alternatives but
>> > what I suggested is fine.
>>
>> > As for XML being overkill for anything, I highly disagree. XML is
>> > suitable for the smallest tasks.  These days I use XML for almost all
>> > my data exchange needs: including conf files.  Elementtree makes it
>> > possible to process XML and pull out some typical data in ten or so
>> > lines of code.  What could possibly be overkill about that?
>>
>> > Carl Banks
>>
>> I used XML for almost everything in the past until I found YAML.
>> Elementtree makes it easy but not easy enough.
> 
> I'm honestly very happy for you that you have found the data transfer
> format that you are happy with, but I'm sorry, that doesn't amount to a
> blanket invalidation of everything you've ever tried and rejected.
> 
> 
>> The most powerful thing
>> about YAML is that it was designed to map directly to native data types
>> in languages like Python (see another my post in this thread for
>> example). And this means that simple YAML files will always be easier
>> to process in Python than XML or INI. And this in turn means that OP
>> with any requirements will have to write less code to read and write
>> his config files.
> 
> I will mention that Python already has, built in, a data transfer format
> that maps directly to Python types: pickle.
> 
> And not only that, it's more readable than YAML.
> 
> 
> I will also add that what you think of as a strength is not always
> thought of as a strength by everyone.  In my early days of Python, I
> would use pickle for all kinds of things.  I've now pretty much switched
> entirely to XML, because I no longer believe that direct correspondance
> to Python types is a good thing; at least it isn't for me.  There is a
> very basic reason for this: whenever I write a pair of tools, one to
> output some XML data, and another further down the chain to read it back
> in, I hardly ever want the data to have the same structure in memory in
> both tools.  For me, YAML or pickle would not gain me anything; I'd be
> doing all that reformatting anyway.

Agree, all depends on programmer's preferences.

> Of course, the OP wasn't talking about data transfer, he was talking
> about a freaking config file.  Reading in a config file is a ridulously
> silly thing to try to hyperoptimize.  Do you really want him to add an
> extra dependency just to reduce code used by five lines?
> 
> 
> Carl Banks

No, all I want is to give the OP a useful alternative and make him aware 
of the latest trend in the config file formats.

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


Re: where do I begin with web programming in python?

2008-05-01 Thread George Sakkis
On May 1, 7:13 pm, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> On May 2, 7:45 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
>
>
>
> > jmDesktop schrieb:
>
> > > I have been to the main python site, but am still confused.  I have
> > > been using .net, so it may be obvious how to do this to everyone
> > > else.  I am aware there are various frameworks (Django, Pylons, etc.),
> > > but I would like to know how to create web pages without these.  If I
> > > havemod_pythonor fastcgi on apache, where do I start?  I don't have
> > > clue where to begin to create a web page from scratch in python.  I am
> > > sure I will want to access database, etc., all the "normal" stuff, I
> > > just want to do it myself as opposed to the frameworks, for learning.
>
> > I highly recommend WSGI instead ofmod_pythonor (fast)cgi. I've heard
> > only bad things aboutmod_pythonover the past years and CGI is totally
> > old school.
>
> > Check out Python Paste, CherryPy and Django. You can also try the Zope,
> > Zope3 and Plone world but Zope is usually for larger and complex
> > applications.
>
> > Most frameworks come with their own little web server for development, too.
>
> I'd also suggest avoiding coding anything directly to mod_python and
> instead base things on WSGI. You can still run it on mod_python with a
> suitable adapter, but you can also run it with mod_wsgi, mod_fastcgi,
> or using pure Python web servers such as the one in Paste as well.
>
> For a low level nuts and bolts (anti framework) approach I'd suggest
> looking at:
>
>  http://dev.pocoo.org/projects/werkzeug/
>
> This gives you all the basic components, but it is really up to you as
> to how you put them together, which seems to be what you want to be
> able to do.

Or if you don't want to use any 3rd party package and have Python 2.5,
you may start from 
http://www.xml.com/pub/a/2006/09/27/introducing-wsgi-pythons-secret-web-weapon.html.
Here's the standard "Hello world!" example:

from wsgiref.simple_server import make_server

def application(environ, start_response):
start_response('200 OK',[('Content-type','text/html')])
return ['Hello World!']

httpd = make_server('', 8000, application)
print "Serving HTTP on port 8000..."
httpd.serve_forever()

and point your browser to http://localhost:8000/

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


RegEx for matching brackets

2008-05-01 Thread NevilleDNZ
Below is a (flawed) one line RegEx that checks curly brackets (from
awk/c/python input) are being matched.  Is there a one liner for doing
this in python?

ThanX
N

re_open_close="(((\{))[^{}]*((?(0)\})))+"
re_open_close=re.compile(re_open_close)
tests="""
  { this is a test  BAD
  { this is a test } OK
  { this is a test } { this is a test } OK
  { this is a test } { this { this is a test } is a test } OK
  { this is a test  { this { this is a test } is a test } missing
close BAD
""".splitlines()[1:]
for test in tests:
  if bool(re_open_close.search(test)) == bool(re.search("OK",test)):
print "DETECTED:",test
  else:
print "MISSED:",test
[linux]$ python ./re_matching.py
DETECTED:   { this is a test  BAD
DETECTED:   { this is a test } OK
DETECTED:   { this is a test } { this is a test } OK
DETECTED:   { this is a test } { this { this is a test } is a test }
OK
MISSED:   { this is a test  { this { this is a test } is a test }
missing close BAD
--
http://mail.python.org/mailman/listinfo/python-list


Up to the minute gizmo and gadget news and reviews!

2008-05-01 Thread gizmohackers
Come check out this new site on the latest news and reviews on gizmos
and gadgets!

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Carl Banks
On May 1, 4:50 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> On Thu, 01 May 2008 11:56:20 -0700, Carl Banks wrote:
> > On May 1, 1:30 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> >> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:
> >> > On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> >> >> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>
> >> >> > IMO .ini-like config files are from the stone age. The modern
> >> >> > approach is to use YAML (http://www.yaml.org).
>
> >> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
> >> >> and so comprehensively and completely fails to achieve its stated
> >> >> main goal of being "readable by humans", that I had assumed it was
> >> >> an April Fool along the lines of Intercal or brainf***.
>
> >> > YAML, ISTM, took a simple concept that worked for small,
> >> > straightforward data, and tried to make into a format that could
> >> > anything anywhere, with disastrous results.  It's not unlike Perl in
> >> > this regard.  It's quite ridiculous.
>
> >> > My recommendation to the OP would be:
>
> >> > If you intend to write a GUI that completely sets all the options,
> >> > use XML.  You can bet there are some users who would prefer text
> >> > editing options files, and XML, while not the most readable format
> >> > available, at least gives users the option.
>
> >> > If you don't intend to write a GUI to do that, write a simple text
> >> > file parser (if the options are simple), use ConfigParser, or use a
> >> > Python file that you exec.
>
> >> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
> >> > ApplicationData/Appname/config.ext on Windows.  I don't recommend
> >> > using the Windows registry to store options; use it to modify Windows
> >> > behavior (like file associations) but keep your own program's options
> >> > in your own file.
>
> >> If you don't like YAML, use JSON or something similar -- XML is
> >> overkill and .INI is too limited.
>
> > I don't think you know the OP's requirements enough to know whether INI
> > or XML is suitable. You're welcome to suggest alternatives but what I
> > suggested is fine.
>
> > As for XML being overkill for anything, I highly disagree. XML is
> > suitable for the smallest tasks.  These days I use XML for almost all my
> > data exchange needs: including conf files.  Elementtree makes it
> > possible to process XML and pull out some typical data in ten or so
> > lines of code.  What could possibly be overkill about that?
>
> > Carl Banks
>
> I used XML for almost everything in the past until I found YAML.
> Elementtree makes it easy but not easy enough.

I'm honestly very happy for you that you have found the data transfer
format that you are happy with, but I'm sorry, that doesn't amount to
a blanket invalidation of everything you've ever tried and rejected.


> The most powerful thing
> about YAML is that it was designed to map directly to native data types
> in languages like Python (see another my post in this thread for
> example). And this means that simple YAML files will always be easier to
> process in Python than XML or INI. And this in turn means that OP with
> any requirements will have to write less code to read and write his
> config files.

I will mention that Python already has, built in, a data transfer
format that maps directly to Python types: pickle.

And not only that, it's more readable than YAML.


I will also add that what you think of as a strength is not always
thought of as a strength by everyone.  In my early days of Python, I
would use pickle for all kinds of things.  I've now pretty much
switched entirely to XML, because I no longer believe that direct
correspondance to Python types is a good thing; at least it isn't for
me.  There is a very basic reason for this: whenever I write a pair of
tools, one to output some XML data, and another further down the chain
to read it back in, I hardly ever want the data to have the same
structure in memory in both tools.  For me, YAML or pickle would not
gain me anything; I'd be doing all that reformatting anyway.


Of course, the OP wasn't talking about data transfer, he was talking
about a freaking config file.  Reading in a config file is a
ridulously silly thing to try to hyperoptimize.  Do you really want
him to add an extra dependency just to reduce code used by five lines?


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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Torsten Bronger
Hallöchen!

Ivan Illarionov writes:

> [...]
>
> For me it looks more like an old-school/new-school thing than
> use-case thing. I may be wrong, but I see more and more new
> projects use things like reST and YAML/JSON and it feels like they
> are gradually replacing traditional old-school solutions.
>
> And I've got very strong impression that YAML is a the future of
> configuration files when Google released their App Engine.

In contrast to many other areas of software, configuration files
needn't be compatible with anything except the user's brain.  So
even if the rest of the world uses config format X, you can safely
stick with config format Y.

I mean, YAML is not really a complex thing, yet it was conceived not
before 2001.  The reason is that traditional config files do a good
job.

Tschö,
Torsten.

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


Re: where do I begin with web programming in python?

2008-05-01 Thread Graham Dumpleton
On May 2, 7:45 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> jmDesktop schrieb:
>
> > I have been to the main python site, but am still confused.  I have
> > been using .net, so it may be obvious how to do this to everyone
> > else.  I am aware there are various frameworks (Django, Pylons, etc.),
> > but I would like to know how to create web pages without these.  If I
> > havemod_pythonor fastcgi on apache, where do I start?  I don't have
> > clue where to begin to create a web page from scratch in python.  I am
> > sure I will want to access database, etc., all the "normal" stuff, I
> > just want to do it myself as opposed to the frameworks, for learning.
>
> I highly recommend WSGI instead ofmod_pythonor (fast)cgi. I've heard
> only bad things aboutmod_pythonover the past years and CGI is totally
> old school.
>
> Check out Python Paste, CherryPy and Django. You can also try the Zope,
> Zope3 and Plone world but Zope is usually for larger and complex
> applications.
>
> Most frameworks come with their own little web server for development, too.

I'd also suggest avoiding coding anything directly to mod_python and
instead base things on WSGI. You can still run it on mod_python with a
suitable adapter, but you can also run it with mod_wsgi, mod_fastcgi,
or using pure Python web servers such as the one in Paste as well.

For a low level nuts and bolts (anti framework) approach I'd suggest
looking at:

  http://dev.pocoo.org/projects/werkzeug/

This gives you all the basic components, but it is really up to you as
to how you put them together, which seems to be what you want to be
able to do.

Graham

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


Pep11

2008-05-01 Thread Terry Reedy
The syllable link at the bottem is not currently working.
The site itself is still alive and distributing 2.5.1
terry



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


Re: dropping win98 support? was Re: Python 2.6 and wrapping C libraries on Windows

2008-05-01 Thread Terry Reedy

"illume" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Ah, why is that?

Were any of the reasons given in
http://www.python.org/dev/peps/pep-0011/
unclear?
It appears you are already aware of MS's non-support of Win98

| Seems like a lot of people using it, so it's still worthwhile making
| 2.6 work with win98.

Since the warning was given in 2.5, no one has agreed enough to volunteer 
to do do.



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


Re: is +=1 thread safe

2008-05-01 Thread Gary Herron

AlFire wrote:

Hi,

I have a piece of software which uses threads in very massive way - 
like hundreds of  them generated every second.


there is also a piece of code which maintains the number of 
outstanding threads, simply


counter+=1 is executed when before starting the thread and counter-=1 
after it finishes.


all is very simple and by the end of the program life I expect the 
counter to zero out.


however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as 
expected.


I guarded those statement with Lock.{acquire,release} and now it 
always returns 0.



But I still can not believe that +=1 is not a thread safe operation.


Any clue?

Of course it's not thread safe.   For the same reason and more basic, 
even the expression i++ is not thread safe in C++.


Any such calculation, on modern processors, requires three operations: 
 retrieve value of i into a register,

 increment the register
 write the value into i.

If a thread is interrupted anywhere within that sequence, and another 
thread access i, you have a conflict.  (And indeed, hardware interrupts 
can occur between any two instructions.)


Gary Herron

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


Re: Custom Classes?

2008-05-01 Thread Victor Subervi
On Wed, Apr 30, 2008 at 12:35 PM, J. Cliff Dyer <[EMAIL PROTECTED]> wrote:

> Post working code, and I'll answer your actual question.


Good grief!  The code is *not* double spaced! Take a look. Click to the end
of the first line and hit the right arrow key, and see for yourself.  As for
not initializing w, well, I did in my code and just forgot to cut and paste
that. Same with the except. Sorry on those. And yes, I pull out try clauses
when I need to look at stacks. Here:

w = 0

try:

  w += 1

  getpic = "getpic" + str(w) + ".py"

  try:

os.remove(getpic)

  except:

pass

  code = """

#!/usr/local/bin/python

import cgitb; cgitb.enable()

import MySQLdb

import cgi

import sys,os

sys.path.append(os.getcwd())

from login import login

user, passwd, db, host = login()

form = cgi.FieldStorage()

picid = int(form["id"].value)

x = int(form["x"].value)

pics =
{1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\

9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}

pic = pics[x]

print 'Content-Type: text/html'

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)

cursor= db.cursor()

sql = "select " + pic + " from products where id='" + str(picid) + "';"

cursor.execute(sql)

content = cursor.fetchall()[0][0].tostring()

cursor.close()

print 'Content-Type: image/jpeg'

print

print content

"""

  script = open(getpic, "w")

  script.write(code)

  print '' % pic

  print '\n' % (getpic, d, y)

except:

  pass


TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 23:03:38 +0200, Torsten Bronger wrote:

> Hallöchen!
> 
> Ivan Illarionov writes:
> 
>> [...]
>>
>> I took the example from
>> http://www.kuro5hin.org/story/2004/10/29/14225/062 I haven't use my own
>> example only because I don't have one at hand right now. YAML, in its
>> simple form, definetely makes me more productive. I wasted too much
>> time with XML in the past and I won't ever use it as a serialization or
>> config/settings format again. .INI/ConfigParser is too limited and has
>> no standards. I just don't see anything better than YAML to do human
>> and Python editable config files and to serialize information for later
>> use.
> 
> Okay, but serialisation is something completely different.  Nobody would
> use INI files for it.
> 
> For other things, it simply depends on the use case.  For example, I
> *know* that the configuration files of my pet project will not exceed
> the dumb section.key=value scheme so anything else would be overkill.
> 
> Besides, YAML adds another dependency.
> 
> Tschö,
> Torsten.

For me it looks more like an old-school/new-school thing than use-case 
thing. I may be wrong, but I see more and more new projects use things 
like reST and YAML/JSON and it feels like they are gradually replacing 
traditional old-school solutions.

And I've got very strong impression that YAML is a the future of 
configuration files when Google released their App Engine.

Of course I may be wrong and it's just my opinion.

-- 
Ivan

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

pil:effbot and pythonware offline

2008-05-01 Thread spdegabrielle
Sorry, I'm new to python and was trying to get imageTK;
this led me to try find PIL, but pythonware and effbot both seem to be
offline.

I can't find any mention of an outage on python.org, this newsgroup,
or the planet-blogs.

Is it just me? and does anyone know where I can find ImageTK?

Cheers,

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


Re: dropping win98 support?

2008-05-01 Thread Christian Heimes
illume schrieb:
> Ah, why is that?
> 
> There's still at least 1.1% of people using win98, if you believe this
> source of stats:
> http://www.w3schools.com/browsers/browsers_os.asp
> 
> I just noticed that win9x winme and win nt are all being dropped from
> python.
> 
> I know they are old and crufty, but there's still heaps of people
> using them.

The Python core developer team has limited resources. We don't want to
waste our energy with supporting ancient operation systems. Microsoft
has dropped the support for the 9x and NT series several years ago.
Dropping the support as well makes future development and new features
much easier for us.

Python can finally depend on the wide api functions and sane unicode
support.

> Someone pointed me to the pep, where the un-support seems planned:
> http://www.python.org/dev/peps/pep-0011/
> 
> 
> Seems like a lot of people using it, so it's still worthwhile making
> 2.6 work with win98.

People can still use Python 2.5. Users of deprecated and unsupported
OSes can't except new versions of software to run on their boxes.

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


Re: Getting started with pyvtk

2008-05-01 Thread Robert Kern

Peter Pearson wrote:

I'm trying to get started with pyvtk, the Python interface
to the Visualization Toolkit, but there's obviously
something important that I haven't figured out after an
embarrassingly long morning of googling around.  When I run
sample pyvtk code (example1.py, from
http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/pyvtk/examples/example1.py),
nothing graphical happens, but some text files appear named
example1.vtk and example1b.vtk.  Guessing that I need to
feed one of these to vtk, I tried "vtk 

pyvtk is not the Python interface to VTK. It is for the creation of VTK files. 
The vtk(1) command is a Tcl shell with the VTK libraries loaded (I believe). 
Read the VTK documentation for information on the Tcl interface if you really 
want to use it. The Python interface is also included in the VTK sources, 
although it might not have been built on your machine. You have to enable it 
when you build VTK itself. The Python interface is essentially the same as the 
C++ interface. There are Python examples in the VTK source tree.


--
Robert Kern

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

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


Re: where do I begin with web programming in python?

2008-05-01 Thread Christian Heimes
jmDesktop schrieb:
> I have been to the main python site, but am still confused.  I have
> been using .net, so it may be obvious how to do this to everyone
> else.  I am aware there are various frameworks (Django, Pylons, etc.),
> but I would like to know how to create web pages without these.  If I
> have mod_python or fastcgi on apache, where do I start?  I don't have
> clue where to begin to create a web page from scratch in python.  I am
> sure I will want to access database, etc., all the "normal" stuff, I
> just want to do it myself as opposed to the frameworks, for learning.

I highly recommend WSGI instead of mod_python or (fast)cgi. I've heard
only bad things about mod_python over the past years and CGI is totally
old school.

Check out Python Paste, CherryPy and Django. You can also try the Zope,
Zope3 and Plone world but Zope is usually for larger and complex
applications.

Most frameworks come with their own little web server for development, too.

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


Is anyone using Python for embedded applications?

2008-05-01 Thread Lori Welte
Hi Dean

 

I need a minimalist version of Python to run on a ColdFire-based
embedded system (written in C with no RTOS). It will be used by
mechanical engineers to test their servo and stepper motors. I need all
the basic features you are providing in PyMite.

 

I've managed to port PyMite and run a test "trivial" on my embedded
platform, but I am a bit confused about whether this is really what I
need.

 

I need an interactive Python interpreter running on my embedded...I will
be feeding it lines through my USB connection. It seems that PyMite is
not exactly what I'm looking for (?). I expected to be able to do
something like pm_run("abs(-1)") for example, but that doesn't work.
After reading carefully your docs, it seems like in fact that PyMite
should be used by writing Python programs on a PC, running your
PyImageCreator, then rebuilding the embedded with the native C code, and
downloading the image file to the embedded? Although this is pretty
nifty, this won't work for my needs.

 

Could you confirm that PyMite does not run like pm_run() =
PyRun_SimpleString() or if it does, what am I missing?

 

Thanks so much for all your excellent software

Lori Welte

"firmwaregirl"

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

dropping win98 support? was Re: Python 2.6 and wrapping C libraries on Windows

2008-05-01 Thread illume
Ah, why is that?

There's still at least 1.1% of people using win98, if you believe this
source of stats:
http://www.w3schools.com/browsers/browsers_os.asp

I just noticed that win9x winme and win nt are all being dropped from
python.

I know they are old and crufty, but there's still heaps of people
using them.

Someone pointed me to the pep, where the un-support seems planned:
http://www.python.org/dev/peps/pep-0011/


Seems like a lot of people using it, so it's still worthwhile making
2.6 work with win98.





On May 1, 10:09 pm, Christian Heimes <[EMAIL PROTECTED]> wrote:
> illume schrieb:
>
> > Hi,
>
> > after a little research it appears that win9x is not supported by the
> > msvcr90.dll run time.
>
> > Can you confirm thisLenard?
>
> > Has anyone tested the new python binaries that link to msvcr90.dll on
> > win9x machines?
>
> It doesn't matter to use because Python 2.6 and 3.0 require at least
> Windows 2000 SP4. The 9x, ME and NT series aren't supported any more.
>
> Christian

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


Re: where do I begin with web programming in python?

2008-05-01 Thread Mike Driscoll
On May 1, 4:25 pm, jmDesktop <[EMAIL PROTECTED]> wrote:
> I have been to the main python site, but am still confused.  I have
> been using .net, so it may be obvious how to do this to everyone
> else.  I am aware there are various frameworks (Django, Pylons, etc.),
> but I would like to know how to create web pages without these.  If I
> have mod_python or fastcgi on apache, where do I start?  I don't have
> clue where to begin to create a web page from scratch in python.  I am
> sure I will want to access database, etc., all the "normal" stuff, I
> just want to do it myself as opposed to the frameworks, for learning.
>
> Thank you for any help.

The web frameworks make it a lot easier. But you can use the httplib
modules. You should check out the wiki: 
http://wiki.python.org/moin/WebProgramming

There's also a couple of books on the topic: "Python Web Programming"
by Steve Holden, and "Web Programming in Python" by Thiruvathukal.

Check out the cgi-type stuff especially.

Hope that helps some.

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


where do I begin with web programming in python?

2008-05-01 Thread jmDesktop
I have been to the main python site, but am still confused.  I have
been using .net, so it may be obvious how to do this to everyone
else.  I am aware there are various frameworks (Django, Pylons, etc.),
but I would like to know how to create web pages without these.  If I
have mod_python or fastcgi on apache, where do I start?  I don't have
clue where to begin to create a web page from scratch in python.  I am
sure I will want to access database, etc., all the "normal" stuff, I
just want to do it myself as opposed to the frameworks, for learning.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Torsten Bronger
Hallöchen!

Ivan Illarionov writes:

> [...]
>
> I took the example from
> http://www.kuro5hin.org/story/2004/10/29/14225/062 I haven't use
> my own example only because I don't have one at hand right
> now. YAML, in its simple form, definetely makes me more
> productive. I wasted too much time with XML in the past and I
> won't ever use it as a serialization or config/settings format
> again. .INI/ConfigParser is too limited and has no standards. I
> just don't see anything better than YAML to do human and Python
> editable config files and to serialize information for later use.

Okay, but serialisation is something completely different.  Nobody
would use INI files for it.

For other things, it simply depends on the use case.  For example, I
*know* that the configuration files of my pet project will not
exceed the dumb section.key=value scheme so anything else would be
overkill.

Besides, YAML adds another dependency.

Tschö,
Torsten.

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


Re: Getting started with pyvtk

2008-05-01 Thread Paul Melis
On 1 mei, 22:54, Peter Pearson <[EMAIL PROTECTED]> wrote:
> I'm trying to get started with pyvtk, the Python interface
> to the Visualization Toolkit,

It looks like you're using this package:
http://cens.ioc.ee/projects/pyvtk/

These are not the official Python bindings to VTK, but seem to be an
add-on that allow you to manipulate VTK _files_ from Python.

The official bindings are included in the VTK distribution and can be
enabled at build-time (assuming you build VTK yourself).

For a simple example that will open a window and show some 3D object,
see for example the example code the vtkConeSource class:
http://public.kitware.com/cgi-bin/viewcvs.cgi/*checkout*/Examples/Tutorial/Step1/Python/Cone.py?root=VTK&content-type=text/plain

> Simply running "vtk" (apparently 4.0)

VTK 4.0 is really really old. Consider switching to 5.0 at least or
use the CVS version if you feel adventurous.

Hope this helps,
Paul
--
http://mail.python.org/mailman/listinfo/python-list


Getting started with pyvtk

2008-05-01 Thread Peter Pearson
I'm trying to get started with pyvtk, the Python interface
to the Visualization Toolkit, but there's obviously
something important that I haven't figured out after an
embarrassingly long morning of googling around.  When I run
sample pyvtk code (example1.py, from
http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/pyvtk/examples/example1.py),
nothing graphical happens, but some text files appear named
example1.vtk and example1b.vtk.  Guessing that I need to
feed one of these to vtk, I tried "vtk spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 11:56:20 -0700, Carl Banks wrote:

> On May 1, 1:30 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:
>> > On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
>> >> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>>
>> >> > IMO .ini-like config files are from the stone age. The modern
>> >> > approach is to use YAML (http://www.yaml.org).
>>
>> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
>> >> and so comprehensively and completely fails to achieve its stated
>> >> main goal of being "readable by humans", that I had assumed it was
>> >> an April Fool along the lines of Intercal or brainf***.
>>
>> > YAML, ISTM, took a simple concept that worked for small,
>> > straightforward data, and tried to make into a format that could
>> > anything anywhere, with disastrous results.  It's not unlike Perl in
>> > this regard.  It's quite ridiculous.
>>
>> > My recommendation to the OP would be:
>>
>> > If you intend to write a GUI that completely sets all the options,
>> > use XML.  You can bet there are some users who would prefer text
>> > editing options files, and XML, while not the most readable format
>> > available, at least gives users the option.
>>
>> > If you don't intend to write a GUI to do that, write a simple text
>> > file parser (if the options are simple), use ConfigParser, or use a
>> > Python file that you exec.
>>
>> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
>> > ApplicationData/Appname/config.ext on Windows.  I don't recommend
>> > using the Windows registry to store options; use it to modify Windows
>> > behavior (like file associations) but keep your own program's options
>> > in your own file.
>>
>> If you don't like YAML, use JSON or something similar -- XML is
>> overkill and .INI is too limited.
> 
> 
> I don't think you know the OP's requirements enough to know whether INI
> or XML is suitable. You're welcome to suggest alternatives but what I
> suggested is fine.
>
> As for XML being overkill for anything, I highly disagree. XML is
> suitable for the smallest tasks.  These days I use XML for almost all my
> data exchange needs: including conf files.  Elementtree makes it
> possible to process XML and pull out some typical data in ten or so
> lines of code.  What could possibly be overkill about that?
> 
> 
> Carl Banks

I used XML for almost everything in the past until I found YAML. 
Elementtree makes it easy but not easy enough. The most powerful thing 
about YAML is that it was designed to map directly to native data types 
in languages like Python (see another my post in this thread for 
example). And this means that simple YAML files will always be easier to 
process in Python than XML or INI. And this in turn means that OP with 
any requirements will have to write less code to read and write his 
config files.

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


Re: send gpg encrypted emails (properly mime formatted)

2008-05-01 Thread Mike Driscoll
On May 1, 12:57 pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> Any ideas on python packages that could help with sending gpg encrypted
> (properly mime formatted) emails?
>
> My idea is to forward all my emails to a remote imap server, but gpg encrypt
> them to myself in the process.

Take a look at this for the gpg part:

http://wiki.python.org/moin/GnuPrivacyGuard

And the standard library has the email module which does mime
formatting.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 14:13:08 -0500, Jon Ribbens wrote:

> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> I used XML files before for this purpose and found YAML much easier and
>> better suitable for the task.
>>
>> Please explain why don't like YANL so much?
> 
> Because even the examples in the spec itself are unreadable gibberish.
> The PyYAML library is over 300kB! These are rather big clues that it's
> unsuitable for the purpose for which it was designed. It's certainly
> unsuitable for use as a configuration file format, where it is overkill
> by several orders of magnitude.
> 
>   !!str &a1 "foo":
>   !!str bar
>   &a2 baz : *a1
>   ! foo :
>   ! baz
> 
> This is supposed to be human readable?

Thanx, now I see your point. I didn't mean all the fancy features of 
YAML, but the most basic sintax.

Compare this:

Bob
Abooey
adv
555-1212
[EMAIL PROTECTED]
[EMAIL PROTECTED]


and this:
babooey:
computer : cpu1
firstname: Bob
lastname: Abooey
cell: 555-1212
addresses:
- address: [EMAIL PROTECTED]
  password: 
- address: [EMAIL PROTECTED]
  password: 

I find the latter *much* more readable.

And the most important thing is that it *maps directly to Python data 
types*, in this case dictionaries and lists:
{babooey: {computer: cpu1, firstname: Bob, lastname: Abooey, cell: 555, 
1212, addresses: [{address: [EMAIL PROTECTED], password: },
{address: [EMAIL PROTECTED], password: }]}

I took the example from 
http://www.kuro5hin.org/story/2004/10/29/14225/062
I haven't use my own example only because I don't have one at hand right 
now. YAML, in its simple form, definetely makes me more productive. I 
wasted too much time with XML in the past and I won't ever use it as a 
serialization or config/settings format again. .INI/ConfigParser is too 
limited and has no standards. I just don't see anything better than YAML 
to do human and Python editable config files and to serialize information 
for later use.

>> PS. Your reply remind me of early days of Python when Perl programmers
>> said exacly the same thing about Python.
> 
> I think I would suffer irony overload if I saw a Perl programmer
> criticising Python for being hard to read ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread tinnews
Carl Banks <[EMAIL PROTECTED]> wrote:
> On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> > On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> >
> > > IMO .ini-like config files are from the stone age. The modern approach is
> > > to use YAML (http://www.yaml.org).
> >
> > You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
> > and so comprehensively and completely fails to achieve its stated
> > main goal of being "readable by humans", that I had assumed it
> > was an April Fool along the lines of Intercal or brainf***.
> 
> 
> YAML, ISTM, took a simple concept that worked for small,
> straightforward data, and tried to make into a format that could
> anything anywhere, with disastrous results.  It's not unlike Perl in
> this regard.  It's quite ridiculous.
> 
> 
> My recommendation to the OP would be:
> 
> If you intend to write a GUI that completely sets all the options, use
> XML.  You can bet there are some users who would prefer text editing
> options files, and XML, while not the most readable format available,
> at least gives users the option.
> 
But XML has human unfriendly syntax, is awkward to type, is difficult
to read, what's good about it?  If there's a GUI between you and the
XML then OK, but that wasn't where we were was it?

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


Re: i want to add a timeout to my code

2008-05-01 Thread maehhheeyy
On Apr 29, 3:29 pm, John Krukoff <[EMAIL PROTECTED]> wrote:
> On Tue, 2008-04-29 at 14:47 -0700, maehhheeyy wrote:
> > On Apr 17, 4:24 pm, Miki <[EMAIL PROTECTED]> wrote:
> > > On Apr 17, 1:10 pm,maehhheeyy<[EMAIL PROTECTED]> wrote:
>
> > > > I want to add a timeout so that when I pull out my gps from my serial
> > > > port, it would wait for a bit then loop and then see if it's there. I
> > > > also want to add a print statement saying that there is no GPS device
> > > > found. However when I run my code and unplug my serial port, my code
> > > > will just hang until I plug it back in.
> > > > This is my code right now:
>
> > > > def GetGPS():
> > > >       data = []
> > > >       #Open com1: 9600,8,N,1
> > > >       fi = serial.Serial(0, timeout = 1)
> > > >       print '[gps module] SERIAL PORT OPEN ON COM1:'
>
> > > > can anyone help me please? Thanks.
>
> > >http://docs.python.org/lib/node545.html
>
> > > HTH,
> > > --
> > > Miki <[EMAIL PROTECTED]>http://pythonwise.blogspot.com
>
> > I tried the code onto my codes but what came out was that in the line
> > signal.signal(signal.SIGSLRM, handler), an attributeError appeared
> > reading that 'module' object has no attribute 'SIGALRM'
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Are you writing your program on windows, or some other platform which is
> not unix?
>
> --
> John Krukoff <[EMAIL PROTECTED]>
> Land Title Guarantee Company- Hide quoted text -
>
> - Show quoted text -

Yeah I'm using Windows 2000.
--
http://mail.python.org/mailman/listinfo/python-list


Python Wins "Favorite Scripting Language" Award

2008-05-01 Thread Steve Holden
The Linux Journal readers apparently suffer the same ambiguity as the 
rest of us when it comes to defining what the difference between a 
scripting language and a programming language.


They do, however, clearly like Python, which they voted their scripting 
language of 2008. PHP, Bash and Perl came in reasonably close on 
Python's heels, but 28.9% of those voting voted for Python.


See all the awards at

  http://www.linuxjournal.com/article/10065

regards
 Steve
--
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: data manipulation

2008-05-01 Thread Jeff
The function expects an excel file.  It cannot read a plain text
file.  You would need to figure out a way to convert the text file
data into an excel format and save it to a new file first.

The proper way to handle this is to make your data processing
functions expect a defined format.  Then, you write importer functions
for various types of files that convert the data in each file to the
defined format.  That way, you can support various file formats and
reuse your processing functions on all of them.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Micah Elliott
On 2008-05-01 Carl Banks wrote:

> If you don't intend to write a GUI to do that, write a simple
> text file parser (if the options are simple), use ConfigParser,
> or use a Python file that you exec.

INI is great for so many things.  It is also extremely
commonplace, regardless of platform.  The biggest challenge might
be choosing which one to adopt:

http://wiki.python.org/moin/ConfigParserShootout

-- 
Micah Elliott | [EMAIL PROTECTED] | http://MicahElliott.blogspot.com


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Jon Ribbens
On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> I used XML files before for this purpose and found YAML much easier and 
> better suitable for the task.
>
> Please explain why don't like YANL so much?

Because even the examples in the spec itself are unreadable gibberish.
The PyYAML library is over 300kB! These are rather big clues that it's
unsuitable for the purpose for which it was designed. It's certainly
unsuitable for use as a configuration file format, where it is
overkill by several orders of magnitude.

  !!str &a1 "foo":
  !!str bar
  &a2 baz : *a1
  ! foo :
  ! baz

This is supposed to be human readable?

> PS. Your reply remind me of early days of Python when Perl programmers 
> said exacly the same thing about Python.

I think I would suffer irony overload if I saw a Perl programmer
criticising Python for being hard to read ;-)
--
http://mail.python.org/mailman/listinfo/python-list


data manipulation

2008-05-01 Thread Krishna
I have a script that reads an excel file and and do manipulations on
it. But, now, I have a text file that needs the same manipulation. I
tried the same script, but it will not work, when I use command such
as: workbook = xlrd.open_workbook('C:/trial.txt'), its giving me
errors saying "expected BOF record". I was wondering how to work
around this. Do I have to do some format conversion to accomplish this
or am I missing something

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Carl Banks
On May 1, 1:30 pm, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:
> > On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> >> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>
> >> > IMO .ini-like config files are from the stone age. The modern
> >> > approach is to use YAML (http://www.yaml.org).
>
> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and
> >> so comprehensively and completely fails to achieve its stated main goal
> >> of being "readable by humans", that I had assumed it was an April Fool
> >> along the lines of Intercal or brainf***.
>
> > YAML, ISTM, took a simple concept that worked for small, straightforward
> > data, and tried to make into a format that could anything anywhere, with
> > disastrous results.  It's not unlike Perl in this regard.  It's quite
> > ridiculous.
>
> > My recommendation to the OP would be:
>
> > If you intend to write a GUI that completely sets all the options, use
> > XML.  You can bet there are some users who would prefer text editing
> > options files, and XML, while not the most readable format available, at
> > least gives users the option.
>
> > If you don't intend to write a GUI to do that, write a simple text file
> > parser (if the options are simple), use ConfigParser, or use a Python
> > file that you exec.
>
> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
> > ApplicationData/Appname/config.ext on Windows.  I don't recommend using
> > the Windows registry to store options; use it to modify Windows behavior
> > (like file associations) but keep your own program's options in your own
> > file.
>
> If you don't like YAML, use JSON or something similar -- XML is overkill
> and .INI is too limited.


I don't think you know the OP's requirements enough to know whether
INI or XML is suitable. You're welcome to suggest alternatives but
what I suggested is fine.

As for XML being overkill for anything, I highly disagree. XML is
suitable for the smallest tasks.  These days I use XML for almost all
my data exchange needs: including conf files.  Elementtree makes it
possible to process XML and pull out some typical data in ten or so
lines of code.  What could possibly be overkill about that?


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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Matimus
On May 1, 4:37 am, Lance Gamet <[EMAIL PROTECTED]> wrote:
> Hi, python beginner starting a new project here.
>
> This project will store most of its actual data in a shared-database, but
> I have a small amount of user specific data that I need to be stored like
> configuration or preferences for example, the list of databases that the
> program should connect to.
>
> On Unix this might be a .file, on windows this could be in the registry,
> or an ini file or an xml file in ProgramData or AppData or something.
>
> Is there a pythony way to store such config data, perhaps there is
> already a standard python package for such a purpose?
>
> My app uses Qt, and Qt has its method of doing it (QSettings), but for
> architectural reasons I don't want to use it.
>
> Could sqlite be an option perhaps? I am still undecided if the ability
> for the user to edit the file independently of the program is a good or
> bad thing.
>
> Thanks a lot.
> Lance

sqlite is a wonderful option, if the user doesn't need to directly
edit it.

Alternatively, you might consider just using python code. Something
like this:

[config_file.py]
class Config:
   optiona = 1
   optionb = 2
[/end file]

Then, in your code you can just:

>>> import imp
>>> m = imp.load_source("config_file", "./config_file.py") # use appropriate 
>>> path (of course)
>>> m.Config.optiona
1
>>> m.Config.optionb
2

Like any other solution, this option has advantages and disadvantages,
but I think it is worth exploring. The class method in the above code
is just an example, choose whatever format is appropriate.

As for generating the contents of the file, tripple quoted strings and
`%r` are your friends.

Matt

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


Re: DO U WANT TO KNOW ABOUT SCIENTOLOGY?

2008-05-01 Thread Danyelle Gragsone
<3 BAHAHAHAA
--
http://mail.python.org/mailman/listinfo/python-list


Re: DO U WANT TO KNOW ABOUT SCIENTOLOGY?

2008-05-01 Thread Mensanator
On May 1, 8:11�am, [EMAIL PROTECTED] wrote:
> � � � � � � � � � � HELLO FRIEND IAM SHALINI,
>
> � � � � � � � � � � � � � � � � � � � � DO U WANT TO KNOW ABOUT
> SCIENTOLOGY?

Do I need to know about wiping my ass with a rock?

Oh, wait...that's Islam, isn't it?

Sorry, I often get those two confused.

Scientology and ass wiping.

>
> � � � � � � � � � � � � � � � � � � � � � � �PLS LOOK AT THE BELOW
> WEBSITE.
>
> � � � � � � � � � � � � � � � � � � � � � � � � �www.bigconcern3.blogspot.com

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

Re: tool to calculate color combination

2008-05-01 Thread Max M

Astan Chee skrev:

Hi,
I was just wondering if there is a tool/script in python that allows me 
to do color calculations; specifically, when I add them.


There is the colorsys module which I have used in this class:




from colorsys import rgb_to_hls, hls_to_rgb
import binascii
from types import StringType, TupleType, ListType, IntType, FloatType
from math import modf

class RGB:
""" Makes it easier to work with rgb colors """

def __init__(self, color):
# set color value
self.color = self.any2color(color)

def any2color(self, color):
"""
Takes a number of color formats and returns a sequence of 3 
floats:

(r,g,b)
Some legal formats for pure blue are: 
'0xFF','#FF','FF',

[0.0, 0.0, 1.0], [0, 0, 255], (0, 0.0, 'FF') and ('0', '0', 'f').
Mixed types are allowed in sequences.
"""
# it must be a hex, so convert to sequence of hex values
if isinstance(color, StringType):
# handle hex value
if color[:2].lower() == '0x': color = color[2:]
elif color[0] == '#': color = color[1:]
color = (color[:2], color[2:4], color[4:])
# convert sequence to floats
color_result = []
a = color_result.append
for part in color:
# what type is the part?
if isinstance(part, StringType): # hex part
if len(part) == 1:
part = '0%s' % part
b = binascii.a2b_hex(part)
a(ord(b[0])/255.0)
elif isinstance(part, IntType): # int part
a(part/255.0)
elif isinstance(part, FloatType): # float part
a(part)
return color_result


def __str__(self):
"Returns string representation of color (same as html_hex)"
return self.html_hex()


def r(self):
return self.color[0]

def g(self):
return self.color[1]

def b(self):
return self.color[2]


def bytes(self):
"""
Takes a sequence of colors in floats, and returns a sequence of 
int in

the range 0-255
"""
return map(lambda x: int(x*255), self.color)


def html_hex(self):
"""
Returns the color in a hex string representation of the form 
'#FF'

"""
r,g,b = self.color
return '#%02X%02X%02X' % (int(r*255),int(g*255),int(b*255))


def _cAdd(self, x, y):
"Private method! Cirkular add x+y so value allways in 0.0-1.0 
range"

fractional, integer  = modf(x + y)
if not fractional and integer: # special case 1.0
return 1.0
return abs(fractional)
# wrong result for negative values!


def hls_delta(self, dh, dl, ds):
"""
Returns a Color object same as self, but adjusted by delta hls
values
"""
h,l,s = rgb_to_hls(*self.color)
nh = self._cAdd(h, dh)
nl = l + dl
if nl > 1.0: nl = 1.0
if nl < 0.0: nl = 0.0
ns = s + ds
if ns > 1.0: ns = 1.0
if ns < 0.0: ns = 0.0
return RGB(hls_to_rgb(nh, nl, ns))


def change_ls(self, new_l=None, new_s=None):
"""
Returns a Color object same as self, but with new lightness and
saturation levels
"""
h,l,s = rgb_to_hls(*self.color)
if new_l == None:
new_l = l
if new_s == None:
new_s = s
return RGB(hls_to_rgb(h, new_l, new_s))


def spacer(self, transparent=None):
"""
Creates a 1x1 GIF89a of color. If no color it returns a 
transparent gif

Should probably not be in this module?
"""
template = [71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 0, 0, 255, 
255,
255, 0, 0, 0, 33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 
1, 0,

0, 2, 2, 68, 1, 0, 59]
if not transparent:
template[13:16] = self.bytes() # set rgb values
template[22] = 0 # remove transparency
return ''.join(map(chr, template))



if __name__=='__main__':

red = (255, 0, 0)
green   = (0.0, 1.0, 0.0)
blue= (0.0, 0.0, 1.0)
yellow  = '#00'

col = RGB(blue)
print col.color
print col.bytes()
print col

brighter = col.change_ls(0.0, 0.0)
print 'brighter:',brighter

#complementary = col.hls_delta(0.50, 0.0, 0.0)
#print complementary


--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

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


Re: Python application distribution

2008-05-01 Thread Martin v. Löwis
> I haven't figured out a way to do this but see no reason why it cannot be
> done.  I have a decent size application written in 100% Python.  I would
> like to distribute this application, but only the .pyc files.  Since the
> .pyc's are just the compiled sources I figured it would work, but if I copy
> just the pyc's and my main app's py into a directory by themselves, I'm
> unable to execute.  Why is this?

This should work fine. What precisely are you doing to execute it, and
how precisely does it fail?

> At this point I'm not really keen on
> handing out the source files to my application, it feels unprofessional.

I don't consider it unprofessional. If the software is packaged that
the end user readily notices the difference - that's unprofessional.
IOW, unless the user browsers your app's directory, he shouldn't even
have to know that the application is written in Python.

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


Re: Problems with Cheese Shop

2008-05-01 Thread Martin v. Löwis
> How can I authorise to the Python Cheese Shop in order to use
> setup.py upload?  Currently, I get
> 
> Upload failed (401): You must be identified to edit package information

You need to add your PyPI password to .pypirc.

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


Re: Problems with Cheese Shop

2008-05-01 Thread Torsten Bronger
Hallöchen!

Christian Heimes writes:

> Torsten Bronger schrieb:
>
>> How can I authorise to the Python Cheese Shop in order to use
>> setup.py upload?  Currently, I get
>> 
>> Upload failed (401): You must be identified to edit package
>> information
>
> Try "python setup.py register sdist upload"

I forgot to say that the package itself is already there, just not
the current release.  Is "register" still the way to go?

Thank you!

Tschö,
Torsten.

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


send gpg encrypted emails (properly mime formatted)

2008-05-01 Thread Neal Becker
Any ideas on python packages that could help with sending gpg encrypted
(properly mime formatted) emails?

My idea is to forward all my emails to a remote imap server, but gpg encrypt
them to myself in the process.

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


Re: Tremendous slowdown due to garbage collection

2008-05-01 Thread Dieter Maurer
John Nagle <[EMAIL PROTECTED]> writes on Mon, 28 Apr 2008 11:41:41 -0700:
> Dieter Maurer wrote:
> > Christian Heimes <[EMAIL PROTECTED]> writes on Sat, 12 Apr 2008 18:47:32 
> > +0200:
> >> [EMAIL PROTECTED] schrieb:
> >>> which made me suggest to use these as defaults, but then
> 
> > We observed similar very bad behaviour -- in a Web application server.
> > Apparently, the standard behaviour is far from optimal when the
> > system contains a large number of objects and occationally, large
> > numbers of objects are created in a short time.
> > We have seen such behaviour during parsing of larger XML documents, for
> > example (in our Web application).
> 
> Our solution to that was to modify BeautifulSoup to use weak pointers.
> All the pointers towards the root and towards previous parts of the
> document are "weak".  As a result, reference counting alone is sufficient
> to manage the tree.  We still keep GC enabled, but it doesn't find much
> to collect.

It will not help in our setup.

We, too, have almost no cycles -- but the GC does not know this:

  If a large number of objects are created temporarily and not released
  before the generation 1 threshoold is reached, then
  the garbage collector will start collections -- even, if there
  are no or very few cycles.
  A generation 2 garbage collection takes time proportional
  to the total number of (GC aware) objects -- independent of
  the number of cycles.

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


Python application distribution

2008-05-01 Thread ron.longo

I haven't figured out a way to do this but see no reason why it cannot be
done.  I have a decent size application written in 100% Python.  I would
like to distribute this application, but only the .pyc files.  Since the
.pyc's are just the compiled sources I figured it would work, but if I copy
just the pyc's and my main app's py into a directory by themselves, I'm
unable to execute.  Why is this?  At this point I'm not really keen on
handing out the source files to my application, it feels unprofessional.

Thanks,
Ron
-- 
View this message in context: 
http://www.nabble.com/Python-application-distribution-tp16993351p16993351.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Problems with Cheese Shop

2008-05-01 Thread Christian Heimes
Torsten Bronger schrieb:
> Hallöchen!
> 
> How can I authorise to the Python Cheese Shop in order to use
> setup.py upload?  Currently, I get
> 
> Upload failed (401): You must be identified to edit package information

Try "python setup.py register sdist upload"

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


Problems with Cheese Shop

2008-05-01 Thread Torsten Bronger
Hallöchen!

How can I authorise to the Python Cheese Shop in order to use
setup.py upload?  Currently, I get

Upload failed (401): You must be identified to edit package information

Thanks!

Tschö,
Torsten.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Patrick Mullen
YAML is a joke if you expect a windows user to be able to hand edit the
data.  Windows users typically expect a .ini file in the application's
directory.  (Usually not the users home directory, even if that may be a
better location).  XML is ok, but .ini is much preferred.

If you have a configuration gui or whatever and the file doesn't need to be
hand edited, it doesn't really matter what format you store it in.  Sqlite
db would be fine in this case.  Still keep the file as a ".yourappname" file
in users home linux directory, and probably do as mentioned above and keep
it in their windows home directory.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote:

> On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
>> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>>
>> > IMO .ini-like config files are from the stone age. The modern
>> > approach is to use YAML (http://www.yaml.org).
>>
>> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and
>> so comprehensively and completely fails to achieve its stated main goal
>> of being "readable by humans", that I had assumed it was an April Fool
>> along the lines of Intercal or brainf***.
> 
> 
> YAML, ISTM, took a simple concept that worked for small, straightforward
> data, and tried to make into a format that could anything anywhere, with
> disastrous results.  It's not unlike Perl in this regard.  It's quite
> ridiculous.
> 
> 
> My recommendation to the OP would be:
> 
> If you intend to write a GUI that completely sets all the options, use
> XML.  You can bet there are some users who would prefer text editing
> options files, and XML, while not the most readable format available, at
> least gives users the option.
> 
> If you don't intend to write a GUI to do that, write a simple text file
> parser (if the options are simple), use ConfigParser, or use a Python
> file that you exec.
> 
> Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
> ApplicationData/Appname/config.ext on Windows.  I don't recommend using
> the Windows registry to store options; use it to modify Windows behavior
> (like file associations) but keep your own program's options in your own
> file.
> 
> 
> Carl Banks

If you don't like YAML, use JSON or something similar -- XML is overkill 
and .INI is too limited.

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


Re: Zope/DTML Infuriating...

2008-05-01 Thread Michael L Torrie
Michael Torrie wrote:
> The second example, x = Integer.fromString('5') demonstrates a huge
> weakness in Java.  

Ahem.  Javascript.  Sorry.

-- 
Michael Torrie
Assistant CSR, System Administrator
Chemistry and Biochemistry Department
Brigham Young University
Provo, UT 84602
+1.801.422.5771

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?

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


Re: Stream I/O to a java applet (os.popen?)

2008-05-01 Thread Michael Torrie
Cody Woolaver wrote:
> This is all done at the terminal though and i need to have it done through a 
> python file. I'm aware that i will have to use os.popen but am unfamiliar 
> with how it works.

You'll probably want to look at the subprocess module, which replaces
the old os.popen stuff.  It's also a bit better at running on Windows.
There are lots of docs and examples relating to subprocess.  Probably
some good recipes too, especially for running on windows.  I'd begin by
looking on google for "python subprocess example windows."

Bear in mind interactive control of a subprocess is sometimes fraught
with difficulty, as it's easy to deadlock if you're waiting for the
subprocess to say something and it's waiting for you to say something.

On another track, you might want to consider using Jython, as it will
allow your python class file to interact directly with the Java stuff,
rather than having to do it via pipes and subprocesses.  The only
downside to Jython currently is it's stuck at Python 2.2 stuff.  But
it's a nice integration of Java and Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Ivan Illarionov
On Thu, 01 May 2008 11:11:29 -0500, Jon Ribbens wrote:

> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>> IMO .ini-like config files are from the stone age. The modern approach
>> is to use YAML (http://www.yaml.org).
> 
> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and so
> comprehensively and completely fails to achieve its stated main goal of
> being "readable by humans", that I had assumed it was an April Fool
> along the lines of Intercal or brainf***.
> 
> I certainly wouldn't recommend it as being suitable for, well, anything
> at all.
> 
> Or were you trolling and I missed the joke? ;-)

No, it isn't. I acually find it usefull and readable. I don't think that 
programmers at Google would use something that is a joke. 

I used XML files before for this purpose and found YAML much easier and 
better suitable for the task.

Please explain why don't like YANL so much?

PS. Your reply remind me of early days of Python when Perl programmers 
said exacly the same thing about Python.

-- 
Ivan


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


Re: simple beginner question about lists and negative index

2008-05-01 Thread Terry Reedy

"jmDesktop" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| This program:
|
| s = 'abcde'
| i = -1
| for i in range (-1, -len(s), -1):
|print s[:i], i
|
| gives
|
| abcd -1
| abc -2
| ab -3
| a -4
|
| Why doesn't the first one have the e if -1 is the end of the list?  In
| Dive Into Python it said that -1 was the end of the list.  Thanks.

A sequence with n items has n+1 slice positions, numbered 0 to n: the 2 at 
beginning and end and n-1 between items.  Example
-a-b-c-
0 1 2 3
has 4 slice positions.
Hence the first item is seq[0:1] and last is seq[n-1:n]

In a sense, we 'ought' to index sequences with average of two successive 
slice positions, giving seq[1/2],,,seq[n-1/2].
But this is inconvenient, so we either round down (C, Python, etc) or up 
(Fortran), giving seq[0]seq[n-1] or seq[1],,,seq[n].
Python allows n-1 and n-k to be abbreviated as -1 and -k.

-1 as an abbreviation of n-1 is only the end of the list for indexing.
n is the end for slicing.  It is abbreviated by omission.  Perhaps

for i in range(n+1): print i, 'abcde'[:5-i]

will make this all even clearer.

Terry Jan Reedy




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


Re: pop langs website ranking

2008-05-01 Thread Jon Harrop
[EMAIL PROTECTED] wrote:
> Alexa's data is more reliable than quantcast.

Alexa claim to have accurate data on lots of sites but I just tried to
correlate their data with the exact data on our web server and the
discrepancies are huge. For example, combining our number of absolute
visitors with their measure of "reach" for our site indicates that there
are 58 billion internet users.

So their data are not even order-of-magnitude accurate. The only web analyst
I ever met was an astrophysicist so this does not really surprise me. ;-)

-- 
Dr Jon D Harrop, Flying Frog Consultancy
http://www.ffconsultancy.com/products/?u
--
http://mail.python.org/mailman/listinfo/python-list


Re: Photo gallery software

2008-05-01 Thread Jumping Arne
On Thu, 1 May 2008 16:59:33 +0200, Scott Sandeman-Allen wrote
(in article <[EMAIL PROTECTED]>):

> I've been working with Photologue for a while with some nice results.
> 

Looks like it's time to start reading that Django book.

Thanks, JA

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


Re: Zope/DTML Infuriating...

2008-05-01 Thread Michael Torrie
Michael Torrie wrote:
> The second example, x = Integer.fromString('5') demonstrates a huge
> weakness in Java.  

Ahem.  Javascript.  Sorry.
--
http://mail.python.org/mailman/listinfo/python-list


my module and unittest contend over commandline options...

2008-05-01 Thread chrisber
using the unittest module in Python 2.3.5, I've written some test code
that ends up with

if __name__ == "__main__":
unittest.main()

Since I want to run this code in various environments, I'd initially
added some commandline options, e.g. to specify a configuration file
like so

 test.py -c devtest.conf
or
 test.py -c localtest.conf

etc.
However, unittest also looks for options on the commandline, and it
was complaining about unrecognized options and quitting.

I've poked around to see if I could delete the options my earlier code
consumed from the commandline buffer, before invoking unittest, but
that seems klugy. Instead, I hardwired  in a testing config file name,
that always has to be local. That works pretty well, but it leaves me
wonderfing whether there would have been another clean way to allow
both my test code and unittest to have options without interfering
with one another.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Carl Banks
On May 1, 12:11 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>
> > IMO .ini-like config files are from the stone age. The modern approach is
> > to use YAML (http://www.yaml.org).
>
> You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
> and so comprehensively and completely fails to achieve its stated
> main goal of being "readable by humans", that I had assumed it
> was an April Fool along the lines of Intercal or brainf***.


YAML, ISTM, took a simple concept that worked for small,
straightforward data, and tried to make into a format that could
anything anywhere, with disastrous results.  It's not unlike Perl in
this regard.  It's quite ridiculous.


My recommendation to the OP would be:

If you intend to write a GUI that completely sets all the options, use
XML.  You can bet there are some users who would prefer text editing
options files, and XML, while not the most readable format available,
at least gives users the option.

If you don't intend to write a GUI to do that, write a simple text
file parser (if the options are simple), use ConfigParser, or use a
Python file that you exec.

Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/
ApplicationData/Appname/config.ext on Windows.  I don't recommend
using the Windows registry to store options; use it to modify Windows
behavior (like file associations) but keep your own program's options
in your own file.


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


Re: Zope/DTML Infuriating...

2008-05-01 Thread Michael Torrie
Jens wrote:
> - Why is it, when primitive data types seem to be objects (similar to
> javascript), that type casting is done through build-in functions
> rather than methods, e.g. String.toInt('5') or '5'.toInt() or x =
> Integer.fromString('5').

Mainly because it's much cleaner to do it the python way (absolutely
explicit), and just as clear or clearer what you are intending to do.
Digging a little deeper, you'll find that the built-in function "str,"
for example, actually calls object.__str__().  This is nice because it
allows any object class to define that method and have it work with
str() in a manner consistent across python.  It preserves some amount of
uniformity.

The second example, x = Integer.fromString('5') demonstrates a huge
weakness in Java.  In python, rather than asking an integer object to
convert from a limited selection of other objects, python works the
other way, asking objects to convert themselves to integers (if they
can).  We don't worry about the size of integers, since python's
integers are auto-sizing.  So any object that implements the __int__()
method can be used with the classic "int()" built-in function.  The same
goes for __float__ and float().

Little things like this really make me happy about how python does
things generally.  I think much of how Java works with Integer and
String (as you describe above) is because Java has primitive types
(which aren't objects at all) and then boxed objects around the
primitive types.  Python eliminates this idea, and makes everything,
even "simple" types objects.

Now sure python could just say always call the "int()" or "float()" or
"str()" method on objects to produce those respective conversions.  But
using a combination of a built-in language function and a specialized,
reserved class method name, allows a lot of flexibility without
infringing on the programmer's need to use method names like "int,
float, or str" if he or she so desired.

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


Re: Is vs Equality Operator

2008-05-01 Thread Terry Reedy

"Good Z" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hello,
| I am having problem in using is. Here is what i am doing.
|
| x=''
| if x is None or x is '':
|return 1

x is not the singleton value None, nor is it the newly created null string 
object.  It is up to the implementation whether each instance of '' reuses 
one cached (or interned) null string object or creates another.  Don't 
depend on such behavior unless you really mean it.  Same goes for comparing 
ints.

|
| The above statement does not return value 1.
|
| If i changed the above check to
| if x == None or x == '':
|return 1
| Now it works fine.

x still is not None but does equal in value ''

I recommend here

if x is None or x == '': ...

tjr



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


Re: PyGame, window is not closing, tut not helping

2008-05-01 Thread Mike Driscoll
On May 1, 10:55 am, globalrev <[EMAIL PROTECTED]> wrote:
> im doing this 
> :http://www.learningpython.com/2006/03/12/creating-a-game-in-python-us...
>
> and when closing the program the window stays up and doesnt respond. i
> tried adding this:http://www.pygame.org/wiki/FrequentlyAskedQuestions
>
> bu it doesnt work, or maybe im doing it wrong.
>
> heres the code without the added tutorial exit:
>
> import os, sys
> import pygame
> from pygame.locals import *
>
> if not pygame.font: print 'Warning, fonts disabled'
> if not pygame.mixer: print 'Warning, sound disabled'
>
> class PyManMain:
>     """The Main PyMan Class - This class handles the main
>     initialization and creating of the Game."""
>
>     def __init__(self, width=640,height=480):
>         """Initialize"""
>         """Initialize PyGame"""
>         pygame.init()
>         """Set the window Size"""
>         self.width = width
>         self.height = height
>         """Create the Screen"""
>         self.screen = pygame.display.set_mode((self.width
>                                                , self.height))
>
>     def MainLoop(self):
>         """This is the Main Loop of the Game"""
>         while 1:
>             for event in pygame.event.get():
>                 if event.type == pygame.QUIT:
>                     sys.exit()
>
> class Snake(pygame.sprite.Sprite):
>     """This is our snake that will move around the screen"""
>
>     def __init__(self):
>         pygame.sprite.Sprite.__init__(self)
>         self.image, self.rect = load_image('snake.png',-1)
>         self.pellets = 0
>
> if __name__ == "__main__":
>     MainWindow = PyManMain()
>     MainWindow.MainLoop()

I think the issue is that you're running it from within IDLE. It looks
like pyGame's event loop and Tkinter's event loop interfere with each
other. If you run the scripts from the command line, it works.

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


Re: Best way to store config or preferences in a multi-platform way.

2008-05-01 Thread Jon Ribbens
On 2008-05-01, Ivan Illarionov <[EMAIL PROTECTED]> wrote:
> IMO .ini-like config files are from the stone age. The modern approach is 
> to use YAML (http://www.yaml.org). 

You mean YAML isn't a joke!? It's so ludicrously overcomplicated,
and so comprehensively and completely fails to achieve its stated
main goal of being "readable by humans", that I had assumed it
was an April Fool along the lines of Intercal or brainf***.

I certainly wouldn't recommend it as being suitable for, well,
anything at all.

Or were you trolling and I missed the joke? ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGame, window is not closing, tut not helping

2008-05-01 Thread globalrev
another program that has the same problem:
import sys, pygame
pygame.init()

size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("snake.png")
ballrect = ball.get_rect()

while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()

ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]

screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
--
http://mail.python.org/mailman/listinfo/python-list


PyGame, window is not closing, tut not helping

2008-05-01 Thread globalrev
im doing this :
http://www.learningpython.com/2006/03/12/creating-a-game-in-python-using-pygame-part-one/

and when closing the program the window stays up and doesnt respond. i
tried adding this:
http://www.pygame.org/wiki/FrequentlyAskedQuestions

bu it doesnt work, or maybe im doing it wrong.

heres the code without the added tutorial exit:


import os, sys
import pygame
from pygame.locals import *

if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'

class PyManMain:
"""The Main PyMan Class - This class handles the main
initialization and creating of the Game."""

def __init__(self, width=640,height=480):
"""Initialize"""
"""Initialize PyGame"""
pygame.init()
"""Set the window Size"""
self.width = width
self.height = height
"""Create the Screen"""
self.screen = pygame.display.set_mode((self.width
   , self.height))


def MainLoop(self):
"""This is the Main Loop of the Game"""
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()


class Snake(pygame.sprite.Sprite):
"""This is our snake that will move around the screen"""

def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('snake.png',-1)
self.pellets = 0

if __name__ == "__main__":
MainWindow = PyManMain()
MainWindow.MainLoop()

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


Symposium “Image Processing and Analysis” within the ICCES'09 Thailand - Announce & Call for Papers

2008-05-01 Thread [EMAIL PROTECTED]
(Our apologies for cross-posting.
We appreciate if you kindly distribute this information by your co-
workers and colleagues.)

**

Symposium “Image Processing and Analysis”
International Conference on Computational & Experimental Engineering
and Sciences 2009 (ICCES'09)
Phuket, Thailand, 8-13 April 2009
http://icces.org/cgi-bin/ices09/pages/index

**

Dear Colleague,

Within the International Conference on Computational & Experimental
Engineering and Sciences 2009 (ICCES'09), to be held in Phuket,
Thailand, in 8-13 April 2009, we are organizing the Symposium “Image
Processing and Analysis”.
Examples of some topics that will be considered in that symposium are:
Image restoring, Description, Compression, Segmentation and
Description; Objects tracking, Matching, Reconstruction and
Registration; Visualization Enhance; Simulation and Animation;
Software Development for Image Processing and Analysis; Grid Computing
in Image Processing and Analysis; Applications of Image Processing and
Analysis.

Due to your research activities in those fields, we would like to
invite you to submit your work and participate in the Symposium “Image
Processing and Analysis”.

For instructions and submission, please access to the conference
website at: http://icces.org/cgi-bin/ices09/pages/index.
Please note, when submitting your work you should choose the Symposium
“Image Processing and Analysis”.

Important dates and Instructions:

- 15 Oct 2008: Start abstract submission;
- 1 Jan 2009: Deadline for abstract submission;
- 10 Jan 2009: End of abstract selection.
If you intend to submit your work please notify as soon as possible
the main organizer of your intention ([EMAIL PROTECTED]);
Instructions for authors are available at: 
http://icces.org/cgi-bin/ices09/pages/guide.


With kind regards,
Yours sincerely,

The Organizers,

João Manuel R. S. Tavares ([EMAIL PROTECTED]) (main organizer)
Faculty of Engineering of University of Porto, Porto, Portugal
Yongjie (Jessica) Zhan ([EMAIL PROTECTED])
Department of Mechanical Engineering, Carnegie Mellon University,
Pittsburgh, USA
Maria João M. Vasconcelos ([EMAIL PROTECTED])
Faculty of Engineering of University of Porto, Porto, Portugal
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread idev
On May 1, 11:41 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Martin, could you please tell me how to do this, I am pretty new in
> > Solaris.
>
> It's fairly complicated, so I'm not sure I can give you the full
> tutorial in a Usenet message.
>
> In essence, you need to spot the linker line in the build process,
> (e.g. by the -o option to the compiler), and add -lm to it.
>
> If you cannot do this on your own, I recommend you hire somebody
> who can.
>
> Regards,
> Martin

Thanks Martin,
For sure I am not maintainer :).

Thanks for the help and explanations.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help me with linking libraries on Solaris 10 sparc

2008-05-01 Thread Martin v. Löwis
> Martin, could you please tell me how to do this, I am pretty new in
> Solaris.

It's fairly complicated, so I'm not sure I can give you the full
tutorial in a Usenet message.

In essence, you need to spot the linker line in the build process,
(e.g. by the -o option to the compiler), and add -lm to it.

If you cannot do this on your own, I recommend you hire somebody
who can.

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


Re: is +=1 thread safe

2008-05-01 Thread John Nagle

AlFire wrote:

Hi,
all is very simple and by the end of the program life I expect the 
counter to zero out.


however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as expected.

I guarded those statement with Lock.{acquire,release} and now it always 
returns 0.



But I still can not believe that +=1 is not a thread safe operation.


Any clue?


   "counter += 1" is not an atomic operation, apparently.  Sorry.

   However, appending and removing from a list or dict are atomic operations,
because if they were not, memory allocation would break.

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


Re: is +=1 thread safe

2008-05-01 Thread Diez B. Roggisch

AlFire schrieb:

Hi,

I have a piece of software which uses threads in very massive way - like 
hundreds of  them generated every second.


there is also a piece of code which maintains the number of outstanding 
threads, simply


counter+=1 is executed when before starting the thread and counter-=1 
after it finishes.


all is very simple and by the end of the program life I expect the 
counter to zero out.


however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as expected.

I guarded those statement with Lock.{acquire,release} and now it always 
returns 0.



But I still can not believe that +=1 is not a thread safe operation.


don't confuse augmented assignment with incrementation as it is offered 
by C (if your data-type actually fits into a single addressable memory 
spot, that is)


python's += works like this


a += b  <=> a = a.__iadd__(b)

Thus you actually get a situation where the expression on the right is 
evaluated but not yet assigned - and then another thread can take over 
control, computing  with the old value of a.


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


Re: is +=1 thread safe

2008-05-01 Thread Duncan Booth
AlFire <[EMAIL PROTECTED]> wrote:

> But I still can not believe that +=1 is not a thread safe operation.
> 
> 
> Any clue?

The statement:

x+=1

is equivalent to:

  x = x.__iadd__(1)

i.e. a function call followed by an assignment.

If the object is mutable then this *may* be safe so long as you never do 
any other assignment to x (the __iadd__ method will return the object being 
mutated so the assignment would in this restricted case be a noop).

Integers are immutable, so the assignment must always rebind x to a new 
object. There is no way given Python's semantics that this could be thread 
safe.

Generating hundreds of threads is, BTW, a very good way to get poor 
performance on any system. Don't do that. Create a few threads and put the 
actions for those threads into a Queue. If you want the threads to execute 
in parallel investigate using sub-processes.

The threading module already has a function to return the number of Thread 
objects currently alive.
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing with characters

2008-05-01 Thread George Sakkis
On May 1, 3:36 am, Duncan Booth <[EMAIL PROTECTED]> wrote:

> George Sakkis <[EMAIL PROTECTED]> wrote:
> > On Apr 30, 5:06 am, Torsten Bronger <[EMAIL PROTECTED]>
> > wrote:
> >> Hallöchen!
>
> >> SL writes:
> >> > "Gabriel Genellina" <[EMAIL PROTECTED]> schreef in bericht
> >> >news:[EMAIL PROTECTED]
>
> >> >> En Wed, 30 Apr 2008 04:19:22 -0300, SL <[EMAIL PROTECTED]> escribió:
> And
> >> >> that's a very reasonable place to search; I think chr and ord are
> >> >> builtin functions (and not str methods) just by an historical
> >> >> accident. (Or is there any other reason? what's wrong with
> >> >> "a".ord() or str.from_ordinal(65))?
>
> >> > yes when you know other OO languages you expect this. Anyone know
> >> > why builtins were chosen? Just curious
>
> >> *Maybe* for aesthetical reasons.  I find ord(c) more pleasent for
> >> the eye.  YMMV.
>
> >> The biggest ugliness though is ",".join().  No idea why this should
> >> be better than join(list, separator=" ").
>
> > Seconded. While we're at it, a third optional 'encode=str' argument
> > should be added, to the effect of:
>
> > def join(iterable, sep=' ', encode=str):
> > return sep.join(encode(x) for x in iterable)
>
> > I can't count the times I've been bitten by TypeErrors raised on
> > ','.join(s) if s contains non-string objects; having to do
> > ','.join(map(str,s)) or ','.join(str(x) for x in s) gets old fast.
> > "Explicit is better than implicit" unless there is an obvious default.
>
> I'm afraid I don't agree with you on this. Most places where I use join
> I already know the type of the values being joined. In those few cases
> where I want to join non strings, or want to do some other processing on
> the values the generator comprehension is easy and has the advantage
> that I can use a more complex expression than a simple function call
> without having to wrap it in a lambda or otherwise contort things:
>
> e.g. comma.join(x[1] for x in s)
> vs.  comma.join(s, encode=operator.itemgetter(1))
> or   comma.join(s, encode=lambda x: x[1])

You don't have to use encode; you can write it as
join((x[1] for x in s), comma)

The main benefit of encode is its obvious default (=str), otherwise
it's not strictly necessary (although it is handy for named functions
e.g. encode=repr).

> Plus of course, you aren't going to be writing ','.join(str(x) for x in
> s) more than once in any given program before you extract it out to a
> function, are you?

In fact I am, not every one-liner needs to be a function. Just the
fact that such a function would live in a general utils module that I
have to import in most of my other modules (effectively making it a
two-liner) is not worth the few extra keystrokes.

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


  1   2   >