Re: persistent fifo queue class

2007-03-08 Thread Diez B. Roggisch
David Bear schrieb:
> Diez B. Roggisch wrote:
> 
>> David Bear schrieb:
>>> I'm looking to see if there are any examples or prewritting fifo queue
>>> classes. I know this is a broad topic. I'm looking to implement a simple
>>> application where a web server enqueue and pickle using a local socket on
>>> to a 'queue server' -- and then I will have another application dequeue
>>> the pickles again using a local socket.
>> Why don't you use a DB for that? If you want pickles, use a  blob
>> column. But all the rest - a defined protocol, stable server,
>> transactions - you get for free.
>>
>> Diez
> 
> Thanks for the suggestion. I did think of this. Indeed the final destination
> of the data is in a db. However, the postsgresql server is on a separate
> box. It will be connected via a private lan. I was worried that possible
> network disruptions would cause either the web application to hang -- or
> data to just get lost. I was thinking along the lines is a message queue
> architecture, where the web app would push data directly onto a queue --
> and then a worker app would dequeue the data and handle it by sending it to
> the db server or otherwise.

Well, if your DB connection is flaky, data will be corrupted - or lost. 
In any case. What good does it do for you to have the messages then? And 
what if the Harddisk the file sits on is corrupt? And don't forget the 
added complexity of a home-brewn solution with all its possible errors - 
much more likely to cause data loss.


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


Re: catching exceptions from an except: block

2007-03-08 Thread Bruno Desthuilliers
MonkeeSage a écrit :
> On Mar 7, 4:58 pm, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
>>except_retry: # the missing(???) keyword you're after
> 
> What is 'except_retry'?

A totally imaginary statement that would do what the OP is looking for.

> To the OP, with the loop and the callables you could also break out of
> the loop when the condition is met and use the else condition to raise
> the exception.
> 
> def test(arg):
> for f in int, float, str, hex:
> try:
> return f(arg)
> break # breaks on f==str

You don't need to break here since you're returning.

> except:
> pass
> else:
> raise ValueError # remove str above to see this
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-08 Thread Bruno Desthuilliers
C Barr Leigh a écrit :
> Help! Have I found a serious bug?

No. This is a FAQ. Default arguments of functions are evaled only once - 
when the def statement is eval'd and the function object constructed.

> This seems like highly undesired behaviour to me.

Possibly, but this is unlikely to change in a near future, so you'd 
better get used to it. If you want mutable objects as default values for 
functions, the idiom is:

def some_func(default=None):
   if default is None:
 default = []
   # code here

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-08 Thread Ayaz Ahmed Khan
"Gabriel Genellina" typed:
> 
> See  
> http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

Thanks for the link, Gabriel. I didn't know about this.

-- 
Ayaz Ahmed Khan

Falling in love makes smoking pot all day look like the ultimate in
restraint.
-- Dave Sim, author of "Cerebus".
-- 
http://mail.python.org/mailman/listinfo/python-list


Howto find dict members from a list of keys

2007-03-08 Thread Alexander Eisenhuth
Hello,

what algo do you use, when you want to find the dict values from d, with 
members 
of l. Following example:

 >>> d = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:10}
 >>> l = [7,8]
 >>> found_dic_members = 
 >>> print found_dict_members
[8,9]

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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-08 Thread Steven D'Aprano
On Wed, 07 Mar 2007 23:34:20 -0800, Nick Vatamaniuc wrote:



>> >>From the standard library docs:
>>
>> > "Keys and values are listed in an arbitrary order which is non-random,
>> > varies across Python implementations, and depends on the dictionary's
>> > history of insertions and deletions."
>>
>> > i.e. the behaviour you have discovered is an implementation detail,
>> > and could change in future versions.
> 
> I would consider that a bad choice. In the dictionary the keys are a
> set i.e. you might as well get a set() when you do d.keys() but the
> set() came later so you just get a list. 

The internal implementation of dictionaries are irrelevant.

Whether the keys "inside" a dictionary are "a set of keys" or "a list of
keys" or "a bunch of keys" is just semantics. 


> The problem with a list is
> that somehow people want to make sense of it's order, just like in
> this case. 

And the problem with a dictionary is that some people want to make sense
of its order, just like in this case, and the fifty thousand previous
times people have asked this newsgroup how they can sort a dictionary.



> So if instead of asking, he could have just written the
> application based on the fact that the keys will always be sorted in
> some way. But then one day his application maybe run a different
> platform and all of the sudden the keys are not sorted as before and
> then disaster strikes.

That would be his problem for being a bad coder, not our problem or the
language's fault.

There is no limit to the "could haves" that lead to disaster. Somebody
"could have" assumed that list.sort() returns the sorted list. Somebody
"could have" assumed that "is" is merely a synonym for "==".

And you know something? We get people making those mistakes all the time.
When people make those mistakes, it is *their responsibility*, for being
stupid or not reading the docs or not doing sufficient testing, or simply
for being inexperienced.


> I hope that dictionary.keys() would return a set to emphasize that
> keys are unordered.

What makes you think that people will magically intuit that sets are
unordered when they insist on thinking that dicts are ordered?

The below-average coder does this:

>>> D = {1: None, 2: None, 3:None}
>>> D
{1: None, 2: None, 3: None}

and concludes that dictionaries are ordered. If they are better-than
average, they might try this:

>>> D = {1: None, 4: None, 3:None} # keys out of order
>>> D
{1: None, 3: None, 4: None}

Still ordered, right? It's actually quite hard to get a dict with purely
integer keys out of order. So they ASS_U_ME that dicts are ordered.

What makes you think they won't do the same with sets?

>>> set((1, 2, 3))
set([1, 2, 3])
>>> set((1, 4, 3))
set([1, 3, 4])
>>> D = {4: None, 2: None, 1: None, 3: None}
>>> set(D.keys())
set([1, 2, 3, 4])

Sure looks ordered to me.

The solution is:

(1) Don't assume unordered data structures like sets and dicts are
ordered, even if they look like it. They aren't.

(2) If you want the keys of a dict sorted, get the keys, and sort them
when and as you need them.

(3) If you think you want a sorted dictionary, chances are you actually
want a different algorithm.

(4) But if you really do need a sorted dictionary, there are recipes on
the web. Google is your friend. But remember, they will be slower than
regular dictionaries.


-- 
Steven D'Aprano 

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


Re: merits of Lisp vs Python

2007-03-08 Thread John Nagle
Brian Adkins wrote:
> Ken Tilton wrote:
> 
>> John Nagle wrote:

> Turns out John is having quite a tough time with Python web hosting (the 
> thread has split off to a c.l.p only fork), so I'm going to cut him some 
> slack. Maybe with some lovin' we can woo him over to c.l.l ;)

 Been there, done that.  I've actually used an original refrigerator
sized Symbolics LISP machine.

 I tend to think of Python as a LISP with infix syntax.
We have a better handle on what to put in a dynamic language now, and
Python does a good job in that direction.  I'm happy with the
language; it's the integration with external components that isn't
working.

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


Re: Howto find dict members from a list of keys

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 05:20:20 -0300, Alexander Eisenhuth  
<[EMAIL PROTECTED]> escribió:

> what algo do you use, when you want to find the dict values from d, with  
> members
> of l. Following example:
>
>  >>> d = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:10}
>  >>> l = [7,8]
>  >>> found_dic_members = 
>  >>> print found_dict_members
> [8,9]

found_dic_members = [d[key] for key in l]


-- 
Gabriel Genellina

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


Re: Problem with Packages

2007-03-08 Thread Srikanth
> It appears that you forgot the basic rule: a package is a directory with
> an __init__.py file (even if empty).

Exactly right. I didn't know that __init__.py is a mandatory one.
Thanks for pointing out.

> > my_apps
> > |
> > |--> mod3.py
> > |--> dir1/dir1_1/mod1.py
> > |--> dir2/dir2_2/mod2.py
>
> You need 4 of such files here.

Thanks again for saying 4, cause I would have definetly put only 2
(inside dir1_1 and dir2_2)

> > And the directory my_apps is included in PYTHONPATH environment
> > variable, what am I doing wrong? I executed this code under PyDev and
> > it's working perfectly but when I run it outside of PyDev, it fails.
>
> Maybe PyDev plays some tricks with PYTHONPATH or something...
>

I got the same doubt and I checked PyDev before posting, the
PYTHONPATH is exactly the same but I didn't notice or rather
overlooked __init__.py file it created automatically when I created
packages using the dialogs.

> Gabriel Genellina

Thanks you Gabriel!
-- Srikanth

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


Re: Howto find dict members from a list of keys

2007-03-08 Thread Steven D'Aprano
On Thu, 08 Mar 2007 09:20:20 +0100, Alexander Eisenhuth wrote:

> Hello,
> 
> what algo do you use, when you want to find the dict values from d, with 
> members 
> of l. Following example:
> 
>  >>> d = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:10}
>  >>> l = [7,8]
>  >>> found_dic_members = 
>  >>> print found_dict_members
> [8,9]

It depends. 

If all of the values in d are usable as keys (that is, all the values
are hashable, so no lists or sets etc.) then you can build a
reverse-lookup dictionary and use that for fast look-ups.

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> rd = dict(zip(d.values(), d.keys()))
>>> rd
{'a': 1, 'c': 3, 'b': 2}

But if you can't do that, you're stuck with a slow search through the
entire dict:

def reverse_search(d, target):
"""Return the first key of dict d that matches the target value."""
for key, value in d.iteritems():
if value == target:
return key
raise KeyError('no key found matching that value')


In both cases though, you have to think about what you want to happen for
duplicated values.



-- 
Steven D'Aprano 

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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-08 Thread Duncan Booth
Carsten Haese <[EMAIL PROTECTED]> wrote:

> Here is a simple counterexample that breaks the ordering, at least for
> the version I'm running:
> 
 d = {}
 for i in range(0,6): d[10**i] = []
> ... 
 d
> {10: [], 1: [], 100: [], 1000: [], 10: [], 1: []}

Here's another counterexample which shows that even dictionaries with 
the same consecutively numbered small integer keys can vary the order in 
which the keys are returned:

>>> d1 = dict.fromkeys([1,2])
>>> d2 = dict.fromkeys([9,1,2])
>>> del d2[9]
>>> d1
{1: None, 2: None}
>>> d2
{2: None, 1: None}

In current C-Python implementations, the hash code for an integer is 
simply the integer itself. That means there is a strong tendency for 
consecutive integers to be stored in consecutive slots in the 
dictionary. However as soon as you get gaps, or add the keys out of 
order, there is a opportunity for higher valued keys to displace lower 
valued keys into a different slot.

If you want the keys sorted then sort them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Howto find dict members from a list of keys

2007-03-08 Thread Steven D'Aprano
On Thu, 08 Mar 2007 05:26:22 -0300, Gabriel Genellina wrote:

> En Thu, 08 Mar 2007 05:20:20 -0300, Alexander Eisenhuth  
> <[EMAIL PROTECTED]> escribió:
> 
>> what algo do you use, when you want to find the dict values from d, with  
>> members
>> of l. Following example:
>>
>>  >>> d = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:10}
>>  >>> l = [7,8]
>>  >>> found_dic_members = 
>>  >>> print found_dict_members
>> [8,9]
> 
> found_dic_members = [d[key] for key in l]

*self stares at the line of code*

*self thinks about what he just posted*

*self realises with acute embarrassment that he's jumped to conclusions
and completely misunderstood the Original Poster's question*

Oops! I'll just be slinking away now... 



-- 
Steven D'Aprano 

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


Re: Descriptor/Decorator challenge

2007-03-08 Thread Michele Simionato
Raymond Hettinger wrote:
> Any trick in the book (metaclasses, descriptors, etc) is fair game.

So you are asking for a serious hack, right?

As soon as I saw your challenge I thought "That's difficult. Very
difficult.
No way I can solve that with a simple descriptor/decorator. I need
more POWER.
Time to look at the byteplay module".

The byteplay module by Noam Raphael (http://byteplay.googlecode.com/
svn/trunk/byteplay.py) seems to exist just to make possible
spectacular hacks. So I took
your challenge as an opportunity to explore a bit its secrets. In
doing so,
I have also decided to break the rules and not to solve your problem,
but
a different one, which is the one I am more interested in ;)

Basically, I am happy with the double underscores, but I am unhappy
with
the fact that a method does not know the class where it is defined, so
that you have to repeat the name of the class in ``super``.

With some bytecode + metaclass hackery it is possible to make the
methods
smart enough to recognize the class where they are defined, so your
example could be solved as follows:

from currentclass import CurrentClassEnabled

class A(CurrentClassEnabled):
def m(self):
print 'A.m'
def am(self):
CurrentClass.m(self) # the same as A.m(self)

class B(A):
def m(self):
print 'B.m'
def bm(self):
CurrentClass.m(self) # the same as B.m(self)
def superm(self):
super(CurrentClass, self).m() # the same as super(B, self).m()

m = B()
m.am() # prints 'A.m'
m.bm() # prints 'B.m'
m.superm() # prints 'A.m'

As you see, as a byproduct, double underscores are not needed anymore,
since methods are called directly from the CurrentClass. The approach
also works for ordinary attributes which are not methods.

The code to enable recognition of CurrentClass is short enough to be
includede here, but I will qualify it as a five star-level hackery:

$ cat currentclass.py
# requires byteplay by Noam Raphael
# see http://byteplay.googlecode.com/svn/trunk/byteplay.py
from types import FunctionType
from byteplay import Code, LOAD_GLOBAL, STORE_FAST, LOAD_FAST

def addlocalvar(f, locname, globname):
if locname not in f.func_code.co_names:
return f # do nothing
c = Code.from_code(f.func_code)
c.code[1:1] = [(LOAD_GLOBAL, globname), (STORE_FAST, locname)]
for i, (opcode, value) in enumerate(c.code[2:]):
if opcode == LOAD_GLOBAL and value == locname:
c.code[i+2] = (LOAD_FAST, locname)
f.func_code = c.to_code()
return f

class _CurrentClassEnabled(type):
def __new__(mcl, name, bases, dic):
for n, v in dic.iteritems():
if isinstance(v, FunctionType):
dic[n] = addlocalvar(v, 'CurrentClass', name)
return super(_CurrentClassEnabled, mcl).__new__(mcl, name,
bases, dic)

class CurrentClassEnabled:
__metaclass__ = _CurrentClassEnabled


Enjoy!

  Michele Simionato

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


splitting common functions into a sepperate module

2007-03-08 Thread jonkersbart
Dear,

I have wrote a script and want to group some functions of the script
in a separate modulo so that I can import the module in other scripts
and use the same functions there..

The problem is that the common functions need access to some global
variables defined in the script. Python uses different namespaces for
different modules so I can't access the variables of the script in the
module.

What is the best solution to solve this problem?

Thanks in advance,
Bart

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


Re: Problem with Packages

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 05:26:45 -0300, Srikanth <[EMAIL PROTECTED]> escribió:

>> It appears that you forgot the basic rule: a package is a directory with
>> an __init__.py file (even if empty).
>
> Exactly right. I didn't know that __init__.py is a mandatory one.
> Thanks for pointing out.

You may want to review this section on the Python Tutorial, covering  
packages:  
http://docs.python.org/tut/node8.html#SECTION00840

>> You need 4 of such files here.
>
> Thanks again for saying 4, cause I would have definetly put only 2
> (inside dir1_1 and dir2_2)

That was absolutely intentional :) so you had to figure out *where* to put  
the __init__.py files...

>> Maybe PyDev plays some tricks with PYTHONPATH or something...
>>
> I got the same doubt and I checked PyDev before posting, the
> PYTHONPATH is exactly the same but I didn't notice or rather
> overlooked __init__.py file it created automatically when I created
> packages using the dialogs.

Ah, those automagical tools...

> Thanks you Gabriel!

I'm glad you found it helpful!

-- 
Gabriel Genellina

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


Re: splitting common functions into a sepperate module

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 05:45:24 -0300, <[EMAIL PROTECTED]> escribió:

> I have wrote a script and want to group some functions of the script
> in a separate modulo so that I can import the module in other scripts
> and use the same functions there..
>
> The problem is that the common functions need access to some global
> variables defined in the script. Python uses different namespaces for
> different modules so I can't access the variables of the script in the
> module.

Are those *really* global variables? If yes, you could put them in yet  
another module, maybe config.py, and always get/set them using:
import config
config.xxx = "abc"
foo(x, config.yyy)
(do *not* use: from config import xxx)

Or, you may consider placing the global variables on the same module as  
those common functions (if that make some sense...)

But perhaps they are not really global variables, and you can use some  
class to hold them, specially if you can logically attach some methods to  
it.

Without further knowledge of the application, that's all I can say.

-- 
Gabriel Genellina

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


Re: catching exceptions from an except: block

2007-03-08 Thread Gerard Flanagan
On Mar 7, 7:32 pm, "Arnaud Delobelle" <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> Imagine I have three functions a(x), b(x), c(x) that each return
> something or raise an exception.  Imagine I want to define a function
> that returns a(x) if possible, otherwise b(x), otherwise c(x),
> otherwise raise CantDoIt.
>


(This is my first decorator.)  You could also just raise your custom
exception rather than having a "retval". Other variations I'm sure are
possible. HTH.


import exceptions

class ABCException(exceptions.Exception):
pass

def onfail(retval):
def outer(fn):
def inner(*args, **kwargs):
try:
return fn(*args, **kwargs)
except:
return retval
return inner
return outer

@onfail(False)
def a(x):
if x == 1:
return 'function a succeeded'
else:
raise

@onfail(False)
def b(x):
if x == 2:
return 'function b succeeded'
else:
raise

@onfail(False)
def c(x):
if x == 3:
return 'function c succeeded'
else:
raise

def doit(x):
for f in [a, b, c]:
result = f(x)
if result:
return result
raise ABCException()

print doit(1)
print doit(2)
print doit(3)
print doit(4)

---

function a succeeded
function b succeeded
function c succeeded
Traceback (most recent call last):
  File "\working\scratch.py", line 48, in ?
print doit(4)
  File "\working\scratch.py", line 43, in doit
raise ABCException()
__main__.ABCException
shell returned 1




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


Re: Descriptor/Decorator challenge

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 05:37:39 -0300, Michele Simionato  
<[EMAIL PROTECTED]> escribió:

> The code to enable recognition of CurrentClass is short enough to be
> includede here, but I will qualify it as a five star-level hackery:

You forgot the standard disclaimer: "This is extremely dangerous stuff,  
only highly trained professionals can do that! Kids, never try this at  
home!"

-- 
Gabriel Genellina

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


Re: Howto find dict members from a list of keys

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 05:37:48 -0300, Steven D'Aprano  
<[EMAIL PROTECTED]> escribió:

> On Thu, 08 Mar 2007 05:26:22 -0300, Gabriel Genellina wrote:
>
>> found_dic_members = [d[key] for key in l]
>
> *self stares at the line of code*
>
> *self thinks about what he just posted*
>
> *self realises with acute embarrassment that he's jumped to conclusions
> and completely misunderstood the Original Poster's question*
>
> Oops! I'll just be slinking away now...

LOL! :)

(...now! But when I saw your previous post, I had to check whether it was  
*me* who misunderstood the OP answering with a silly one-liner...)


-- 
Gabriel Genellina

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


Re: catching exceptions from an except: block

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 06:17:37 -0300, Gerard Flanagan  
<[EMAIL PROTECTED]> escribió:

> @onfail(False)
> def a(x):
> if x == 1:
> return 'function a succeeded'
> else:
> raise

I know it's irrelevant, as you use a bare except, but such raise looks a  
bit ugly...

-- 
Gabriel Genellina

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


property syntax

2007-03-08 Thread bearophileHUGS
Probably you have already discussed this topic, but maybe you can
stand touching it again briefly.
Maybe properties aren't used so often to deserve a specific syntax,
but I don't like their syntax much. Here I show some alternative
solutions that work with the current Python, followed by a syntax
idea, that may be better fit for Python 3.0 (but maybe changing its
name it can be retrofitted into Python 2.6 too).

Some code is from:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
That I have modified to suit my tastes.


# The first version doesn't work with Psyco:
# import psyco; psyco.full()

import sys

def nestedproperty(function):
keys = '__get__', '__set__', '__del__'
func_locals = {'doc':function.__doc__}
def probe_function(frame, event, arg):
if event == 'return':
locals = frame.f_locals
func_locals.update(dict((k, locals.get(k)) for k in keys))
sys.settrace(None)
return probe_function
sys.settrace(probe_function)
function()
return property(fget=func_locals.get("__get__"),
fset=func_locals.get("__set__"),
fdel=func_locals.get("__del__"),
doc=func_locals.get("doc")
   )


class Angle(object):
def __init__(self, rad):
self._rad = rad

@nestedproperty
def rad():
"The angle in radians"
def __get__(self):
return self._rad
def __set__(self, angle):
if isinstance(angle, Angle):
angle = angle.rad
self._rad = float(angle)

a = Angle(5)
print a.rad
a.rad = 10
print a.rad
help(a)

# =

# The second version is cleaner, but at the moment it has a problem
with the property docstring (but that may be fixed) (it works with
Psyco):

class classpropertytype(property):
"Pythonic property syntax."
# Code from:
# 
www.z3lab.org/sections/blogs/philipp-weitershausen/2006_05_29_pycon-06-lightning-talk/
def __init__(self, name, bases=(), members=None):
if members is None:
members = {}
doc = members.get('__doc__')
if doc is None:
doc = members.get('__get__').__doc__
sup = super(classpropertytype, self)
return sup.__init__(members.get('__get__'),
members.get('__set__'),
members.get('__del__'),
doc)
classproperty = classpropertytype('classproperty')

class Angle(object):
def __init__(self, rad):
self._rad = rad

class rad(classproperty):
"The angle in radians"
def __get__(self):
return self._rad
def __set__(self,angle):
if isinstance(angle, Angle):
angle = angle.rad
self._rad = angle

a = Angle(5)
print a.rad
a.rad = 10
print a.rad
help(a)

# =

# The third way has a bit of magic, but I like it best, and it works
with Psyco too:

class _property_meta(type):
def __new__(meta, class_name, bases, new_attrs):
if bases == (object,):
# The property class itself
return type.__new__(meta,class_name,bases,new_attrs)
keys = "fget fset fdel __doc__".split()
return property(*(new_attrs.get(k) for k in keys))

class classproperty(object):
__metaclass__ = _property_meta

def __new__(cls, fget=None, fset=None, fdel=None, fdoc=None):
if fdoc is None and fget is not None:
fdoc = fget.__doc__
return property(fget, fset, fdel, fdoc)


class Angle(object):
def __init__(self, rad):
self._rad = rad

class rad(classproperty):
"The angle in radians"
def fget(self):
return self._rad
def fset(self,angle):
if isinstance(angle, Angle):
angle = angle.rad
self._rad = angle


a = Angle(5)
print a.rad
a.rad = 10
print a.rad
help(a)


# =

# I may appreciate a better syntax, this is just an idea:
# (George Sakkis has suggested a different syntax that I like less)

"""

class Angle(object):
def __init__(self,rad):
self._rad = rad

property rad:
"The angle in radians"
def __get__(self):
return self._rad
def __set__(self, angle):
if isinstance(angle, Angle):
angle = angle.rad
self._rad = angle

class Angle2(Angle):
property rad:
def __get__(self):
return self._rad * 2

"""

# I'd like that possible syntax to mean this:

class Angle(object):
def __init__(self, rad):
self._rad = rad

def get_rad(self):
return self._rad

def set_rad(self, angle):
if isinstance(angle, Angle):
angle = angle.rad
self._rad = angle

rad = property(fget=lambda self: self.get_ra

Re: splitting common functions into a sepperate module

2007-03-08 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Dear,
> 
> I have wrote a script and want to group some functions of the script
> in a separate modulo so that I can import the module in other scripts
> and use the same functions there..
> 
> The problem is that the common functions need access to some global
> variables defined in the script.

And now you find out why globals are bad...

> Python uses different namespaces for
> different modules so I can't access the variables of the script in the
> module.
> 
> What is the best solution to solve this problem?

There's no one-size-fits-all answer. Usual solutions include:
- passing the needed values as args to the functions
- wrapping the functions as methods of a class, passing the whole state 
as args to the class initializer.



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


Re: Jython Data Extraction problem

2007-03-08 Thread Diez B. Roggisch
Steve Williams wrote:

> The data is an 8-byte 2s complement binary integer stored in a MSSQL
> 2005 CHAR column.  (COBOL did that, not me). I'm using zxJDBC to read
> the data and Jython to process.
> I could extract the integer if it wasn't returned in the resultset as
> unicode.  Things like ord(char) and struct.unpack('>B',char) to get at
> the bits don't seem to work.  struct.unpack('>g',string) is not available.
> I've tried fooling with charset in the url and the connect statement and
> tried encode, but I have no experience here.
> Is there anyway to get Jython/zxJDBC to stop converting the string to
> unicode?
> Any advice is welcome.

It's a JDBC-thing in the end, see if you find a solution there. Apart from
that, I don't see the problem really - why can't you just create a
byte-string by using the .encode-method? Sure, you need to know which
encoding was actually used when reading the bytes from the DB. But you
should be able to figure that out, there aren't too much candidates -
basically the usual suspects of cp1250, latin1 and the like.

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


Re: Descriptor/Decorator challenge

2007-03-08 Thread Michele Simionato
On Mar 8, 10:20 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> You forgot the standard disclaimer: "This is extremely dangerous stuff,
> only highly trained professionals can do that! Kids, never try this at
> home!"

;)

Yep, the only good use case for this kind of games is for prototyping
in current Python
features that are candidate for inclusion in future versions of
Python, but this was
what Raymond asked. However, there is also the fun of it ;)

Michele Simionato

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


Re: multithreading concept

2007-03-08 Thread Bryan Olson
sturlamolden wrote:
[...]
> If you want to utilize the computing power of multiple CPUs, you
> should use multiple processes instead of threads. On Python this is
> mandatory due to the GIL. In any other language it it highly
> recommended. The de-factor standard for parallel multiprocessing (MPI)
> uses multiple processes, even on SMPs.

That doesn't really work in Python. There have been projects to
allow Pythonic coordination of processes -- POSH had some good
ideas -- but none have reached fruition.

There's nothing like a close thing to a good defacto standard in
the area. Microsoft's Win32 threads can claim to get as close as
anything.


-- 
--Bryan


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


Re: How to build a Windows service using win32?

2007-03-08 Thread Giles Brown
On 7 Mar, 16:45, "Gregor Mosheh" <[EMAIL PROTECTED]> wrote:
> Giles Brown wrote:
> > Yeah.  You've cleverly decided to simplify the "smallest
> > possible python service" by removing the
> > if __name__ == '__main__':
>
> Ha ha. :)
> Seriously, though, I removed that long after it was failing to work, and
> have since replaced it and it didn't affect a thing.

Thats "didn't affect a thing" in the sense of "it was still broken but
so it didn't *affect a thing* when something else about it was
broken"? Yeah?

For the record I'm pretty confident that the "if __name__ ==
'__main__':" is necessary to stop the module attempting to handle the
command line with the pythonservice.exe looks to import the service
class when you start the service via the SCM.

Anyway you've got it working now so thats the main thing.

Giles

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


Re: VIM: Python type indented-block command equivalent to % for C?

2007-03-08 Thread Roel Schroeven
Paddy3118 schreef:
> Assuming that only space characters are allowed
> for indenting, is their a way to yank a Python
> block like y% works for C , or a way to move to
> the end of a block defined by indentation?
> 
> I have tried help indent but could not find
> anything.

I don't know either, but if you find anything, please post it to this 
list: I'm looking for such functionality too.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: is it possible to give an instance a value?

2007-03-08 Thread egbert
On Thu, Mar 08, 2007 at 01:22:25PM +1100, Steven D'Aprano wrote:

> On Wed, 07 Mar 2007 16:02:05 +0100, egbert wrote:
> > My impression is that you can do everything you want to
> > by making your instance callable, and not using a but a().
 
> You can't do this:
> 
> >>> a() = "some value"

I didn't say that you can do that. 
But in my example you can do
>>>  a("some value")
and that seems to be near enough for manstey.
e
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Re: splitting common functions into a sepperate module

2007-03-08 Thread jonkersbart
On 8 mrt, 10:36, Bruno Desthuilliers  wrote:
> [EMAIL PROTECTED] a écrit :
>
> > Dear,
>
> > I have wrote a script and want to group some functions of the script
> > in a separate modulo so that I can import the module in other scripts
> > and use the same functions there..
>
> > The problem is that the common functions need access to some global
> > variables defined in the script.
>
> And now you find out why globals are bad...
>
> > Python uses different namespaces for
> > different modules so I can't access the variables of the script in the
> > module.
>
> > What is the best solution to solve this problem?
>
> There's no one-size-fits-all answer. Usual solutions include:

I was hoping for a one-size-fits-all answer. But it seems to be that
it doesn't exists.
I already know these solutions, but was hoping for a better one.

> - passing the needed values as args to the functions
There are to many arguments so this is not a preferred solutions

> - wrapping the functions as methods of a class, passing the whole state
> as args to the class initializer.
I already considerate this one, but I don't like it because it is not
correct in terms of the object-oriented concept.
Because there are no other solutions I have to bury my bad feelings
and use this solution.

Thanks,
Bart


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

Re: property syntax

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 06:34:12 -0300, <[EMAIL PROTECTED]> escribió:

> Probably you have already discussed this topic, but maybe you can
> stand touching it again briefly.
> Maybe properties aren't used so often to deserve a specific syntax,
> but I don't like their syntax much. Here I show some alternative
> solutions that work with the current Python, followed by a syntax
> idea, that may be better fit for Python 3.0 (but maybe changing its
> name it can be retrofitted into Python 2.6 too).

You miss this common way, that does not depend on metaclasses, nor base  
classes, nor custom decorators... The only drawback is the "deprecated"  
status of apply:

class Angle(object):

@apply
def rad():
  doc = "The angle in radians"
  def fget(self):
return self._rad
  def fset(self, value):
self._rad = value
  return property(**locals())


(Hmmm... I wonder what the 2to3 conversion tool is doing in this case?)

-- 
Gabriel Genellina

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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-08 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> If they are better-than
> average, they might try this:
> 
 D = {1: None, 4: None, 3:None} # keys out of order
 D
> {1: None, 3: None, 4: None}
> 
> Still ordered, right? It's actually quite hard to get a dict with purely
> integer keys out of order.

It isn't hard at all.

The next step would be to try something with a few more than 3 keys and 
decide that you can't be bothered with all that typing and inventing 
values.

dict.fromkeys([randint(0,99) for i in range(10)])

gives you keys out of order about 99.92% of the time.

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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-08 Thread Paul Rubin
"John" <[EMAIL PROTECTED]> writes:
> I am coding a radix sort in python and I think that Python's dictionary may 
> be a choice for bucket.

Why are you coding a radix sort? 

> The only problem is that dictionary is a mapping without order. But
> I just found that if the keys are numeric, the keys themselves are
> ordered in the dictionary.

Just an accident, dicts are implemented using hashing, and small
integers hash to themselves.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: splitting common functions into a sepperate module

2007-03-08 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, jonkersbart
wrote:

>> - wrapping the functions as methods of a class, passing the whole state
>> as args to the class initializer.
> I already considerate this one, but I don't like it because it is not
> correct in terms of the object-oriented concept.

Why?  I thought combining state/data and related functions into one object
is a key concept of OOP.

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


Configuration: Apache + mod_python

2007-03-08 Thread Danilo
Hi there,

is it possible to create a rewrite rule to send every server-request
to the directory /py? But only if the file does not exists on the
server.

This is my mod_python section of the apache config-file.


SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonPath "['/var/www/mydomain.com/htdocs/py'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE myapp.settings
PythonDebug Off


Thanks.

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


Re: splitting common functions into a sepperate module

2007-03-08 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> On 8 mrt, 10:36, Bruno Desthuilliers > - wrapping the functions as methods of a class, passing the whole state
>> as args to the class initializer.
> I already considerate this one, but I don't like it because it is not
> correct in terms of the object-oriented concept.

Oh yes ? Why so ? You have a bunch of behaviors dependent on a same 
state, don't you ?


> Because there are no other solutions I have to bury my bad feelings
> and use this solution.

Better to leave "correctness of object-oriented concept" to purists and 
zealots, and use the appropriate *pragmatic* solution IMHO. No reason to 
have "bad feelings" here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property syntax

2007-03-08 Thread bearophileHUGS
Gabriel Genellina:
> You miss this common way, that does not depend on metaclasses,
> nor base classes, nor custom decorators...

My purpose was to discuss a new syntax. The other stuff is mostly for
reference, to show that lot of (some) people has tried to find
alternative solutions to a problem they feel.


> The only drawback is the "deprecated"

I can see other drawbacks: you have to use an explicit doc = "..."
instead of a normal docstring, and you have to remember to put return
property(**locals()) at its end. I don't know if your version is
compatible with Psyco (I presume it's compatible). And I think all
those solutions can't be subclassed like I have shown in the
altenative syntax (but maybe you can find a way to modify the
metaclass version to allow this too).

Bye and thank you,
bearophile

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


Re: multithreading concept

2007-03-08 Thread Paul Boddie
On 8 Mar, 10:48, Bryan Olson <[EMAIL PROTECTED]> wrote:
>
> That doesn't really work in Python. There have been projects to
> allow Pythonic coordination of processes -- POSH had some good
> ideas -- but none have reached fruition.

What makes all of the following not "Pythonic"...?

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

Things like the CSP paradigm have sort of made their way into the
Python language itself, via enhancements to the yield keyword, which
has the dubious distinction of being a keyword which appears to return
a value. I'm sure one could define "Pythonic" as being "you can write
code like you do now (but not like any of the ways encouraged by the
aforementioned solutions) and it just works over multiple processors/
cores", but that's a view which is somewhat detached from the
practicalities (and favoured practices) of concurrent programming,
especially given the few guarantees Python would be able to provide to
make such a thing work effectively.

Paul

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


Re: Configuration: Apache + mod_python

2007-03-08 Thread Graham . Dumpleton
On Mar 8, 9:50 pm, "Danilo" <[EMAIL PROTECTED]> wrote:
> Hi there,
>
> is it possible to create a rewrite rule to send every server-request
> to the directory /py? But only if the file does not exists on the
> server.
>
> This is my mod_python section of the apache config-file.
>
> 
> SetHandler python-program
> PythonHandler django.core.handlers.modpython
> PythonPath "['/var/www/mydomain.com/htdocs/py'] + sys.path"
> SetEnv DJANGO_SETTINGS_MODULE myapp.settings
> PythonDebug Off
> 

For the more general case of where a HTTP 404 error would otherwise be
returned, indicating that a resource could not be found, as opposed to
an actual physical file, you can just use:

  ErrorDocument 404 /py

This would be simpler than using mod_rewrite. I can't remember though
whether the handler when triggered in this case can change the
response status to something other than 404.

You could use mod_rewrite if you really must, but not sure how it
would interact with virtual resources managed by some handler where no
actual file exists. To be practical you would probably want to
restrict the scope of mod_rewrite to specific contexts.

Quoting an example from very good book "The Definitive Guide to Apache
mod_rewrite", you can do something similar to:

  RewriteEngine On
  # If its not here ...
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  # Look here instead ...
  RewriteRule ^/images/(.*) /pics/$1 [PT]

In this case it is causing lookups for images to be made in two
places, but your case wouldn't be much different.

Graham

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


Re: thread and portability Unix/Linux

2007-03-08 Thread awalter1
On 7 mar, 21:07, "Joshua J. Kugler" <[EMAIL PROTECTED]> wrote:
> awalter1 wrote:
> > Hi,
> > I have a Python application that runs under HPUX 11.11 (then unix). It
> > uses threads :
> > from threading import Thread
> > # Class Main
> > class RunComponent(Thread):
>
> > My application should run under Linux (red hat 3 ou 4) and I read that
> > differences exist between the implementation of threads : on HPUX
> > 11.11 there is CMA (ou DCE) threads and on Linux POSIX thread. Do you
> > think that my Python application should be modified or may be such
> > differences are hidden by the python interpreter ?
> > In other terms, do I get some risks on this particular aspect by
> > porting my application ?
> > Thanks a lot
>
> > PS: If you are aware of other risk of porting, I am interested too.
>
> The Python threading model abstracts from the underlying OS threading, so
> there should be no need to change anything (AFAIK).
>
> j
>
> --
> Joshua Kugler
> Lead System Admin -- Senior Programmerhttp://www.eeinternet.com
> PGP Key:http://pgp.mit.edu/ ID 0xDB26D7CE
>
> --
> Posted via a free Usenet account fromhttp://www.teranews.com- Masquer le 
> texte des messages précédents -
>
> - Afficher le texte des messages précédents -

Marvellous !
Thank you

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


Re: Howto find dict members from a list of keys

2007-03-08 Thread James Stroud
Gabriel Genellina wrote:
> En Thu, 08 Mar 2007 05:37:48 -0300, Steven D'Aprano 
> <[EMAIL PROTECTED]> escribió:
> 
>> On Thu, 08 Mar 2007 05:26:22 -0300, Gabriel Genellina wrote:
>>
>>> found_dic_members = [d[key] for key in l]
>>
>> *self stares at the line of code*
>>
>> *self thinks about what he just posted*
>>
>> *self realises with acute embarrassment that he's jumped to conclusions
>> and completely misunderstood the Original Poster's question*
>>
>> Oops! I'll just be slinking away now...
> 
> LOL! :)
> 
> (...now! But when I saw your previous post, I had to check whether it 
> was *me* who misunderstood the OP answering with a silly one-liner...)
> 
> 
> --Gabriel Genellina
> 
I think it was a silly one-liner.

If you look closely at the example, the only mapping of

[7, 8] ==> [8, 9]

is

[key, key] ==> [value, value]

Look again at the example and consider the positional relationships.

The answer, then, is trivial if not silly:

[d[k] for k in l]

It doesn't appear he as asking for the interesting case:

[value, value] ==> [key, key]

Its easy to see how Gabriel was thrown for a loop on this one.

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


Re: Howto find dict members from a list of keys

2007-03-08 Thread Alexander Eisenhuth
Yes it was the silly on-liner ... it was a bit ago I used it last time ... 
thanks

Gabriel Genellina schrieb:
> En Thu, 08 Mar 2007 05:37:48 -0300, Steven D'Aprano 
> <[EMAIL PROTECTED]> escribió:
> 
>> On Thu, 08 Mar 2007 05:26:22 -0300, Gabriel Genellina wrote:
>>
>>> found_dic_members = [d[key] for key in l]
>>
>> *self stares at the line of code*
>>
>> *self thinks about what he just posted*
>>
>> *self realises with acute embarrassment that he's jumped to conclusions
>> and completely misunderstood the Original Poster's question*
>>
>> Oops! I'll just be slinking away now...
> 
> LOL! :)
> 
> (...now! But when I saw your previous post, I had to check whether it 
> was *me* who misunderstood the OP answering with a silly one-liner...)
> 
> 
> --Gabriel Genellina
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert an integer to a float?

2007-03-08 Thread Antoon Pardon
On 2007-03-05, Andrew Koenig <[EMAIL PROTECTED]> wrote:
><[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> Hi, I have the following functions,  but ' dx = abs(i2 - i1)/min(i2,
>> i1)' always return 0, can you please tell me how can i convert it from
>> an integer to float?
>
> I don't think that's what you really want to do.
>
> What you really want is for dx to be a float rather than being truncated to 
> an integer.  Division is going to behave that way in the future, so if you 
> want it to behave that way now, you can write
>
> from __future__ import division
>
> at the beginning of your program.
>
> If for some reason you don't want to rely on using a version of Python that 
> knows about this future behavior, you might consider
>
> dx = float(abs(i2 - i1))/min(i2, i1)

I prefer to multiply by 1.0 That has the advantage it continues to work
if your numbers happen to be complex.

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


Re: Configuration: Apache + mod_python

2007-03-08 Thread Danilo
On 8 Mrz., 12:18, [EMAIL PROTECTED] wrote:
> On Mar 8, 9:50 pm, "Danilo" <[EMAIL PROTECTED]> wrote:
>
> > Hi there,
>
> > is it possible to create a rewrite rule to send every server-request
> > to the directory /py? But only if the file does not exists on the
> > server.
>
> > This is my mod_python section of the apache config-file.
>
> > 
> > SetHandler python-program
> > PythonHandler django.core.handlers.modpython
> > PythonPath "['/var/www/mydomain.com/htdocs/py'] + sys.path"
> > SetEnv DJANGO_SETTINGS_MODULE myapp.settings
> > PythonDebug Off
> > 
>
> For the more general case of where a HTTP 404 error would otherwise be
> returned, indicating that a resource could not be found, as opposed to
> an actual physical file, you can just use:
>
>   ErrorDocument 404 /py
>
> This would be simpler than using mod_rewrite. I can't remember though
> whether the handler when triggered in this case can change the
> response status to something other than 404.
>
> You could use mod_rewrite if you really must, but not sure how it
> would interact with virtual resources managed by some handler where no
> actual file exists. To be practical you would probably want to
> restrict the scope of mod_rewrite to specific contexts.
>
> Quoting an example from very good book "The Definitive Guide to Apache
> mod_rewrite", you can do something similar to:
>
>   RewriteEngine On
>   # If its not here ...
>   RewriteCond %{REQUEST_FILENAME} !-f
>   RewriteCond %{REQUEST_FILENAME} !-d
>   # Look here instead ...
>   RewriteRule ^/images/(.*) /pics/$1 [PT]
>
> In this case it is causing lookups for images to be made in two
> places, but your case wouldn't be much different.
>
> Graham

The rewrite rule works, but now every request ist send to /py.
This is my .conf:


DocumentRoot /var/www/mydomain.com/htdocs
ServerName mydomain.com
ServerAlias www.mydomain.com


SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonPath "['/var/www/mydomain.com/htdocs/py'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE myapp.settings
PythonDebug Off


RewriteEngine On
# If its not here...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Look here instead...
RewriteRule (.*) /py$1 [PT]

ErrorLog /var/www/mydomain.com/logs/error.log
CustomLog /var/www/mydomain.com/logs/access.log common


Any ideas what is wrong?

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


writing dictionary to file

2007-03-08 Thread kavitha thankaian
Hi,
   
  I have  'n' number of dictionaries with the same name but different values
  ( DorC means debit or credit)
   
   
  some={'DorC':'D', 'amount':200,'name':'xxx'}
  some={'DorC':'C', 'amount':200,'name':'xxx'}
  some={'DorC':'D', 'amount':300,'name':'yyy'}
  some={'DorC':'C', 'amount':500,'name':'yyy'}
  some={'DorC':'D', 'amount':700,'name':zzz}
  some={'DorC':'C', 'amount':900,'name':zzz}  and so on,,,
   
  if the credit and debit is not equal for a person, then i would like to open 
a file and write it in the following format:
   
  name:yyy
  debit:300
  credit:500
   
  name:zzz
  debit:700
  credit:900
   
  can anyone help me???
   
  kavitha


-
 Here’s a new way to find what you're looking for - Yahoo! Answers -- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to check whether file is open or not

2007-03-08 Thread Ros

Thanks a lot Gabriel.
ctypes is working!

Regards,
Ros


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


Re: Generator expression parenthesis mixed with function call ones

2007-03-08 Thread Laurent Pointal
Gabriel Genellina a écrit :
> If you want to review the original discussion on how to spell a
> generator expression (called "accumulator display" by that time) see
> http://mail.python.org/pipermail/python-dev/2003-October/038868.html

That's a long discussion... and it seem I'm not alone to dislike parens
confusion.

http://mail.python.org/pipermail/python-dev/2003-October/038906.html

Thanks for the pointer.

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


Re: How to check whether file is open or not

2007-03-08 Thread Bart Ogryczak
On Mar 7, 6:28 am, "Ros" <[EMAIL PROTECTED]> wrote:
> There are 10 files in the folder. I wish to process all the files one
> by one. But if the files are open or some processing is going on them
> then I do not want to disturb that process. In that case I would
> ignore processing that particular file and move to next file.

If you can os.open() with O_EXLOCK flag, it's not open by other
process. Now that should work on Unix, Linux and MacOS X. All Windows
proceeding form NT line, are supposed to be POSIX compatible, but
somehow this flag is not available.





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


Re: VIM: Python type indented-block command equivalent to % for C?

2007-03-08 Thread Antony Scriven
[F-ups set to comp.editors]

Paddy3118 wrote:

 > Not python:
 > but python type
 > indented text
 >
 > Notice the blank line above.
 > It could have several
 > spaces or tabs, and still
 > be a part of the block
 > beginning 'Not python:':
 >   The block ends at the
 >   first non-blank line
 >   with less indent.
 >
 > Assuming that only space characters are allowed
 > for indenting, is their a way to yank a Python
 > block like y% works for C , or a way to move to
 > the end of a block defined by indentation?

I expect there are scripts for Python. Try googling and
www.vim.org. Anyway I'm not sure that I understand your
description 100%, but try something like this.

   :ono = /\n.*\%<=indent('.')c\S\\|\%$/+0

Now try d= y= etc. Also note that I've made it work
linewise. And take look at :help /\%v if you want it to
work with tabs. --Antony

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


heapq.heappush and pop to use key

2007-03-08 Thread [EMAIL PROTECTED]
I wanted to have a heap of custom objects, and in different heaps I
wanted to have the weights for my elements differently. So, I modified
the heapq module to accept key arguments also.

The untested code is here. Please let me know if you find any bug or
if there is an easy way to do this.

-
Suresh
-
__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace',
'nlargest',
   'nsmallest']

from itertools import islice, repeat, count, imap, izip, tee
from operator import itemgetter
import bisect

pass_it = lambda x: x

def heappush(heap, item, key=pass_it):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap)-1, key=key)

def heappop(heap, key=pass_it):
"""Pop the smallest item off the heap, maintaining the heap
invariant."""
lastelt = heap.pop()# raises appropriate IndexError if heap is
empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0, key)
else:
returnitem = lastelt
return returnitem

def heapreplace(heap, item, key=pass_it):
"""Pop and return the current smallest value, and add the new
item.

This is more efficient than heappop() followed by heappush(), and
can be
more appropriate when using a fixed-size heap.  Note that the
value
returned may be larger than item!  That constrains reasonable uses
of
this routine unless written as part of a conditional replacement:

if item > heap[0]:
item = heapreplace(heap, item)
"""
returnitem = heap[0]# raises appropriate IndexError if heap is
empty
heap[0] = item
_siftup(heap, 0, key)
return returnitem

def heapify(x, key=pass_it):
"""Transform list into a heap, in-place, in O(len(heap)) time."""
n = len(x)
# Transform bottom-up.  The largest index there's any point to
looking at
# is the largest with a child index in-range, so must have 2*i + 1
< n,
# or i < (n-1)/2.  If n is even = 2*j, this is (2*j-1)/2 = j-1/2
so
# j-1 is the largest, which is n//2 - 1.  If n is odd = 2*j+1,
this is
# (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
for i in reversed(xrange(n//2)):
_siftup(x, i, key)

# 'heap' is a heap at all indices >= startpos, except possibly for
pos.  pos
# is the index of a leaf with a possibly out-of-order value.  Restore
the
# heap invariant.
def _siftdown(heap, startpos, pos, key):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a
place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if key(parent) <= key(newitem):
break
heap[pos] = parent
pos = parentpos
heap[pos] = newitem


def _siftup(heap, pos, key):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2*pos + 1# leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and key(heap[rightpos]) <=
key(heap[childpos]): # **CHANGED**
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2*pos + 1
# The leaf at pos is empty now.  Put newitem there, and bubble it
up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos, key)

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


Writing xml file from MS SQL

2007-03-08 Thread Ros
I am using pymssql for storing data into MS SQL. (I am using pymssql
first time so dont know much about it)
I wish to write/create XML file from database.
There are few examples available for mysql but not much information
about pymssql and MS SQL.

I have worked with cElementTree with SAX and I guess it can parse data
in the most efficient manner if you compare it with other parsers. How
can I use cElementTree to write xml file with the combination of
pymssql(MS SQL) and pyxml.

If you know any links, examples then please post them.

Regards,
Ros

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


Re: clientcookie/clientform and checking to see if a website accepted my login details

2007-03-08 Thread John J. Lee
[EMAIL PROTECTED] writes:

> alright, i'm coding a program that will log me into yahoo.com (so
> far), now, the problem i have is that once i've submitted by login &
> password, the program doesn't know whether yahoo.com accepted it.
> "
> response = ClientCookie.urlopen(form.click())
> "
> 
> now, when i get an error, the contents of 'response' will be
> different, ex: the contents of  'example' will be
> 'logged in!'. is there any function that can search
> through the code for that text to check if i'm logged in or not?

There's no general way to find out (regardless of whether you're using
Python or something else).  So:

data = response.read()
logged_in = 'logged in!' in data
if logged_in:
print "logged in OK"


John

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


Re: Writing xml file from MS SQL

2007-03-08 Thread Diez B. Roggisch
Ros wrote:

> I am using pymssql for storing data into MS SQL. (I am using pymssql
> first time so dont know much about it)
> I wish to write/create XML file from database.
> There are few examples available for mysql but not much information
> about pymssql and MS SQL.
> 
> I have worked with cElementTree with SAX and I guess it can parse data
> in the most efficient manner if you compare it with other parsers. How
> can I use cElementTree to write xml file with the combination of
> pymssql(MS SQL) and pyxml.

1) read data from database
2) create XML-Nodes filled with this data
3) write XML-Nodes to disk
4) 
5) Profit!

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


Re: heapq.heappush and pop to use key

2007-03-08 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> I wanted to have a heap of custom objects, and in different heaps I
> wanted to have the weights for my elements differently. So, I modified
> the heapq module to accept key arguments also.

I would have just used tuples of the form (weight, obj) with the original
`heapq` module.

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


Tell me the truth

2007-03-08 Thread francois . petitjean

In the python-ideas mailing list
http://mail.python.org/pipermail/python-ideas/2007-March/thread.html  there
was a discussion about the fact that python has opeartors 'and', 'or' and
'not' (keywords of the language) but 'bool'  is a type. Naturally we have
 (not not x) == bool(x)  # always True
If I take into account the fact that 'True' and 'False' are singletons
(guaranteed ?) :
 (not not x) is bool(x)  # should be always True.

>>> def ok(x):
... return (not not x) is bool(x)
...
>>> ok(0)
True
>>> ok(False)
True

ok(11) is True
True
Interesting Let's make another function:
>>> def foo(x):
... return (not not x) is bool(x)  is True
...
>>> foo(False)
False
>>> foo(0.0)
False
>>> foo(0.1)
True

To see if the problem comes from using the a is b is True form, let's try
>>> def ok3(x):
... return (not not x) is bool(x) == True
...
>>> ok3(44)
True
>>> ok3(0)
False

After much head scrating and experimenting with dis.dis() I have found that
chaining comparisons (with is or ==)  a == b == c in Python is never a good
idea. It is interpreted as
 ( a == b ) and ( b == c)
Such a magic is fine  when we write:
 if  0.0 <= x < 1.0:
but it renders the outcome of  if a == b == c: somewhat confusing. In the
reference documentation the sentences """Comparisons can be chained
arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except
that y is evaluated only once (but in both cases z is not evaluated at all
when x < y is found to be false). """ should be followed by a warning about
chaining '==' or similar operators.

Regards

PS. Sorry for bad english.


   NOTICE: This message contains information which is confidential and the
   copyright of our company or a third  party. If you are not the intended
   recipient of this message please delete it and destroy all copies. If
   you
   are the intended recipient of this message you should not disclose or
   distribute this message to third parties without the consent of our
   company. Our company does not represent, warrant and/or guarantee that
   the integrity of this message has been maintained nor that the
   communication is free of virus, interception or interference. The
   liability of our company is limited by our General Conditions of
   Services.
   Nota : Ce message contient des informations confidentielles propriété de
   notre société et/ou d'un tiers. Si vous n'êtes pas parmi les
   destinataires désignés de ce message, merci de l'effacer ainsi que
   toutes ses copies. Si vous êtes parmi les destinataires désignés de ce
   message, prière de ne pas le divulguer ni de le transmettre à des tiers
   sans l'accord de notre société. Notre société ne peut garantir que
   l'intégrité de ce message a été préservée ni que la présente
   communication est sans virus, interception ou interférence. La
   responsabilité de notre société est limitée par nos Conditions Générales
   de Services.


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


Copy geodatabase(mdb) if it is locked

2007-03-08 Thread Ahmed, Shakir
I am trying to copy a geodatabase (.mdb) file from source to destination
using

shutil.copyfile(src, dest)

 

It is working fine but the main problem when the destination (.mdb) file
is locked by other users then it's bumped out and not copied over.

 

Is there any way to copy the locked .mdb file and overwrite it.

 

Any help is highly appreciated.

 

shakir

 

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

Re: merits of Lisp vs Python

2007-03-08 Thread Stephen Eilert
On Mar 8, 5:23 am, John Nagle <[EMAIL PROTECTED]> wrote:
> Brian Adkins wrote:
> > Ken Tilton wrote:
>
> >> John Nagle wrote:
> > Turns out John is having quite a tough time with Python web hosting (the
> > thread has split off to a c.l.p only fork), so I'm going to cut him some
> > slack. Maybe with some lovin' we can woo him over to c.l.l ;)
>
>  Been there, done that.  I've actually used an original refrigerator
> sized Symbolics LISP machine.
>
>  I tend to think of Python as a LISP with infix syntax.
> We have a better handle on what to put in a dynamic language now, and
> Python does a good job in that direction.  I'm happy with the
> language; it's the integration with external components that isn't
> working.
>
> John Nagle


OMG! And I thought the thread was dead!

Necromancers! Run!!!

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


Reading a portion of a file

2007-03-08 Thread cmfvulcanius
I am using a script with a single file containing all data in multiple
sections. Each section begins with "#VS:CMD:command:START" and ends
with "#VS:CMD:command:STOP". There is a blank line in between each
section. I'm looking for the best way to grab one section at a time.
Will I have to read the entire file to a string and parse it further
or is it possible to grab the section directly when doing a read? I'm
guessing regex is the best possible way. Any help is greatly
appreciated.

Thanks

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


Re: Python Source Code Beautifier

2007-03-08 Thread Alan Franzoni
Il Wed, 07 Mar 2007 14:13:28 -0300, Gabriel Genellina ha scritto:

> __iadd__, in general, is not *required* to modify the instance in place  
> (but should try to do that, if possible). After this code:
>   b = a
>   a += c
> you can't assert than a and b both refer to the *same* object, as before.  
> If you need that, don't use += at all. (For a generic object, I mean. The  
> built-in list "does the right thing", of course)

Surely _I_ can't, and _I_ won't. But take the opposite example.

Let's say I'm using an external library, and that library's author provides
any kind of 'convenience' container type he feels useful for the library's
purposes, but without forcing a type constraint to the parameters passed to
a certain function - as should be done in a language like python, and this
container does create a copy of the object even employing incremental
operators.

Now, let's suppose I find that container type not useful for my purposes,
*or* I have already written a different container type which mimicks a
list's behaviour (adding some kind of functionality, of course).

Now, let's suppose a certain function in that library should give a certain
result based on the contents of that container, but without modifying the
original object, but it needs to modify it in order to do some operations. 

if the function looks like this:

def foo(container):
container += [1, 2, 3]
... 

it might happen that the original object gets modified even when it
shouldn't, depending on the actual object passed to the library.

What I just mean... I don't see calling extend() to be that painful in
respect to += . If there were no other way to do it, I would agree it would
be useful. But if there're such methods, do we really need this syntactic
sugar to introduce confusion?

-- 
Alan Franzoni <[EMAIL PROTECTED]>
-
Togli .xyz dalla mia email per contattarmi.
Remove .xyz from my address in order to contact me.
-
GPG Key Fingerprint (Key ID = FE068F3E):
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tell me the truth

2007-03-08 Thread Mikael Olofsson


[EMAIL PROTECTED] wrote:
> If I take into account the fact that 'True' and 'False' are singletons
> (guaranteed ?) :
>  (not not x) is bool(x)  # should be always True.
> [snip code and results of code]
>   
Consider the following:

 >>> def ok1(x):
return (not not x) is bool(x)

 >>> def ok2(x):
return (not not x) is bool(x) is True

 >>> def ok3(x):
return ok1(x) is True

 >>> def ok4(x):
return ((not not x) is bool(x)) is True

 >>> def ok5(x):
return ((not not x) is bool(x)) and (bool(x) is True)

 >>> for x in [False, True]:
print x,ok1(x), ok2(x), ok3(x), ok4(x), ok5(x)

   
False True False True True False
True True True True True True

Note that ok2(x) and ok5(x) exhibit the same behaviour.

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


Re: Tell me the truth

2007-03-08 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> After much head scrating and experimenting with dis.dis() I have found
> that chaining comparisons (with is or ==)  a == b == c in Python is
> never a good idea. It is interpreted as
>  ( a == b ) and ( b == c)
> Such a magic is fine  when we write:
>  if  0.0 <= x < 1.0:
> but it renders the outcome of  if a == b == c: somewhat confusing.

I don't understand why it is confusing. What other meaning would you 
expect?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: thread safe SMTP module

2007-03-08 Thread Aahz
In article <[EMAIL PROTECTED]>,
Gordon Messmer  <[EMAIL PROTECTED]> wrote:
>Aahz wrote:
>> 
>> Assuming you have correctly tracked down the problem area, I would call
>> that a thread bug in Python.  But my experience is that you simply have
>> run into a problem with the socket.  I would suggest that using
>> socket.setdefaulttimeout() would work just as well.
>
>I believe that solution, also would not work.  This note is included in 
>the socket documentation, regarding "timeout mode":
>
>http://docs.python.org/lib/socket-objects.html
>"A consequence of this is that file objects returned by the makefile() 
>method must only be used when the socket is in blocking mode; in timeout 
>or non-blocking mode file operations that cannot be completed 
>immediately will fail."
>
>smtplib.SMTP uses file objects when reading SMTP responses.  If I used 
>setdefaulttimeout(), then the socket would be in timeout mode and the 
>above note would be applicable.

Hrm.  At this point, I would suggest taking discussion to python-dev; it
has been too long since I looked closely at thread/socket behavior.

>I am not at all above calling python's behavior a bug, except that it 
>seemed like a known behavior given the note in the thread documentation 
>regarding built-in functions that block on I/O.

No, at this point I think this is neither bug nor about thread blocking
on I/O.  I think it's about sockets dying and the inability of sockets in
blocking mode to recover.  I have seen this kind of behavior in
single-threaded systems.  But it really needs someone who knows more than
I do, and I think the first step here is to go ahead and file a bug
report for tracking purposes.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I disrespectfully agree."  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: worker thread catching exceptions and putting them in queue

2007-03-08 Thread Aahz
In article <[EMAIL PROTECTED]>,
Paul Sijben  <[EMAIL PROTECTED]> wrote:
>
>in a worker thread setup that communicates via queues is it possible to
>catch exceptions raised by the worker executed, put them in an object
>and send them over the queue to another thread where the exception is
>raised in that scope?
>
>considering that an exception is an object I feel it ought to be
>possible, however I do not see how to go about it.

One caution: because exceptions keep stack frames alive, you can have
garbage collection problems.  Make sure to del the exception when you're
done with it.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I disrespectfully agree."  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython with Apache

2007-03-08 Thread Josh Bloom

Hi Ed,

Some more info about your environment will be helpful here.
What OS version, apache version, etc.

-Josh


On 7 Mar 2007 15:05:54 -0800, edfialk <[EMAIL PROTECTED]> wrote:


Hi all, I'm completely new to Python, but fairly experienced in PHP
and few other languages.

Long story short: The IronPython executable doesn't work for .cgi
scripts in my browser.


I've been assigned to write a service that pulls in parameters from
the URL, accesses a file and serves some data through a CSV.  The only
problem I foresee myself is accessing and reading this file, which is
a 'hyper-cube' in that it has many dimensions of data.

Anyway, the code for reading and writing this cube was already written
by a coworker in IronPython and .NET.  Again, I'm totally new to
Python but as I'm stepping through trying to pick out pieces that I
need, I can't even import clr.

So, I'm told I need IronPython, which I get, and I replace the #!c:
\Python25\python.exe with the IronPython executable (#!c:
\IronPython-1.0.1\ipy.exe), but I get a 500 Internal Server error and:

"[Wed Mar 07 17:02:21 2007] [error] [client 127.0.0.1] malformed
header from script. Bad header=  File , line 0, in __import__:
testing.cgi" in the Error log.

Does anyone know how to set up this 'IronPython' through Apache so I
can use it to read/write data?

Any help would be greatly appreciated.
Thanks!
-Ed

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

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

pylint: don't warn about tabs

2007-03-08 Thread Alan Isaac
I am brand new to pylint.
As a tab user, I want the tabs warning turned off.
How?

Larger question:
where is the config file format documented?

Thanks,
Alan Isaac

PS This is a wonderful tool.


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


Re: Reading a portion of a file

2007-03-08 Thread Rune Strand
On Mar 8, 5:12 pm, [EMAIL PROTECTED] wrote:
> I am using a script with a single file containing all data in multiple
> sections. Each section begins with "#VS:CMD:command:START" and ends
> with "#VS:CMD:command:STOP". There is a blank line in between each
> section. I'm looking for the best way to grab one section at a time.
> Will I have to read the entire file to a string and parse it further
> or is it possible to grab the section directly when doing a read? I'm
> guessing regex is the best possible way. Any help is greatly
> appreciated.

Seems like something along these line will do:

_file_ = "filepart.txt"

begin_tag = '#VS:CMD:command:START'
end_tag = '#VS:CMD:command:STOP'

sections = []
new_section = []
for line in open(_file_):
line = line.strip()
if begin_tag in line:
new_section = []
elif end_tag in line:
sections.append(new_section)
else:
if line: new_section.append(line)

for s in sections: print s

If your want more control, perhaps flagging "inside_section",
"outside_section" is an idea.


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


Re: pylint: don't warn about tabs

2007-03-08 Thread Bjoern Schliessmann
Alan Isaac wrote:

> I am brand new to pylint.
> As a tab user, I want the tabs warning turned off.
> How?

Advice: Don't. IIRC it's planned in future Python versions that TABs
aren't supported for indentation.

Regards,


Björn

-- 
BOFH excuse #401:

Sales staff sold a product we don't offer.

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


Re: tkinter text editor

2007-03-08 Thread Gigs_
Gigs_ wrote:
> I'm writing text editor.
> 
> How to enable/disable (cut, copy etc.) when text is selected/not selected
Btw it is cut copy ... in edit menu
-- 
http://mail.python.org/mailman/listinfo/python-list


tkinter text editor

2007-03-08 Thread Gigs_
I'm writing text editor.

How to enable/disable (cut, copy etc.) when text is selected/not selected
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tell me the truth

2007-03-08 Thread Erik Johnson

"Duncan Booth" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> [EMAIL PROTECTED] wrote:
>
> > After much head scrating and experimenting with dis.dis() I have found
> > that chaining comparisons (with is or ==)  a == b == c in Python is
> > never a good idea. It is interpreted as
> >  ( a == b ) and ( b == c)
> > Such a magic is fine  when we write:
> >  if  0.0 <= x < 1.0:
> > but it renders the outcome of  if a == b == c: somewhat confusing.
>
> I don't understand why it is confusing. What other meaning would you
> expect?

I can see how one might get themselves confused. I think it simply boils
down to thinking that

A == B == C  is shorthand for: (A == B) == C

It's not.  You're asserting that A is equivalent to B and B is equivalent to
C, NOT that the value of comparing A to B is equivalent to C:

>>> False is False
True
>>> False is False is True
False

If what you want is the second form, a pair of parenthesis forcing order of
evaluation will give it to you.

>>> (False is False) is True
True


-ej


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


Re: Reading a portion of a file

2007-03-08 Thread Jordan
On Mar 8, 11:52 am, "Rune Strand" <[EMAIL PROTECTED]> wrote:
> On Mar 8, 5:12 pm, [EMAIL PROTECTED] wrote:
>
> > I am using a script with a single file containing all data in multiple
> > sections. Each section begins with "#VS:CMD:command:START" and ends
> > with "#VS:CMD:command:STOP". There is a blank line in between each
> > section. I'm looking for the best way to grab one section at a time.
> > Will I have to read the entire file to a string and parse it further
> > or is it possible to grab the section directly when doing a read? I'm
> > guessing regex is the best possible way. Any help is greatly
> > appreciated.
>
> Seems like something along these line will do:
>
> _file_ = "filepart.txt"
>
> begin_tag = '#VS:CMD:command:START'
> end_tag = '#VS:CMD:command:STOP'
>
> sections = []
> new_section = []
> for line in open(_file_):
> line = line.strip()
> if begin_tag in line:
> new_section = []
> elif end_tag in line:
> sections.append(new_section)
> else:
> if line: new_section.append(line)
>
> for s in sections: print s
>
> If your want more control, perhaps flagging "inside_section",
> "outside_section" is an idea.

You probably don't want to use regex for something this simple; it's
likely to make things even more complicated.  Is there a space between
the begin_tag and the first word of a section (same question with the
end_tag)?

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


Re: Copy geodatabase(mdb) if it is locked

2007-03-08 Thread Tim Golden
Ahmed, Shakir wrote:
> I am trying to copy a geodatabase (.mdb) file from source to destination
> using
> 
> shutil.copyfile(src, dest)
> 
> It is working fine but the main problem when the destination (.mdb) file
> is locked by other users then it's bumped out and not copied over.
> 
> Is there any way to copy the locked .mdb file and overwrite it.


Usual rejoinder: is there any way to do it outside Python? (As far
as I know, there isn't although I'm happy to be wrong). If you haven't
already, try one of the platform-specific lists, since this is
really an OS-issue.

For a Python-ish solution, you might have a retries loop, which
kept trying and backing away for increasing periods of time until
it gave up or succeeded. Rough-and-ready and completely untested:


import shutil
import time

src = "c:/temp/temp.mdb"
dest = "c:/temp/temp2.mdb"

n_retries = 5
base_delay = 2

n_retry = 0
while n_retry < n_retries:
   try:
 shutil.copyfile (src, dest)
   except IOError:
 time.sleep (2 ** n_retry)
 n_retry += 1
 continue
   else:
 print "succeeded after", n_retry, "retries"
 break
else:
   print "failed after", n_retry, "retries"



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


Python threading

2007-03-08 Thread test . 07
I am wondering what happens to a thread in python in relation to
win32com extensions.

If I create a new thread, that uses the Dispatch method from win32com,
what happens to the memory allocated in that thread when the thread is
done. Will the Dispatch release the memory it created, or will the
memory remain?

The problem rises from the fact that Dispatch does not seem to release
memory correctly every time. If I include the commands in a thread by
themselves, will the thread clean up ALL memory it used after it is
done?

I did try the pythoncom.CoUnitialize() to release memory, but it
doesn't seem to work (it does work about 30-45 seconds after the
command is run).

Any input is greatly appreciated (on the thread issue or how to use
the pythoncom.CoUnitiliaze() to make it release memory right away).

Thank you in advance!

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


Re: Reading a portion of a file

2007-03-08 Thread Jordan
On Mar 8, 12:46 pm, "Jordan" <[EMAIL PROTECTED]> wrote:
> On Mar 8, 11:52 am, "Rune Strand" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 8, 5:12 pm, [EMAIL PROTECTED] wrote:
>
> > > I am using a script with a single file containing all data in multiple
> > > sections. Each section begins with "#VS:CMD:command:START" and ends
> > > with "#VS:CMD:command:STOP". There is a blank line in between each
> > > section. I'm looking for the best way to grab one section at a time.
> > > Will I have to read the entire file to a string and parse it further
> > > or is it possible to grab the section directly when doing a read? I'm
> > > guessing regex is the best possible way. Any help is greatly
> > > appreciated.
>
> > Seems like something along these line will do:
>
> > _file_ = "filepart.txt"
>
> > begin_tag = '#VS:CMD:command:START'
> > end_tag = '#VS:CMD:command:STOP'
>
> > sections = []
> > new_section = []
> > for line in open(_file_):
> > line = line.strip()
> > if begin_tag in line:
> > new_section = []
> > elif end_tag in line:
> > sections.append(new_section)
> > else:
> > if line: new_section.append(line)
>
> > for s in sections: print s
>
> > If your want more control, perhaps flagging "inside_section",
> > "outside_section" is an idea.
>
> You probably don't want to use regex for something this simple; it's
> likely to make things even more complicated.  Is there a space between
> the begin_tag and the first word of a section (same question with the
> end_tag)?

Sent the post too soon.  What is the endline character for the file
type?  What type of file is it?An example section would be nice
too.  Cheers.

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


Re: tkinter text editor

2007-03-08 Thread jim-on-linux
On Friday 09 March 2007 12:04, Gigs_ wrote:
> Gigs_ wrote:
> > I'm writing text editor.
> >
> > How to enable/disable (cut, copy etc.) when
> > text is selected/not selected
>
> Btw it is cut copy ... in edit menu


state = 'diabled'   ## no change allowed
   ## to Text Wiget  

state = 'normal'  ## default for Text Wiget

jim-on-linux
http:\\www.inqvista.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-08 Thread Matthias Julius
"John" <[EMAIL PROTECTED]> writes:

> I am coding a radix sort in python and I think that Python's dictionary may 
> be a choice for bucket.
>
> The only problem is that dictionary is a mapping without order. But I just 
> found that if the keys are numeric, the keys themselves are ordered in the 
> dictionary.
>
> part of my code is like this:
> radix={}
> for i in range(256):
> radix[i]=[]

I wonder why nobody has suggested the use of a list:

redix = [[] for i in range(256)]

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


Re: merits of Lisp vs Python

2007-03-08 Thread Chris Mellon
On 3/8/07, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Thu, 08 Mar 2007 06:13:15 GMT, John Nagle <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> >
> > When starting out with this project, I'd made the assumption that
> > Python was a stable, working, well-supported technology, like Perl
> > hosting.  It isn't.
> >
> It is interesting how your text seems to blame "Python" (the
> language) when comparing not to "Perl" (the language) but to a service
> field of "Perl hosting".
>
> At the least, be fair and use the phrase "Python hosting" in any
> place you'd have used "Perl hosting"...
>
>
> (I note in passing you did have a comment about Python, the language,
> being good... but anyone reading quickly would tend to interpret, say
> the part quoted above, as "Python is unstable, doesn't work, and
> unsupported" -- none of which, in my experience, is true... Low-cost web
> hosting with Python is a different kettle of fish [chowder, probably
> ])
>

Mr. Nagle has a history of phrasing his personal problems as if they
were vast, sweeping, general issues affecting the entire industry. The
original post, and several followups, referred to *real* hosting
provides, with the emphasis, and in the context of "industrial
strength". Any *real* hosting provider is going to support whatever
language and environment I tell them to, because I'm going to pay them
a lot of money for excellent support and if they give me any trouble I
will go with someone who provides what I want.


What was *meant* was low priced, zero maintenance, reasonably reliable
consumer level hosting. Thats a totally different market, it's not
"industrial strength", and it doesn't merit the emphasis on *real*
provider. And it is true that in that realm Python is not well
represented.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a portion of a file

2007-03-08 Thread cmfvulcanius
On Mar 8, 12:50 pm, "Jordan" <[EMAIL PROTECTED]> wrote:
> On Mar 8, 12:46 pm, "Jordan" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 8, 11:52 am, "Rune Strand" <[EMAIL PROTECTED]> wrote:
>
> > > On Mar 8, 5:12 pm, [EMAIL PROTECTED] wrote:
>
> > > > I am using a script with a single file containing all data in multiple
> > > > sections. Each section begins with "#VS:CMD:command:START" and ends
> > > > with "#VS:CMD:command:STOP". There is a blank line in between each
> > > > section. I'm looking for the best way to grab one section at a time.
> > > > Will I have to read the entire file to a string and parse it further
> > > > or is it possible to grab the section directly when doing a read? I'm
> > > > guessing regex is the best possible way. Any help is greatly
> > > > appreciated.
>
> > > Seems like something along these line will do:
>
> > > _file_ = "filepart.txt"
>
> > > begin_tag = '#VS:CMD:command:START'
> > > end_tag = '#VS:CMD:command:STOP'
>
> > > sections = []
> > > new_section = []
> > > for line in open(_file_):
> > > line = line.strip()
> > > if begin_tag in line:
> > > new_section = []
> > > elif end_tag in line:
> > > sections.append(new_section)
> > > else:
> > > if line: new_section.append(line)
>
> > > for s in sections: print s
>
> > > If your want more control, perhaps flagging "inside_section",
> > > "outside_section" is an idea.
>
> > You probably don't want to use regex for something this simple; it's
> > likely to make things even more complicated.  Is there a space between
> > the begin_tag and the first word of a section (same question with the
> > end_tag)?
>
> Sent the post too soon.  What is the endline character for the file
> type?  What type of file is it?An example section would be nice
> too.  Cheers.

Ok, regex was my first thought because I used to use grep with Perl
and shell scripting to grab everything from one pattern to another
pattern. The file is just an unformatted file. What is below is
exactly what is in the file. There are no spaces between the beginning
and ending tags and the content. Would you recommend using spaces
there? And if so, why?

A sample of the file:

#VS:COMMAND:df:START
Filesystem   1K-blocks  Used Available Use% Mounted on
/dev/vzfs 20971520517652  20453868   3% /
tmpfs  201603244   2015988   1% /var/run
tmpfs  2016032 0   2016032   0% /var/lock
tmpfs  2016032 0   2016032   0% /dev/shm
tmpfs  201603244   2015988   1% /var/run
tmpfs  2016032 0   2016032   0% /var/lock
#VS:COMMAND:df:STOP

#VS:FILE:/proc/loadavg:START
0.00 0.00 0.00 1/32 14543
#VS:FILE:/proc/loadavg:STOP

#VS:FILE:/proc/meminfo:START
MemTotal:   524288 kB
MemFree:450448 kB
Buffers: 0 kB
Cached:  0 kB
SwapCached:  0 kB
Active:  0 kB
Inactive:0 kB
HighTotal:   0 kB
HighFree:0 kB
LowTotal:   524288 kB
LowFree:450448 kB
SwapTotal:   0 kB
SwapFree:0 kB
Dirty:   0 kB
Writeback:   0 kB
Mapped:  73840 kB
Slab:0 kB
CommitLimit: 0 kB
Committed_AS:   248704 kB
PageTables:  0 kB
VmallocTotal:0 kB
VmallocUsed: 0 kB
VmallocChunk:0 kB
#VS:FILE:/proc/meminfo:STOP

#VS:FILE:/proc/stat:START
cpu  67188 0 26366 391669264 656686 0 0
cpu0 24700 0 10830 195807826 373309 0 0
cpu1 42488 0 15536 195861438 283376 0 0
intr 0
swap 0 0
ctxt 18105366807
btime 1171391058
processes 26501285
procs_running 1
procs_blocked 0
#VS:FILE:/proc/stat:STOP

#VS:FILE:/proc/uptime:START
1962358.88 1577059.05
#VS:FILE:/proc/uptime:STOP

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


Re: merits of Lisp vs Python

2007-03-08 Thread Paul Rubin
"Chris Mellon" <[EMAIL PROTECTED]> writes:
> Any *real* hosting provider is going to support whatever
> language and environment I tell them to, because I'm going to pay them
> a lot of money for excellent support and if they give me any trouble I
> will go with someone who provides what I want.

Hosting providers are generally not in the business of doing anything
like that, except the low end ones that mostly support PHP.  

> What was *meant* was low priced, zero maintenance, reasonably reliable
> consumer level hosting. Thats a totally different market, it's not
> "industrial strength", and it doesn't merit the emphasis on *real*
> provider. And it is true that in that realm Python is not well
> represented.

Python is not so well represented in "industrial strength" hosting
either; that kind of hosting generally leaves language support up to
the customer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Where to "import"?

2007-03-08 Thread Paulo da Silva
Hi!

If I have two files .py such as

m.py
from c import *
...
x=c()
...
os.any_method ...
...

c.py
class c:
def __init__(self, ...):
...
os.any_method ...
...
...

both using os module where should I put the "import os"? In both files?

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


Re: Where to "import"?

2007-03-08 Thread Terry Reedy

"Paulo da Silva" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi!
|
| If I have two files .py such as
|
| m.py
| from c import *
| ...
| x=c()
| ...
| os.any_method ...
| ...
|
| c.py
| class c:
| def __init__(self, ...):
| ...
| os.any_method ...
| ...
| ...
|
| both using os module where should I put the "import os"? In both files?

I would even though having it in m.py is not *currently* necessary.  Having 
the import of os into m.py depend on the way you write and import c.py 
looks fragile, and it certainly is a memory burden to remember that c does 
so.  Also, I probably would use 'import c' instead.

tjr



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


Re: tkinter text editor

2007-03-08 Thread Gigs_
jim-on-linux wrote:
> On Friday 09 March 2007 12:04, Gigs_ wrote:
>> Gigs_ wrote:
>>> I'm writing text editor.
>>>
>>> How to enable/disable (cut, copy etc.) when
>>> text is selected/not selected
>> Btw it is cut copy ... in edit menu
> 
> 
> state = 'diabled'   ## no change allowed
>## to Text Wiget  
> 
> state = 'normal'  ## default for Text Wiget
> 
> jim-on-linux
> http:\\www.inqvista.com
yes man but i want to make that when there is no selected text this menu 
items go DISABLED and when text is selected this menu items go NORMAL
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing dictionary to file

2007-03-08 Thread kavitha thankaian
Hi Simon,
   
  iam till here:
   
  dorc=some['DorC']
  amount=some['amount']
  f=open("logfile.txt", "w")
  if dorc =='C':
   a = -(amount)
if dorc == 'D':
   b = amount
   sum=a + b
   if sum == 0:
   f.writelines("name:")
   f.writelines("%s" %some['name'])
   f.writelines("credit:")
   f.writelines("%s" % amount)
   
  but i see an empty file opened,,,
   
  kavitha
   
  Simon Brunning <[EMAIL PROTECTED]> wrote:
  On 3/8/07, kavitha thankaian wrote:
> can anyone help me???

I'm sure we can. How far have you got so far?

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning
MSN: small_values



-
 Here’s a new way to find what you're looking for - Yahoo! Answers -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Tell me the truth

2007-03-08 Thread francois . petitjean
Duncan Booth wrote :
> francois.petitjean at bureauveritas.com wrote:

>> After much head scrating and experimenting with dis.dis() I have found
>> that chaining comparisons (with is or ==)  a == b == c in Python is
>> never a good idea. It is interpreted as
>>  ( a == b ) and ( b == c)
>> Such a magic is fine  when we write:
>>  if  0.0 <= x < 1.0:
>> but it renders the outcome of  if a == b == c: somewhat confusing.

> I don't understand why it is confusing. What other meaning would you
> expect?
Consider:
>>> Python = cool = True
>>> Python is cool
True
>>> Python is cool is True
True
# heh  it seems possible to tackle is True to a boolean expression (not
always)
>>> it = False
>>> Python is cool is not it
True
# I knew that. slef evident...
>>> Python = cool = False
>>> Python is cool is not it
False
# Waht? desillution...
# Ough! You must reread the reference documentation on chaining the
comparison operators and understand the semantics (the two comparisons are
'anded' and 'and' shortcircuits in Python).
>>> Python is cool
True
# Yeah!

Regards


   NOTICE: This message contains information which is confidential and the
   copyright of our company or a third  party. If you are not the intended
   recipient of this message please delete it and destroy all copies. If
   you
   are the intended recipient of this message you should not disclose or
   distribute this message to third parties without the consent of our
   company. Our company does not represent, warrant and/or guarantee that
   the integrity of this message has been maintained nor that the
   communication is free of virus, interception or interference. The
   liability of our company is limited by our General Conditions of
   Services.
   Nota : Ce message contient des informations confidentielles propriété de
   notre société et/ou d'un tiers. Si vous n'êtes pas parmi les
   destinataires désignés de ce message, merci de l'effacer ainsi que
   toutes ses copies. Si vous êtes parmi les destinataires désignés de ce
   message, prière de ne pas le divulguer ni de le transmettre à des tiers
   sans l'accord de notre société. Notre société ne peut garantir que
   l'intégrité de ce message a été préservée ni que la présente
   communication est sans virus, interception ou interférence. La
   responsabilité de notre société est limitée par nos Conditions Générales
   de Services.


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


Re: Where to "import"?

2007-03-08 Thread Bruno Desthuilliers
Paulo da Silva a écrit :
> Hi!
> 
> If I have two files .py such as
> 
> m.py
>   from c import *

avoid this kind of import except in an interactive interpreter and 
eventually in a package __init__.py. Better to use either:

   from c import c
or
   import c
   ...
   x = c.c()

>   ...
>   x=c()
>   ...
>   os.any_method ...

Then you need to import os

>   ...
> 
> c.py
>   class c:
 class C(object):

1/ better to stick to naming conventions (class names in CamelCase)
2/ do yourself a favor: use new-style classes

>   def __init__(self, ...):
>   ...
>   os.any_method ...
>   ...
>   ...
> 
> both using os module where should I put the "import os"? In both files?

Yes. In your above example, it worked because of the "from c import *" - 
and this is exactly why it's bad form to use this in a module (well: 
that's one of the reasons why). Each module should *explicitly* import 
all it's direct dependencies.

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


Re: Squisher -- a lightweight, self-contained alternative to eggs?

2007-03-08 Thread Bruno Desthuilliers
Adam Atlas a écrit :
> Doesn't seem to work. I guess zipimport doesn't support that by
> default... but if I remember correctly, Setuptools adds that. Maybe
> I'll take a look at how it does it (I think by extracting the .so to /
> tmp?) 

or to another known location, IIRC.

> and see how easy it would be to integrate it here.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to "import"?

2007-03-08 Thread Matimus
> both using os module where should I put the "import os"? In both files?

You don't really have a choice, you have to import os in both files.
Python will only load the os module into memory once, but the import
statements are needed to add the os module to the c and m module
namespaces. The code in c.py cannot 'see' the code in m.py, even if it
was imported by m.py. The import command is not like #include in C, it
is not a code dump.

-m

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


Re: tkinter text editor

2007-03-08 Thread James Stroud
Gigs_ wrote:
> jim-on-linux wrote:
> 
>> On Friday 09 March 2007 12:04, Gigs_ wrote:
>>
>>> Gigs_ wrote:
>>>
 I'm writing text editor.

 How to enable/disable (cut, copy etc.) when
 text is selected/not selected
>>>
>>> Btw it is cut copy ... in edit menu
>>
>>
>>
>> state = 'diabled'   ## no change allowed
>>## to Text Wiget 
>> state = 'normal'  ## default for Text Wiget
>>
>> jim-on-linux
>> http:\\www.inqvista.com
> 
> yes man but i want to make that when there is no selected text this menu 
> items go DISABLED and when text is selected this menu items go NORMAL

You have to methodically determine on an event by event basis what is 
going to cause selection and what isn't, then update the menus 
accordingly. It takes a lot of testing. An alternative is polling 
whether text is selected at the moment but is a waste of CPU cycles and 
is unnecessary.

Best is to let the system clipboard handle copy-paste as it was designed 
to do. You are opening a can of worms trying to micromanage your 
application.

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


Re: tkinter how to write

2007-03-08 Thread James Stroud
Gigs_ wrote:
> as I write my first gui program (text editor) I wanna ask you guys how 
> to separate code in classes.?
> Should I put in one class my menu and in another class text and 
> scorllbars etc?
> 
> or something else?
> 
> 
> thanks

Check out Grayson: http://www.manning.com/grayson/

Its $25 for the pdf and is worth about 20 or 30 times that in the effort 
it will take you if you attempt to re-invent the wheel.

For an example of a Tkinter code disaster from not having a good 
reference, glimpse at the source of .

How I wish I'd just read the damn book first!

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


Dyanmic import of a class

2007-03-08 Thread rh0dium
Hi all,

I have a directory with a bunch of python classes each uniquely named
such that the file name (dropping .py) is also the class name of the
file in question.  So for example

foo.py

class foo:
   def __init__(self):
  print "Hi I am %s" % self.__class__.__name__


Now I have a bunch of these files.  I want to be able to dynamically
import each one and run it.  I am having a problem actually doing the
work.   I thought __import__ would work but I can't seem to get it to
work.

for mod in listdir():
   __import__(mod)
   a=mod()
   a.dosomething()  # This is a function which each class shares.

Can anyone help?

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


SQLAlchemy and Oracle Functions?

2007-03-08 Thread Greg Copeland
I have  a need to call an Oracle function, which is not the same thing
as a stored procedure.  Can SQLAlchemy do this directly?  Indirectly?
If so, an example would be appreciated.  If not, how do I obtain the
raw cx_Oracle cursor so I can use that directly?

Thanks,

Greg

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


What is the best way to upgrade python?

2007-03-08 Thread [EMAIL PROTECTED]
Hi,

i am using red hat enterprise 4. It has python 2.3 installed. What is
the best way to upgrade to python 2.4?

I think one way is to compile python 2.4 from the source, but I can't
remove the old one since when i do 'rpm -e python', i get error like
'failed dependencies'.

Thank you for any idea.

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


Re: pylint: don't warn about tabs

2007-03-08 Thread Ben Finney
Bjoern Schliessmann <[EMAIL PROTECTED]> writes:

> Alan Isaac wrote:
> > As a tab user, I want the tabs warning turned off.
>
> Advice: Don't.

Agreed. Sticking to spaces for indentation avoids the ambiguity of
interpretation that ASCII TAB characters are subject to. In addition,
PEP 8 (which many people consider a strong suggestion for a style
guide for all Python code) recommends four space characters for
indentation.

> IIRC it's planned in future Python versions that TABs aren't
> supported for indentation.

I've not seen such plans, can you support that?

If you're thinking of this post from Guido, please note the date it
was made:

http://www.artima.com/weblogs/viewpost.jsp?thread=101968>

-- 
 \   "Dvorak users of the world flgkd!"  -- Kirsten Chevalier, |
  `\rec.humor.oracle.d |
_o__)  |
Ben Finney

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


Re: worker thread catching exceptions and putting them in queue

2007-03-08 Thread Gabriel Genellina
En Thu, 08 Mar 2007 13:31:14 -0300, Aahz <[EMAIL PROTECTED]> escribió:

> In article <[EMAIL PROTECTED]>,
> Paul Sijben  <[EMAIL PROTECTED]> wrote:
>>
>> in a worker thread setup that communicates via queues is it possible to
>> catch exceptions raised by the worker executed, put them in an object
>> and send them over the queue to another thread where the exception is
>> raised in that scope?
>
> One caution: because exceptions keep stack frames alive, you can have
> garbage collection problems.  Make sure to del the exception when you're
> done with it.

Note that it's the traceback who keeps stack frames alive, not the  
exception itself (at least on the current Python versions, might change in  
the future). If no fancy processing of the traceback is needed, maybe  
converting it to string (using the traceback module) before posting it to  
the queue is enough.

-- 
Gabriel Genellina

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


Re: Where to "import"?

2007-03-08 Thread Ben Finney
Paulo da Silva <[EMAIL PROTECTED]> writes:

> Hi!
>
> If I have two files .py such as
>
> m.py
>   from c import *

Best done as either

import c# then use 'x = c.c()'

or

from c import c

Using 'from foo import *' leads to names appearing in your current
namespace that are difficult to track to their origin by reading the
source code.

> both using os module where should I put the "import os"? In both
> files?

Yes. "import os" does two things of note:

  - iff the module is not currently loaded and executed, do so
  - bind the module object to the name "os" in the current namespace

The first step means that you're not losing anything by importing the
module wherever it's needed. The second means the module is available
for use within the current namespace.

-- 
 \  "When cryptography is outlawed, bayl bhgynjf jvyy unir |
  `\   cevinpl."  -- Anonymous |
_o__)  |
Ben Finney

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


SQLAlchemy and Oracle Functions?

2007-03-08 Thread Greg Copeland
I'm using SQLAlchemy and have a need to call an Oracle function; which
is not the same as a stored procedure.  Can this be done directory or
indirectly with SQLAlchemy?  If so, can someone please provide an
example?  If not, how do I obtain the raw cx_Oracle cursor so I can
use callfunc directly on that?

Thanks,

Greg

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


Re: SQLAlchemy and Oracle Functions?

2007-03-08 Thread Sick Monkey

Helpful Links
   http://sourceforge.net/projects/cx-oracle

   http://www.python.net/crew/atuining/cx_Oracle/html/cursorobj.html

==
Example:
Replace the data types as appropriate.

v_Vars = v_Cursor.setinputsizes(p_Result = cx_Oracle.NUMBER)
v_Cursor.execute("""
   begin
 :p_Result := sch.pkg.myfunction(:p_Param1, :p_Param2, :p_Param3);
   end;""",
   p_Param1 = 1,
   p_Param2 = "Some string",
   p_Param3 = "A different string")
print "Result:", v_Vars["p_Result"].getvalue()



On 8 Mar 2007 13:11:00 -0800, Greg Copeland <[EMAIL PROTECTED]> wrote:


I have  a need to call an Oracle function, which is not the same thing
as a stored procedure.  Can SQLAlchemy do this directly?  Indirectly?
If so, an example would be appreciated.  If not, how do I obtain the
raw cx_Oracle cursor so I can use that directly?

Thanks,

Greg

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

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

Re: pylint: don't warn about tabs

2007-03-08 Thread Robert Kern
Alan Isaac wrote:
> I am brand new to pylint.
> As a tab user, I want the tabs warning turned off.
> How?
> 
> Larger question:
> where is the config file format documented?

doc/features.txt
examples/pylintrc

-- 
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: multithreading concept

2007-03-08 Thread Paul Rubin
"Paul Boddie" <[EMAIL PROTECTED]> writes:
> What makes all of the following not "Pythonic"...?
> http://wiki.python.org/moin/ParallelProcessing

I'd say mainly that they don't allow sharing data between processes
except through expensive IPC mechanisms involving system calls.

> I'm sure one could define "Pythonic" as being "you can write
> code like you do now (but not like any of the ways encouraged by the
> aforementioned solutions) and it just works over multiple processors/
> cores", but that's a view which is somewhat detached from the
> practicalities (and favoured practices) of concurrent programming,
> especially given the few guarantees Python would be able to provide to
> make such a thing work effectively.

Really, the existence of the GIL comes as an unpleasant surprise to
progrmamers used to multi-threaded programming in other languages
whose synchronization features outwardly look about the same as
Python's.  Somehow those other languages manage to use multiple CPU's
based on those features, without needing a GIL.  We are looking at a
Python implementation wart, not "practicalities" inherent in the
nature of concurrency.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-08 Thread Ant
On Mar 8, 8:20 am, Steven D'Aprano <[EMAIL PROTECTED]>
wrote:
...
> And the problem with a dictionary is that some people want to make sense
> of its order, just like in this case, and the fifty thousand previous
> times people have asked this newsgroup how they can sort a dictionary.
...
> What makes you think they won't do the same with sets?
...
> (1) Don't assume unordered data structures like sets and dicts are
> ordered, even if they look like it. They aren't.
>
> (2) If you want the keys of a dict sorted, get the keys, and sort them
> when and as you need them.

All good points. Is this misconception really as common as you suggest
(obviously there aren't really going to be 50,000 previous threads of
this nature - but you know what I mean). Because if they are, it is
perhaps a case for adding optimized sorted_dict and sorted_set to the
collections module, similar to the TreeSet and TreeMap classes in
Java.

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


Re: implementing SFTP using Python

2007-03-08 Thread Ravi Terala
Kiran,

You should look into Twisted Python and their Twisted Python Conch 
package. You might not need to reinvent the wheel.
http://twistedmatrix.com/trac/wiki/TwistedConch

Ravi

kadarla kiran kumar wrote:
> Hi Everybody,
>  
> I have to implement SFTP conection from client to the server using 
> Python script.
> Iam very new new to python , and i dont't have much time to complete 
> this. So I need some pointers from you.
>  
> If anybody has already done this kind of stuff, please let me know. 
> Please don't think Iam over ambitious, but i need some kind of Pseudo 
> code ,if possible source code.
>  
> Thanks in Advance,
> K.Kiran Kumar
> 
> 
> Never Miss an Email
> Stay connected with Yahoo! Mail on your mobile. Get started! 
> 
>  
> 
> 

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


  1   2   >