Re: annoying stdin/stdout + pipes problem

2007-09-24 Thread per9000
On 23 Sep, 18:24, Damjan <[EMAIL PROTECTED]> wrote:
> > I want to create a program that reads input from stdio that can prompt
> > a user for input while doing so without getting into problems.
> ...
>
> The trick (which works on Linux for sure) is to open /dev/tty and ask
> question/get input on/from it.
> ...
>
> I'm not usre for other *nix-es, and on Windows this will surelly not work
> --
> damjan

Thanks,

it worked just fine on my Gnu/Linux machine, but I'd really like it to
be independent of OS. Any one else got some idea - or a windows
version of the same?

/Per

--

PS: for the record:
***>cat replace3.py && echo "---" && cat input.txt | python
replace3.py

from sys import stdin, stdout

def censor(foo, bar, input):
return input.replace(foo, bar)

fp = open('/dev/tty', 'r+')
fp.write('Remove what? ')
i = fp.readline().strip()
fp.write('Replace %s with what? ' %i)
o = fp.readline().strip()
fp.close()

for line in stdin.xreadlines():
line = censor('foo', 'candy', line)
line = censor('bar', 'donkey', line)
line = censor('baz', 'hare rama', line)
line = censor(i, o, line)
stdout.write(line)
---
Remove what? black
Replace black with what? beige
candy donkey hare rama
fudonkey donkeyooba xyxxyt
raboof txet
beige knight


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


Re: strange behavious of the logging module?

2007-09-24 Thread Peter Otten
Christian Meesters wrote:

> Also, adding %(funcName)-8s to the formatter in basigConfig does not work
> for me: instead of the functions name the level in lower case gets inserted
> into the logfile.

When you call logging.info(...), "info" actually is the function name. As a
workaround use logging.getLogger(...).info(...).

It would still be a good idea to file a bug report.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Marc 'BlackJack' Rintsch
On Sun, 23 Sep 2007 18:32:28 -0700, Kay Schluehr wrote:

> On 22 Sep., 02:14, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
>> Kay Schluehr a crit :
>> (snip)
>>
>> > I checked out Io once and I disliked it. I expected Io's prototype OO
>> > being just a more flexible variant of class based OO but Io couples a
>> > prototype very closely to its offspring. When A produces B and A.f is
>> > modified after production of B also B.f is modified. A controls the
>> > state of B during the whole lifetime of B. I think parents shall not
>> > do this, not in real life and also not in programming language
>> > semantics.
>>
>> I may totally miss the point, but how is this different from:
>>
>> class A(object):
>>  def dothis(self):
>>  print "A.dothis(%s)" % self
>>
>> class B(A):
>>  pass
>>
>> b = B()
>>
>> b.dothis()
>>
>> def dothat(self):
>>  print "function dothat(%s)" % self
>>
>> A.dothis = dothat
>> b.dothis()
> 
> It's not a big deal because you do not use a class to propagate
> mutable state unless you are using a class attribute intentionally ( i
> guess you do not overuse it just to avoid object encapsulation and
> make everything global ). When using a prototype as in Io you need to
> protect the state of the child object yourself.

Just like in Python!  Here `things` are shared between all "children":

class A(object):
things = list()

def add(self, thing):
self.things.append(thing)

This is what happens too when you use this Io snippet:

A := Object clone do(
things := list()

add := method(thing,
self things append(thing)
)
)

If you don't want `things` to be shared you write an `init` method, in
both Python and Io.  Python:

class B(object):
def __init__(self):
self.things = list()

def add(self, thing):
self.things.append(thing)

And Io:

B := Object clone do(
init := method(
self things := list()
self
)

add := method(thing,
self things append(thing)
)
)

The `init` is called by the default `clone` method automatically just like
`__init__()` in Python.  It is really much like the class/instance
relationship in Python with just the line between class and instance
blurred.

> You can do this by overwriting the objects slots but then you end up
> writing your own object constructors and the templates accordingly, also
> named "classes" by some. Not having dedicated object constructors,
> member variable initializations and the presumed class definition
> boilerplate comes at the price of introducing them on your own.

The mechanism is already there in Io, no need to invent, just use it.

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


Re: scope, modyfing outside object from inside the method

2007-09-24 Thread Peter Otten
Marcin Stępnicki wrote:

> Hello.
> 
> I thought I understand this, but apparently I don't :(. I'm missing
> something very basic and fundamental here, so redirecting me to the
> related documentation is welcomed as well as providing working code :).
> 
> Trivial example which works as expected:
> 
 x = {'a':123, 'b': 456}
 y = x 
 x['a']=890
 y
> {'a': 890, 'b': 456}
> 
> Now, let's try something more sophisticated (it's not real world example,
> I've made up the problem which I think illustrates my issue). Let's say
> I've got such a structure:
> 
> results = [ {'a': 12, 'b': 30 },
> {'a': 13, 'b': 40 } ]
> 
> I'd like to have each row and column in separate object of self-made
> classes.:
> 
> class mycolumn():
>   def __init__(self, resultset, row, col):
>   self.value = resultset[row][col]
>   def __str__(self):
>   return 'Column value: %s' % self.value
> 
> class myrow():
>   def __init__(self):
>   self.container = {}
>   def __str__ (self):
>   return self.container
> 
> results = [
>   {'a': 12, 'b' :30 },
> {'a': 13, 'b' :40 } 
> ]
> 
> mystruct = []
> 
> for row in results:
>   mystruct.append ( myrow() )
>   for col in row:
>   mystruct [len(mystruct)-1].container[col] = \
>mycolumn(results, results.index(row), col)
> 
> print mystruct[0].container['b'] # 12
> results[0]['b'] = 50 # 
> print mystruct[0].container['b'] # also 12 :/
> 
> In other words, I'd like to "map" the results to myrow and mycolumn
> objects, and have these new objects' values changed when I change "results".

Instead of copying a value, you can tell your objects where to look it up.
Your mycolumn class would then become

class MyColumn(object):
def __init__(self, resultset, row, col):
self._resultset = resultset
self._row = row
self._col = col
@property
def value(self):
return self._resultset[self._row][self._col]
def __str__(self):
return 'Column value: %s' % self.value

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

Re: Google and Python

2007-09-24 Thread Bryan Olson
Alex Martelli wrote:
> Bryan Olson wrote:
[...]
>> How does Google use Python? As their scripting-language
>> of choice. A fine choice, but just a tiny little piece.
>>
>> Maybe Alex will disagree with me. In my short time at
>> Google, I was uber-nobody.
> 
> YouTube (one of Google's most valuable properties) is essentially
> all-Python (except for open-source infrastructure components such as
> lighttpd).  Also, at Google I'm specifically "Uber Tech Lead, Production
> Systems": while I can't discuss details, my main responsibilities relate
> to various software projects that are part of our "deep infrastructure",
> and our general philosophy there is "Python where we can, C++ where we
> must". 

Good motto. So is most of Google's code base now in
Python? About what is the ratio of Python code to C++
code? Of course lines of code is kine of a bogus measure.
Of all those cycles Google executes, about what portion
are executed by a Python interpreter?

> Python is definitely not "just a tiny little piece" nor (by a
> long shot) used only for "scripting" tasks; 

Ah, sorry. I meant the choice of scripting language was
a tiny little piece of Google's method of operation.
"Scripting language" means languages such as Python,
Perl, and Ruby.


> if the mutant space-eating
> nanovirus should instantly stop the execution of all Python code, the
> powerful infrastructure that has been often described as "Google's
> secret weapon" would seize up.

And the essence of the Google way is to employ a lot of
smart programmers to build their own software to run on
Google's infrastructure. Choice of language is triva.

I think both Python Google are great. What I find
ludicrous is the idea that the bits one hears about how
Google builds its software make a case for how others
should build theirs. Google is kind of secretive, and
their ways are very much their own. Google's software
is much more Googley than Pythonic.


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


Re: elementtree question

2007-09-24 Thread Gabriel Genellina
En Sat, 22 Sep 2007 00:19:59 -0300, Mark T <[EMAIL PROTECTED]> escribi�:

> "Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> En Fri, 21 Sep 2007 11:49:53 -0300, Tim Arnold <[EMAIL PROTECTED]>
>> escribi�:
>>
>>> Hi, I'm using elementtree and elementtidy to work with some HTML files.
>>> For
>>> some of these files I need to enclose the body content in a new div  
>>> tag,
>>> like this:
>>> 
>>>   
>>>original contents...
>>>   
>>> 

[wrong code]

> The above wraps the body element, not the contents of the body element.   
> I'm
> no ElementTree expert, but this seems to work:

[better code]

Almost right. clear() removes all attributes too, so if the body element  
had any attribute, it is lost. I would remove children from body at the  
same time they're copied into newdiv.
(This whole thing appears to be harder than one would expect at first)

import xml.etree.cElementTree as ET
source = """Test
   original contents... 2&3 some text
   Another paragraph
"""
tree = ET.XML(source)
body = tree.find("body")
newdiv = ET.Element('div', {'class':'remapped'})
for e in list(body.getchildren()):
   newdiv.append(e)
   body.remove(e)
newdiv.text, body.text = body.text, ''
newdiv.tail, body.tail = body.tail, ''
body.append(newdiv)
ET.dump(tree)

-- 
Gabriel Genellina

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

the AIM of LIFE

2007-09-24 Thread abdo911

Allow me to share with you here some information about the AIM of
LIFE .
What is your purpose in life? What is the rationale behind our life?
Why do we live in this life? These questions frequently intrigue
people who try to find accurate answers.
People provide different answers to these questions. Some people
believe the purpose of life is to accumulate wealth. But one may
wonder: What is the purpose of life after one has collected colossal
amounts of money? What then? What will the purpose be once money is
gathered? If the purpose of life is to gain money, there will be no
purpose after becoming wealthy. And in fact, here lies the problem of
some disbelievers or misbelievers at some stage of their life, when
collecting money is the target of their life. When they have collected
the money they dreamt of, their life loses its purpose. They suffer
from the panic of nothingness and they live in tension and
restlessness.
Can Wealth Be an Aim?
We often hear of a millionaire committing suicide, sometimes, not the
millionaire himself but his wife, son, or daughter. The question that
poses itself is: Can wealth bring happiness to one's life? In most
cases the answer is NO. Is the purpose of collecting wealth a standing
purpose? As we know, the five-year old child does not look for wealth:
a toy for him is equal to a million dollars. The eighteen-year old
adolescent does not dream of wealth because he is busy with more
important things. The ninety-year old man does not care about money;
he is worried more about his health. This proves that wealth cannot be
a standing purpose in all the stages of the individual's life.
Wealth can do little to bring happiness to a disbeliever, because he/
she is not sure about his fate. A disbeliever does not know the
purpose of life. And if he has a purpose, this purpose is doomed to be
temporary or self destructive.
What is the use of wealth to a disbeliever if he feels scared of the
end and skeptical of everything. A disbeliever may gain a lot of
money, but will surely lose himself.
Worshipping Allah as an Aim
On the contrary, faith in Allah gives the believer the purpose of life
that he needs. In Islam, the purpose of life is to worship Allah. The
term "Worship" covers all acts of obedience to Allah.
The Islamic purpose of life is a standing purpose. The true Muslim
sticks to this purpose throughout all the stages of his life, whether
he is a child, adolescent, adult, or an old man.
Worshipping Allah makes life purposeful and meaningful, especially
within the framework of Islam. According to Islam this worldly life is
just a short stage of our life. Then there is the other life. The
boundary between the first and second life is the death stage, which
is a transitory stage to the second life. The type of life in the
second stage a person deserves depends on his deeds in the first life.
At the end of the death stage comes the day of judgment. On this day,
Allah rewards or punishes people according to their deeds in the first
life.
The First Life as an Examination
So, Islam looks at the first life as an examination of man. The death
stage is similar to a rest period after the test, i. e. after the
first life. The Day of Judgment is similar to the day of announcing
the results of the examinees. The second life is the time when each
examinee enjoys or suffers from the outcome of his behavior during the
test period.
In Islam, the line of life is clear, simple, and logical: the first
life, death, the Day of Judgment, and then the second life. With this
clear line of life, the Muslim has a clear purpose in life. The Muslim
knows he is created by Allah. Muslims know they are going to spend
some years in this first life, during which they have to obey God,
because God will question them and hold them responsible for their
public or private deeds, because Allah knows about all the deeds of
all people. The Muslim knows that his deeds in the first life will
determine the type of second life they will live in. The Muslim knows
that this first life is a very short one, one hundred years, more or
less, whereas the second life is an eternal one.
The Eternity of the Second Life
The concept of the eternity of the second life has a tremendous effect
on a Muslims during their first life, because Muslims believe that
their first life determines the shape of their second life. In
addition, this determines the shape of their second life and this
determination will be through the Judgment of Allah, the All just and
Almighty.
With this belief in the second life and the Day of Judgment, the
Muslim's life becomes purposeful and meaningful. Moreover, the
Muslim's standing purpose is to go to Paradise in the second life.
In other words, the Muslim's permanent purpose is to obey Allah, to
submit to Allah, to carry out His orders, and to keep in continues
contact with Him through prayers (five times a day), through fasting
(one month a year), through charity (as often as possible), and
through pilgrimage (on

Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Bryan Olson
wrote:

> The keyword "lambda" sucks. ...
> 
> Alonzo Church's calculus used the *symbol*.

The keyword was popularized by LISP, and hence adopted by most other
languages to copy the concept.

In my view, it's no worse than using "=" for assignment instead of equality.

> "function" would be a much better keyword.

As used that way in JavaScript.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Cristian
wrote:

> I think it would make more sense to have beginners _know_ that functions
> are like all other variables ...

Functions are not variables. Though they are values, and can be held in
variables.

In Python, every name is a variable, and can be assigned to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Registration for OSDC 2007 is open

2007-09-24 Thread Richard Jones
OSDC 2007 is in Brisbane this year on 27-29 November (with a tutorial day on 
the 26th). $275 early bid registration closes October 14th.

Just follow the instructions at the top of http://osdc.com.au/registration/ to 
1. register and 2. pay. (If you are going to pay by credit card/PayPal you 
should note the OS7x invoice number that the registration process 
allocates you and re-enter that when you pay.)


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


Re: TRying to import files from my folder not pythons lib folder

2007-09-24 Thread Gabriel Genellina
En Sun, 23 Sep 2007 22:01:39 -0300, Luis M. González <[EMAIL PROTECTED]>  
escribi�:

> This is exactly what I did, but I have a new problem now:
> After seting PYTHONPATH I'm no longer able to start IDLE from the
> start menu.
> It seems the system cannot find the file.
> But if I eliminate PYTHONPATH, everything works as it used to.
>
> I set PYTHONPATH because I wanted to import any existing file in my
> desktop without having to use sys.path.append...
> It works when using the command line but strangely, something get
> messed up with IDLE.
> Any hint?

Perhaps a python module in your desktop has a name conflicting with a  
standard module?

- On the Start menu, navigate to the IDLE item, but dont click it.
- RIGHT click on it, and select Properties. Copy the Destination field.  
Should be something like "C:\Python25\Lib\idlelib\idle.bat"
- Open a cmd window (console), paste the above text and press Enter.
- Almost certainly you'll get an error; post here the full error and  
traceback.

-- 
Gabriel Genellina

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

Re: elementtree question

2007-09-24 Thread Stefan Behnel
Tim Arnold wrote:
> Hi, I'm using elementtree and elementtidy to work with some HTML files. For 
> some of these files I need to enclose the body content in a new div tag, 
> like this:
> 
>   
>original contents...
>   
> 

Give lxml.etree (or lxml.html) a try:

tree = etree.parse("http://url.to/some.html";, etree.HTMLParser())
body = tree.find("body")

and then:

div = etree.Element("div", {"class" : "remapped"})
div.extend(body)
body.append(div)

or alternatively:

children = list(body)
div = etree.SubElement(body, "div", {"class" : "remapped"})
div.extend(children)

http://codespeak.net/lxml/

and for lxml.html, which is currently in alpha status:

http://codespeak.net/lxml/dev/

ET 1.3 will also support the extend() function, BTW.

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


Passing parameters at the command line (New Python User)

2007-09-24 Thread cjt22
Hi there. I just wondered whether anyone could recommend the correct
way I should be passing command line parameters into my program. I am
currently using the following code:

def main(argv = None):


file1=  "directory1"
file2 =  "directory2"


if argv is None:
args = sys.argv[1:]

if len(args) == 0:
Initialise.init(0)
Process.processCon(file1, 0)
Output.print()

for i in range(len(args)):
if args[i] == "-no":
Initialise.init(0)
Process.processCon(file2,1)
Output.print()

if args[i] == "-not":
   Initialise.init(1)
Process1.process(stepStore, firstSteps)
Output.print1()



if __name__ == "__main__":
main()


Have I used bad syntax here so that a user can either run the program
with commands:
main.py
main.py -no
main.py -not

If I also wanted an option file to be passed in at the command line
for 'main.py' and 'main.py -no' what would be the best way to go about
this? I have never used Python to pass in arguments at the command
line so any help would be much appreciated.

Cheers
Chris

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, 
[EMAIL PROTECTED] wrote:

> A question: if you WERE to implement function definitions as normal
> expressions, how would you go about embedding it within an expression?
> 
> x = map(def a:
> 
> 
> 
> , [1, 2, 3])

Perl can do it just fine:

$x = map
  (
sub
  {
...
  },
[1, 2, 3]
  );

The fact that Python has difficulties is purely a demonstration of the
limitations of indentation-controlled syntax, not a criticism of the
concept itself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: annoying stdin/stdout + pipes problem

2007-09-24 Thread Gabriel Genellina
En Mon, 24 Sep 2007 04:04:07 -0300, per9000 <[EMAIL PROTECTED]> escribi�:

> On 23 Sep, 18:24, Damjan <[EMAIL PROTECTED]> wrote:
>> > I want to create a program that reads input from stdio that can prompt
>> > a user for input while doing so without getting into problems.
>> ...
>>
>> The trick (which works on Linux for sure) is to open /dev/tty and ask
>> question/get input on/from it.
>
> it worked just fine on my Gnu/Linux machine, but I'd really like it to
> be independent of OS. Any one else got some idea - or a windows
> version of the same?

On Windows it's almost the same, using "conin$" as the filename for  
console input, and "conout$" as the filename for console output.

-- 
Gabriel Genellina

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

Re: Google and Python

2007-09-24 Thread Nick Craig-Wood
Paul Rubin  wrote:
>  David <[EMAIL PROTECTED]> writes:
> > Another method is for the apps to run continuously and serve on non-80
> > port (or on 80 from another host), and your main web server on port 80
> > reverse proxies to it when appropriate.
> 
>  You can also pass the open sockets around between processes instead of
>  reverse proxying, using the SCM_RIGHTS message on Unix domain sockets
>  under Linux, or some similar mechanism under other Unixes (no idea
>  about Windows).  Python does not currently support this but one of
>  these days I want to get around to writing a patch.

An interesting idea!  Are there any web servers which work like that
at the moment?

Passing file descriptors between processes is one of those things I've
always meant to have a go with, but the amount of code (in Advanced
Programming in the Unix Environment) needed to implement it is rather
disconcerting!  A python module to do it would be great!

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


Re: about __str__

2007-09-24 Thread Mikael Olofsson
Bruno Desthuilliers wrote:
> def __str__(self):
> return "<%s:%s>" % (self.commiterID_, self.commits_)

I would write that in the following way:

def __str__(self):
return "<%(commiterID_)s:%(commits_)s>" % self.__dict__

More explicit IMHO. And easier to maintain, especially if the string 
would contain several insertions.

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


Re: Passing parameters at the command line (New Python User)

2007-09-24 Thread Diez B. Roggisch
 [EMAIL PROTECTED] wrote:

> Hi there. I just wondered whether anyone could recommend the correct
> way I should be passing command line parameters into my program. I am
> currently using the following code:



Use the module optparse.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Paul Rubin
Lawrence D'Oliveiro <[EMAIL PROTECTED]> writes:
> The fact that Python has difficulties is purely a demonstration of the
> limitations of indentation-controlled syntax, not a criticism of the
> concept itself.

Not even.  Haskell has indentation syntax (they call it "layout")
but can have multi-line function definitions inside expressions.
-- 
http://mail.python.org/mailman/listinfo/python-list


vim - what's a smarttab?

2007-09-24 Thread 7stud
Is smarttab one of these:

1) Expands tabs into the number of spaces set with tabstop at the
start of a line, and uses a tabstop sized tab elsewhere.

2) Expands tabs into the number of spaces set with shiftwidth at the
start of a line, and expands tabs into the number spaces set with
tabstop elsewhere.

3) Doesn't do any expanding: uses shiftwidth sized tabs at beginning
of line, and tabstop sized tabs elsewhere.

Alternatively, what is a smarttab?

Thanks.

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


Re: Passing parameters at the command line (New Python User)

2007-09-24 Thread Ben Finney
[EMAIL PROTECTED] writes:

> I have never used Python to pass in arguments at the command line so
> any help would be much appreciated.

Your 'main()' approach is good. I'd rather have the function require
an 'argv' parameter, and have the default set only in the 'if __name__
== "__main__":' block, since that fits my ideas better about the
defaults.

def main(argv):
parse_commandline(argv)
do_cool_stuff()

if __name__ == "__main__":
from sys import argv
main(argv)

I also tend to catch SystemExit in the function, so the exit code can
be returned instead of raised; but that's outside the scope of this
thread.

For anything more advanced than unconditionally grabbing arguments in
sequence from the command line, you should investigate the 'optparse'
module http://docs.python.org/lib/module-optparse> from the
standard library.

-- 
 \ "Holy knit one purl two, Batman!"  -- Robin |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing parameters at the command line (New Python User)

2007-09-24 Thread Marc 'BlackJack' Rintsch
On Mon, 24 Sep 2007 01:04:58 -0700, cjt22 wrote:

> for i in range(len(args)):
> if args[i] == "-no":
> Initialise.init(0)
> Process.processCon(file2,1)
> Output.print()
> 
> if args[i] == "-not":
>Initialise.init(1)
> Process1.process(stepStore, firstSteps)
> Output.print1()

That ``for`` loop is an anti-pattern in Python.  If you want to iterate
over the elements of `args` the just do it directly instead of using an
index:

for arg in args:
if arg == '-no':
# ...

If you need the element *and* an index:

for i, arg in enumarate(args):
# ...

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


SOAPpy Error

2007-09-24 Thread linuxprog
hi all

i'm building a webservice client with soappy

when i send some informations it's returns an error
here is the informations that generates the error
var = SOAPpy.structType()
var._addItem("code", u"XysZjd")
var._addItem("value", 1)
when i send the var variable SOAPpy prints this

  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 473, in 
__call__
return self.__r_call(*args, **kw)
  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 495, in 
__r_call
self.__hd, self.__ma)
  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 366, in __call
config = self.config)
  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 228, in call
data = r.getfile().read()
AttributeError: 'NoneType' object has no attribute 'read'

when i have activate debug , the debug mode shows :
code :  -1
msg : 
headers : None

it should prints some thing like this if all goes well :
code :  200
msg :  OK
headers : Date: Mon, 24 Sep 2007 09:08:45 GMT
Server: Apache/2.2.3 (Debian) PHP/5.2.0-8+etch7
X-Powered-By: PHP/5.2.0-8+etch7
Content-Length: 2116
Connection: close
Content-Type: text/xml; charset=utf-8

wha's wrong ?

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Bruno Desthuilliers
Cristian a écrit :
> On Sep 21, 5:21 pm, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
> 
>> Ok, then what about classes ? They also are objects-like-any-other,
>> after all. So should we have this syntax too ?
>>
>> MyClass = class(ParentClass):
>>__init__ = function (self, name):
>>  self.name = name
>>
>> ?-)
> 
> For consistency I would suggest this, but Python already does this!
> 
> Foo = type('Foo', (object, ), {'bar': lambda self, bar: bar})
> 
> I've created a new class and then binded it to name afterwards. If you
> can import modules without special syntax and you can create classes
> without special syntax, why should functions be treated any
> differently?
> 

You already can create functions without using the def statement:

Help on class function in module __builtin__:

class function(object)
  |  function(code, globals[, name[, argdefs[, closure]]])
  |
  |  Create a function object from a code object and a dictionary.
  |  The optional name string overrides the name from the code object.
  |  The optional argdefs tuple specifies the default argument values.
  |  The optional closure tuple supplies the bindings for free variables.
  |


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


IPv6 in python

2007-09-24 Thread Piotr Dula (pdula)
Hello,
 
How to make python support IPv6?
 
I tried to do:
 
./configure --enable-ipv6
make 
make install
 
and I didn't get any error. However, IPv6 doesn't seem to be working
yet.
 
then I tried 
 
./configure --enable-ipv6=yes
 
and I got a lot of parse errors (many pages similar to this below)
 
In file included from /root/Piotr/Python-2.5.1/Modules/_tkinter.c:67:
/usr/include/tk.h:581: parse error before "Bool"
/usr/include/tk.h:583: parse error before "event"
/usr/include/tk.h:584: parse error before "root"
/usr/include/tk.h:585: parse error before "subwindow"
/usr/include/tk.h:586: parse error before "time"
/usr/include/tk.h:586: `time' redeclared as different kind of symbol
/usr/include/time.h:184: previous declaration of `time'
/usr/include/tk.h:591: parse error before "same_screen"
/usr/include/tk.h:597: parse error before "Bool"
/usr/include/tk.h:599: parse error before "window"
/usr/include/tk.h:601: parse error before "XActivateEven
 
How to make it work? 
 
Thank you in advance,
 
Piotr
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: about __str__

2007-09-24 Thread Bruno Desthuilliers
Mikael Olofsson a écrit :
> Bruno Desthuilliers wrote:
>> def __str__(self):
>> return "<%s:%s>" % (self.commiterID_, self.commits_)
> 
> I would write that in the following way:
> 
> def __str__(self):
>return "<%(commiterID_)s:%(commits_)s>" % self.__dict__
> 
> More explicit IMHO. And easier to maintain, especially if the string 
> would contain several insertions.

Agreed. Well, at least until you want to access something that's not in 
the instance's __dict__ !-)

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Marc 'BlackJack' Rintsch
On Mon, 24 Sep 2007 11:43:59 +0200, Bruno Desthuilliers wrote:

> You already can create functions without using the def statement:
> 
> Help on class function in module __builtin__:
> 
> class function(object)
>   |  function(code, globals[, name[, argdefs[, closure]]])
>   |
>   |  Create a function object from a code object and a dictionary.
>   |  The optional name string overrides the name from the code object.
>   |  The optional argdefs tuple specifies the default argument values.
>   |  The optional closure tuple supplies the bindings for free variables.
>   |

Where the heck does *this* come from?  Neither Python 2.5.1 nor the
3.0alpha has this in `__builtin__`.

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


Re: scope, modyfing outside object from inside the method

2007-09-24 Thread Dustan
On Sep 24, 2:13 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> @property
> def value(self):
> return self._resultset[self._row][self._col]

I remember a thread where someone created a version of property that
worked like this, but it's not in the standard python release, unless
it is in python 3000.

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


Re: Properties and Objects...

2007-09-24 Thread Peter Otten
George V. Neville-Neil wrote:

> I have been trying to switch this over to using properties, which seem
> at first glance to be cleaner, but which I am having a lot of problems
> with.  In particular I want to add a property to an object, not a
> class.  

You can't. The underlying mechanism (descriptors) works on the class level.

> The field list in a class is actually relatively static but I
> wind up with ugly code like:
> 
> class ethernet(pcs.Packet):
> """Ethernet"""
> __layout__ = pcs.Layout()
> _map = ethernet_map.map
> 
> src = pcs.StringField("src", 48)
> dst = pcs.StringField("dst", 48)
> type = pcs.Field("type", 16)

>From the piece of code you present I would guess that the above class
attributes are superfluous. Or doesn't pcs.Packet.__init__() do the

self.src = ... 

thingy?

> def __init__(self, bytes = None, timestamp = None):
> """initialize an ethernet packet"""
> 
> src = pcs.StringField("src", 48)
> dst = pcs.StringField("dst", 48)
> type = pcs.Field("type", 16)
> 
> pcs.Packet.__init__(self, [dst, src, type], bytes = bytes)
> self.description = inspect.getdoc(self)
> 
> and assigning the properties at class time means that it's hard to have
> variations, packets with the same name but with slightly varying field
> lists.

What's so hard about subclassing?

> So, is there a way to assign a property to an object, like this:
> 
> def __init__(
>  self.src = property()
> 
> or something like that?

You can make a property that delegates its behaviour, e. g:

import new

def get_src_one(self):
return 42

class A(object):
src = property(lambda self: self.get_src())
def __init__(self, get):
self.get_src = new.instancemethod(get, self)

a = A(get_src_one)
print a.src

But -- ceterum censeo -- subclassing is probably better, cleaner and
faster. Then instead of calling the class directly make a factory function
that picks the appropriate subclass.

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


python variable assignement

2007-09-24 Thread mihai

I work at an application witch has embeded python.

We have an python type X.

# a != b

a = b # at this point both variables have the same value

b = select_other()

# steel the same values but both have the new value of b

What might be the cause for this behavior? The type of a and b
variable is the same,
and is defined using PyTypeObject structure.

I hope I was explicit.

Thank you in advance,
Mihai.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 10:05 +, Marc 'BlackJack' Rintsch wrote:
> On Mon, 24 Sep 2007 11:43:59 +0200, Bruno Desthuilliers wrote:
> 
> > You already can create functions without using the def statement:
> > 
> > Help on class function in module __builtin__:
> > 
> > class function(object)
> >   |  function(code, globals[, name[, argdefs[, closure]]])
> >   |
> >   |  Create a function object from a code object and a dictionary.
> >   |  The optional name string overrides the name from the code object.
> >   |  The optional argdefs tuple specifies the default argument values.
> >   |  The optional closure tuple supplies the bindings for free variables.
> >   |
> 
> Where the heck does *this* come from?  Neither Python 2.5.1 nor the
> 3.0alpha has this in `__builtin__`.

It comes from the 'new' module:

>>> import new
>>> help(new.function)
Help on class function in module __builtin__:
...

Oddly enough, the help misrepresents which module the function is coming
from.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Kay Schluehr
On Sep 24, 9:09 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> Python:
>
> class B(object):
> def __init__(self):
> self.things = list()
>
> def add(self, thing):
> self.things.append(thing)
>
> And Io:
>
> B := Object clone do(
> init := method(
> self things := list()
> self
> )
>
> add := method(thing,
> self things append(thing)
> )
> )
>
> The `init` is called by the default `clone` method automatically just like
> `__init__()` in Python.  It is really much like the class/instance
> relationship in Python with just the line between class and instance
> blurred.

[...]

> Ciao,
> Marc 'BlackJack' Rintsch

O.K. Marc, I'm convinced by the examples you presented. So init is
also special in Io and is called at the clone event to fill object
slots with data.

Now I have to track back in the discussion thread to remember why we
started to talk about Io...

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


Re: python variable assignement

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 10:13 +, mihai wrote:
> I work at an application witch has embeded python.
> 
> We have an python type X.
> 
> # a != b
> 
> a = b # at this point both variables have the same value

Not quite. At this point, 'a' and 'b' are names in the local namespace
that refer to the same object.

> b = select_other()

Now 'b' becomes a reference to the object returned by select_other().
Presumably that's a different object than the one it referred to before.
'a' still refers to the same object it referred to before.

> # steel the same values but both have the new value of b

No, the code you showed us wouldn't behave this way.

> What might be the cause for this behavior?

What behavior?

>  The type of a and b
> variable is the same,
> and is defined using PyTypeObject structure.

That doesn't matter. (Variable) Names don't have types. Objects have
types, and a name can refer to an object of any type. See
http://effbot.org/zone/python-objects.htm .

> I hope I was explicit.

Unfortunately, you weren't. If the above explanations didn't help you,
please explain what you want to achieve, show us your actual code and
what you expect it to do, and tell us what it's doing instead.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


RE: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Delaney, Timothy (Tim)
Carsten Haese wrote:

>> Where the heck does *this* come from?  Neither Python 2.5.1 nor the
>> 3.0alpha has this in `__builtin__`.
> 
> It comes from the 'new' module:
> 
 import new
 help(new.function)
> Help on class function in module __builtin__:
> ...
> 
> Oddly enough, the help misrepresents which module the function is
> coming from.

Not exactly:

>>> help(type(lambda x: x))
Help on class function in module __builtin__:

The function type is builtin, but it doesn't have an exposed name.
`new.function` is simply a name bound to the function type.

Note the help says *class* function ...

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


Re: Properties and Objects...

2007-09-24 Thread George V. Neville-Neil
At Sun, 23 Sep 2007 19:01:04 -0300,
Gabriel Genellina wrote:
> 
> En Sat, 22 Sep 2007 15:06:38 -0300, George V. Neville-Neil  
> <[EMAIL PROTECTED]> escribi�:
> 
> > I have been trying to switch this over to using properties, which seem
> > at first glance to be cleaner, but which I am having a lot of problems
> > with.  In particular I want to add a property to an object, not a
> > class.  The field list in a class is actually relatively static but I
> > wind up with ugly code like:
> >
> > class ethernet(pcs.Packet):
> > """Ethernet"""
> > __layout__ = pcs.Layout()
> > _map = ethernet_map.map
> >src = pcs.StringField("src", 48)
> > dst = pcs.StringField("dst", 48)
> > type = pcs.Field("type", 16)
> >
> > def __init__(self, bytes = None, timestamp = None):
> > """initialize an ethernet packet"""
> >
> > src = pcs.StringField("src", 48)
> > dst = pcs.StringField("dst", 48)
> > type = pcs.Field("type", 16)
> >
> > pcs.Packet.__init__(self, [dst, src, type], bytes = bytes)
> > self.description = inspect.getdoc(self)
> 
> You don't have to repeat the fields:
> 
>   pcs.Packet.__init__(self, [self.dst, self.src, self.type], bytes  
> = bytes)
> 

Actually that calls the __get__ method of the descriptor, which is not
what I want, I need a list of the objects in the layout.

> does the same thing.
> And you can remove self.description=... and use (at the class level):
>   description = __doc__
> or:
>   description = property(lambda self: self.__doc__)
> to automatically enable subclases to share the definition

Ah, that's very cool, thanks.

> One could say that the field order is important so I'd finally write it as:
> 
> class ethernet(pcs.Packet):
>   """Ethernet"""
>   __layout__ = pcs.Layout()
>   _map = ethernet_map.map
>   src = pcs.StringField("src", 48)
>   dst = pcs.StringField("dst", 48)
>   type = pcs.Field("type", 16)
>   _fields = [dst, src, type]
>   description = property(lambda self: self.__doc__)
> 
>   def __init__(self, bytes = None, timestamp = None):
>   """initialize an ethernet packet"""
> 
>   pcs.Packet.__init__(self, self._fields, bytes = bytes)
> 
> > and assigning the properties at class time means that it's hard to
> > have variations, packets with the same name but with slightly varying
> > field lists.
> 
> This is the part I don't understand. Can't you define a new class, in case  
> you want a different field list? Using the above class:
> 
> class ethernet_modified(ethernet):
>  """Modified ethernet class"""
>  added_field = pcs.StringField("whatever", 16)
>  _fields = [dst, src, type, added_field]
> 
> And it doesn't even requiere an __init__ method
> 

Yes, I could and probably should define different objects.

> > So, is there a way to assign a property to an object, like this:
> >
> > def __init__(
> >  self.src = property()
> >
> > or something like that?
> 
> I'd use different classes for different kind of objects.
> 
> > And, failing that, is there a clean way to modify the class in it's
> > __init__() method so I don't have to call the Field objects twice,
> > once for the property effect and once to put into the list in the base
> > Packet class?
> 
> I think my example above does what you want.

Other than the fact that I need the list of Field objects in the
layout, and not the values, yes.  Of course that's the hard part.

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

Re: vim - what's a smarttab?

2007-09-24 Thread Marco
Hi "7stud",

> Alternatively, what is a smarttab?

in VIM type :help smarttab and you'll see the following:

'smarttab' 'sta'boolean (default off)
 global
 {not in Vi}
When on, a  in front of a line inserts blanks according to
'shiftwidth'.  'tabstop' or 'softtabstop' is used in other places.  A
 will delete a 'shiftwidth' worth of space at the start of the
line.
When off, a  always inserts blanks according to 'tabstop' or
'softtabstop'.  'shiftwidth' is only used for shifting text left or
right |shift-left-right|.
What gets inserted (a Tab or spaces) depends on the 'expandtab'
option.  Also see |ins-expandtab|.  When 'expandtab' is not set, the
number of spaces is minimized by using s.
NOTE: This option is reset when 'compatible' is set.

If you'd like to use VIM for Python make sure you have the following 
settings for the best result:
http://www.vex.net/~x/python_and_vim.html

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Duncan Booth
Carsten Haese <[EMAIL PROTECTED]> wrote:

> It comes from the 'new' module:
> 
 import new
 help(new.function)
> Help on class function in module __builtin__:
> ...
> 
> Oddly enough, the help misrepresents which module the function is coming
> from.

No, I don't think it is misrepresenting anything. The 'new' module simply 
exposes names for some things which don't otherwise  have names, none of 
the types accessible through that module are actually defined there.

The class 'function' is a builtin definition, but by default it isn't bound 
to any name accessible to the Python interpreter. If you do:

>>> def f(): pass

>>> type(f).__module__
'__builtin__'
>>> help(type(f))
Help on class function in module __builtin__:
... etc ...

then the help makes a bit more sense.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Bruno Desthuilliers
Steven D'Aprano a écrit :
> On Fri, 21 Sep 2007 22:07:55 +, Cristian wrote:
> 
>> True, there is lambda, but that is very limited. It might be useful for
>> key arguments, but not much else.
> 
> No, lambda is useful for anything that any other function is useful for, 
> provided that you can write it as a single expression and not need to use 
> statements. 

Which makes a great difference in practice !-)
-- 
http://mail.python.org/mailman/listinfo/python-list

sorting a list numbers stored as strings

2007-09-24 Thread aine_canby
hi,

I have the following list -

["1", "11", "2", "22"]

how do I sort it like this -

["1", "2", "11", "22"]

thanks,

aine

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Bruno Desthuilliers
Matthew Woodcraft a écrit :
> Cristian  <[EMAIL PROTECTED]> wrote:
>> To me, the biggest setback for new programmers is the different
>> syntax Python has for creating functions. Instead of the common (and
>> easy to grasp) syntax of foo = bar Python has the def foo(): syntax.
> 
> [...]
> 
>> in a program like Python there doesn't seem to be any other reason to
>> have it.
> 
> One reason for the different syntax is that functions, unlike most
> other objects, know their own names (which can be shown in tracebacks
> and the like).

Nope. They know *one* of their names - the one they've been given when 
first instanciated. Which may or not be the name used to get at them...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting a list numbers stored as strings

2007-09-24 Thread Amit Khemka
On 9/24/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> hi,
>
> I have the following list -
>
> ["1", "11", "2", "22"]
>
> how do I sort it like this -
>
> ["1", "2", "11", "22"]
>

Hi,

>>> l = ["1", "11", "2", "22"]
>>> sorted(l, cmp = lambda x, y: cmp(int(x), int(y)))  # provide your
own compare function !
>>> l
['1', '2', '11', '22']

Cheers,

-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting a list numbers stored as strings

2007-09-24 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> hi,
> 
> I have the following list -
> 
> ["1", "11", "2", "22"]
> 
> how do I sort it like this -
> 
> ["1", "2", "11", "22"]

source = ["1", "11", "2", "22"]
result = [t[1] for t in sorted((int(item), item) for item in source)]
print result

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


Almost There - os.kill()

2007-09-24 Thread Robert Rawlins - Think Blue
Hello Guys,

 

Finally got around to sitting down to tidy up this script this morning but
I'm having a small syntax problem with os.kill() to kill a process on my
system. Here is the code:

 

def killApplication():

 

   pid = file('/var/lock/MyApplication.lock').read().strip()

   

   logging.info('Killing Application Process: %s' % pid)

 

   os.kill(pid, 15)

 

   logging.info('Application %s Killed' % pid)

 

As you can see if rips the PID from the lock file, which works fine as I get
log data which says 'Killing Application Process: 3079' exactly as I would
expect it too. However when I run this script I get the following error:

 

Traceback (most recent call last):

  File "/pblue/new/Alive.py", line 50, in ?

main()

  File "/pblue/new/Alive.py", line 47, in main

doCheck()

  File "/pblue/new/Alive.py", line 43, in doCheck

killApplication()

  File "/pblue/new/Alive.py", line 28, in killApplication

os.kill(pid, 15)

TypeError: an integer is required

 

Which would suggest its passing those arguments in as the wrong data types
to the kill command. What is the best way to convert these?

 

Thanks guys,

 

Rob

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

Re: Database Abstraction Layer And/Or ORM

2007-09-24 Thread Bruno Desthuilliers
BJ Dierkes a écrit :
> Hello all,
> 
> I am looking for opinions on preferred methods of Database Abstraction 
> Layer or Object Relation Mapper (I'm using Python 2.5).   I have found a 
> number of options such as those listed here:
> 
> http://wiki.python.org/moin/HigherLevelDatabaseProgramming
> 
> 
> I'm not looking for a holy war based on whether a DAL/ORM *should* be 
> used, and/or if it is preferred over direct access to the database API 
> layer.  I understand that can be a lengthy discussion.  I would just 
> like to see if there is a common 'preferred choice' in the area.  

Well... Then, it seems like SQLAlchemy is getting most of the buzz 
actually !-)

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


Re: Writing Object Data to Disk

2007-09-24 Thread Bruno Desthuilliers
David a écrit :
>> I would like to know if "Pickling" the class object is the only way of
>> writing it to disk for persistent storage. Also, do we have a concept
>> similar to "array of objects" in Python? The number of objects is only
>> known at "run-time".
> 
> Have a look at YAML.
> 
> http://freshmeat.net/projects/syck/
> 
> Also it is possible to persist python data to and from XML. See
> xml.marshal.generic.dumps

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


rules from an xml file

2007-09-24 Thread jonny
I have a python code that manages some parameters using some variable
rules that may change from day to day. I'd like that the code will
self-modify according to rules parsed from a xml file:

example:


   
  














   Something is wrong!

   
...  
...   


Due to the fact that rules may change, I have to manage the python
program, parsing the whole xml file, and self-modify the python code
according to these variable rules.
How can I do?

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


Re: sorting a list numbers stored as strings

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 16:53 +0530, Amit Khemka wrote:
> On 9/24/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > hi,
> >
> > I have the following list -
> >
> > ["1", "11", "2", "22"]
> >
> > how do I sort it like this -
> >
> > ["1", "2", "11", "22"]
> >
> 
> Hi,
> 
> >>> l = ["1", "11", "2", "22"]
> >>> sorted(l, cmp = lambda x, y: cmp(int(x), int(y)))  # provide your
> own compare function !
> >>> l
> ['1', '2', '11', '22']

That interpreter session is a work of fiction, since sorted returns the
sorted list instead of sorting the list in place. Also, it's better
(i.e. more readable and likely faster) to use a sort key function
instead of a comparison function whenever possible. In this case, the
sort key function is particularly trivial:

>>> l = ["1", "11", "2", "22"]
>>> sorted(l, key=int)
['1', '2', '11', '22']

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


RE: Almost There - os.kill()

2007-09-24 Thread Robert Rawlins - Think Blue
Woops,

 

Spoke too soon, just wrapped them in int() and it works a charm :-D

 

Rob

 

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Robert Rawlins - Think Blue
Sent: 24 September 2007 12:23
To: [email protected]
Subject: Almost There - os.kill()

 

Hello Guys,

 

Finally got around to sitting down to tidy up this script this morning but
I'm having a small syntax problem with os.kill() to kill a process on my
system. Here is the code:

 

def killApplication():

 

   pid = file('/var/lock/MyApplication.lock').read().strip()

   

   logging.info('Killing Application Process: %s' % pid)

 

   os.kill(pid, 15)

 

   logging.info('Application %s Killed' % pid)

 

As you can see if rips the PID from the lock file, which works fine as I get
log data which says 'Killing Application Process: 3079' exactly as I would
expect it too. However when I run this script I get the following error:

 

Traceback (most recent call last):

  File "/pblue/new/Alive.py", line 50, in ?

main()

  File "/pblue/new/Alive.py", line 47, in main

doCheck()

  File "/pblue/new/Alive.py", line 43, in doCheck

killApplication()

  File "/pblue/new/Alive.py", line 28, in killApplication

os.kill(pid, 15)

TypeError: an integer is required

 

Which would suggest its passing those arguments in as the wrong data types
to the kill command. What is the best way to convert these?

 

Thanks guys,

 

Rob

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

Re: Almost There - os.kill()

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 12:23 +0100, Robert Rawlins - Think Blue wrote:
> os.kill(pid, 15)
> 
> TypeError: an integer is required
> 
>  
> 
> Which would suggest its passing those arguments in as the wrong data
> types to the kill command. What is the best way to convert these?

Instead of giving you the fish, I'll give you a fishing rod. Use
inspection, experimentation, and the online documentation to answer the
following questions:

1) What type is the argument currently?
2) What type does the os.kill function expect?
3) How can you convert an object of type 1 to an object of type 2?

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: rules from an xml file

2007-09-24 Thread Diez B. Roggisch
jonny wrote:

> I have a python code that manages some parameters using some variable
> rules that may change from day to day. I'd like that the code will
> self-modify according to rules parsed from a xml file:
> 
> example:
> 
> 
>
>   
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
>Something is wrong!
> 
>
> ...  
> ...   
> 
> 
> Due to the fact that rules may change, I have to manage the python
> program, parsing the whole xml file, and self-modify the python code
> according to these variable rules.
> How can I do?

So, essentially you are creating a dynamic language? But you already have
one - python!

Who's responsible for creating these rules, and what do they allow to be
done? Because I'd rather use python snippets to define them, that you
compile using the exec-function.

If you insist on using XML, use some module like lxml to parse and create
your own language constructs.

Just a note: the use of "par_X" as attributes is unfortunate, to say the
least. It doesn't allow for easy argument swapping, can cause troubles
because you delete one attribute and miss renaming the others, and in
general it's not good design to have arbitrary numbers of parameters.

Instead, you better go with a nested param-tag.

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


RE: Almost There - os.kill()

2007-09-24 Thread Delaney, Timothy (Tim)
Always be careful with int() incase any of the values have a leading
zero - check the documentation for int() carefully.
 
Cheers,
 
Tim Delaney



From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Robert Rawlins - Think Blue
Sent: Monday, 24 September 2007 5:10 PM
To: 'Robert Rawlins - Think Blue'; [email protected]
Subject: RE: Almost There - os.kill()



Woops,

 

Spoke too soon, just wrapped them in int() and it works a charm :-D

 

Rob

 

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
rg] On Behalf Of Robert Rawlins - Think Blue
Sent: 24 September 2007 12:23
To: [email protected]
Subject: Almost There - os.kill()

 

Hello Guys,

 

Finally got around to sitting down to tidy up this script this morning
but I'm having a small syntax problem with os.kill() to kill a process
on my system. Here is the code:

 

def killApplication():

 

   pid = file('/var/lock/MyApplication.lock').read().strip()

   

   logging.info('Killing Application Process: %s' % pid)

 

   os.kill(pid, 15)

 

   logging.info('Application %s Killed' % pid)

 

As you can see if rips the PID from the lock file, which works fine as I
get log data which says 'Killing Application Process: 3079' exactly as I
would expect it too. However when I run this script I get the following
error:

 

Traceback (most recent call last):

  File "/pblue/new/Alive.py", line 50, in ?

main()

  File "/pblue/new/Alive.py", line 47, in main

doCheck()

  File "/pblue/new/Alive.py", line 43, in doCheck

killApplication()

  File "/pblue/new/Alive.py", line 28, in killApplication

os.kill(pid, 15)

TypeError: an integer is required

 

Which would suggest its passing those arguments in as the wrong data
types to the kill command. What is the best way to convert these?

 

Thanks guys,

 

Rob

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

RE: Almost There - os.kill()

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 12:40 +0100, Robert Rawlins - Think Blue wrote:
> Woops,
> 
>  
> 
> Spoke too soon, just wrapped them in int() and it works a charm :-D

I'm glad that you figured it out for yourself. I'd like to suggest that
you adjust your "give up and ask the list for help" threshold upwards.
Being stumped is frustrating, but on the other hand, figuring stuff out
for yourself is very rewarding, and you retain the acquired knowledge
more readily than if someone just gave you the answer.

By the way, I hope you only wrapped the pid argument in int(), since 15
is already an int.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


RE: Almost There - os.kill()

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 19:48 +0800, Delaney, Timothy (Tim) wrote:
> Always be careful with int() incase any of the values have a leading
> zero - check the documentation for int() carefully.

Why would leading zeroes be a problem?

>>> int("10")
10
>>> int("010")
10
>>> int("0010")
10
>>> int("00010")
10

Maybe you're thinking of "evil eval?"

>>> eval("10")
10
>>> eval("010")
8

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


RE: sorting a list numbers stored as strings

2007-09-24 Thread Delaney, Timothy (Tim)
Carsten Haese wrote:

> That interpreter session is a work of fiction, since sorted returns
> the sorted list instead of sorting the list in place. Also, it's
> better (i.e. more readable and likely faster) to use a sort key
> function instead of a comparison function whenever possible. In this
> case, the sort key function is particularly trivial:
> 
 l = ["1", "11", "2", "22"]
 sorted(l, key=int)
> ['1', '2', '11', '22']

It does appear trivial in this case, but need to be careful with using
int() if any of the strings could have leading zeros. In this case, the
fix is almost as trivial:

 l = ["01", "11", "08", "22"]
 sorted(l, key=lambda x: int(x, 10))
> ['01', '08', '11', '22']

Although I just tried the above using just sorted(l, key=int) and it
succeeded. I'm sure that in some version of Python it would have given a
ValueError (due to the default radix being 0) but it appears to have
changed to a default radix of 10 somewhere along the way. The docs don't
specify what the default radix is (I should probably raise a bug report
for this).

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


Re: sorting a list numbers stored as strings

2007-09-24 Thread Peter Otten
aine_canby wrote:

> I have the following list -
> 
> ["1", "11", "2", "22"]
> 
> how do I sort it like this -
> 
> ["1", "2", "11", "22"]

>>> items = ["1", "11", "2", "22"]
>>> items.sort(key=int)
>>> items
['1', '2', '11', '22']

This is more efficient than Amit's compare function and even Bruno's
decorate-sort-undecorate (DSU) -- which of course only matters if the list
becomes a bit larger. 

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


RE: Almost There - os.kill()

2007-09-24 Thread Delaney, Timothy (Tim)
Carsten Haese wrote:

> On Mon, 2007-09-24 at 19:48 +0800, Delaney, Timothy (Tim) wrote:
>> Always be careful with int() incase any of the values have a leading
>> zero - check the documentation for int() carefully.
> 
> Why would leading zeroes be a problem?
> 
 int("10")
> 10
 int("010")
> 10
 int("0010")
> 10
 int("00010")
> 10
> 
> Maybe you're thinking of "evil eval?"
> 
 eval("10")
> 10
 eval("010")
> 8

Nope - pretty sure that an earlier version of Python defaulted to a
radix of 0, but it appears to default to a radix of 10 in Python 2.5.

In any case, I've submitted a bug report and suggested new text for the
documentation of int() to make it clear what happens when a radix is not
specified.

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


RE: sorting a list numbers stored as strings

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 19:58 +0800, Delaney, Timothy (Tim) wrote:
> I'm sure that in some version of Python it would have given a
> ValueError (due to the default radix being 0) but it appears to have
> changed to a default radix of 10 somewhere along the way.

Not even Python 1.5.2 seems to have a problem with leading zeroes:

Python 1.5.2 (#1, Nov  6 1999, 14:53:40) [C] on sco_sv3
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> int("08")
8

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Python-URL! - weekly Python news and links (Sep 24)

2007-09-24 Thread Gabriel Genellina
QOTW:  "This thread shows again that Python's best feature is
comp.lang.python." - Joerg Schuster

"I find it best to treasure the saints, tolerate the irritable and ignore
the whiners." - RedGrittyBrick


Python as a functional language: of limited usage due to stack limitations:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/2b476f8d3a290f1b/

Generator functions, generator expressions... what is a
generator, after all?

http://groups.google.com/group/comp.lang.python/browse_thread/thread/7a4f8d011e6badcf/

A proposal for removing bitwise operators (most people
said "no, because..."):

http://groups.google.com/group/comp.lang.python/browse_thread/thread/4a16e4cba57b1c4d/

How widely is Python used at Google?

http://groups.google.com/group/comp.lang.python/browse_thread/thread/af75a3e91a03ec18/

An example of optimizing a Python program:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/fa33727aa3a6751f/

About sets, dicts, hash and mutable containers:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/bc8377a8a5d89a3f/

super() documentation and actual behavior are confusing:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/9b38dc19c6beeb8b/

Functions, the def statement, lambda calculus, and why those
things are the way they are:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/661eb7a7e80d310a/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Many Python conferences around the world are in preparation.
Watch this space for links 

Re: rules from an xml file

2007-09-24 Thread Stefan Behnel
jonny wrote:
> I have a python code that manages some parameters using some variable
> rules that may change from day to day. I'd like that the code will
> self-modify according to rules parsed from a xml file:
> 
> example:
> 
> 
>
>   
>   
>   
>   
>   
>par_2="0"/>
>   
>   
>   
>   
>   
>   
>   
>   
> 
>Something is wrong!
> 
>
> ...  
> ...   
> 
> 
> Due to the fact that rules may change, I have to manage the python
> program, parsing the whole xml file, and self-modify the python code
> according to these variable rules.
> How can I do?

A beautiful solution could be to implement a namespace for these elements in
lxml.etree (even if it's not an XML namespace with a URI). You would give each
of the elements its own subclass of lxml.etree.BaseElement, maybe split into
rule elements and expression elements, and then give each of them an
evaluate() method that returns the result of the evaluation, such as

def evaluate(self):
for child in self:
if child.evaluate():
return True
return False

for the "or" element or

def evaluate(self):
if self[0].evaluate():
return self.getnext().evaluate()
else:
return self.getnext().getnext().evaluate()

for an "if-then-else" statement as in your example above (plus special casing
if "then" or "else" are not there).

Then you define a mapping from the tag names to your element classes and let
lxml.etree instantiate the decision tree for you.

Here is the documentation on this feature:
http://codespeak.net/lxml/dev/element_classes.html
http://codespeak.net/lxml/dev/element_classes.html#id1

Especially these two class lookup schemes might be handy:
http://codespeak.net/lxml/dev/element_classes.html#custom-element-class-lookup
http://codespeak.net/lxml/dev/element_classes.html#namespace-class-lookup

And here is an example:
http://codespeak.net/svn/lxml/trunk/src/lxml/html/__init__.py

Have fun,
Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


enabling IPv6 in python

2007-09-24 Thread Piotr Dula (pdula)
Hello,
 
How to make python support IPv6?
 
I have IPv6 running on my host (interfaces have ipv6 addresses assigned)
 
I tried to do:
 
./configure --enable-ipv6
make 
make install
 
and I didn't get any error. However, IPv6 didn't work.  
 
 then I tried 
 
./configure --enable-ipv6=yes
 
and I got a lot of parse errors (many pages of errors similar to the
ones below)
 
In file included from /root/Piotr/Python-2.5.1/Modules/_tkinter.c:67:
/usr/include/tk.h:581: parse error before "Bool"
/usr/include/tk.h:583: parse error before "event"
/usr/include/tk.h:584: parse error before "root"
/usr/include/tk.h:585: parse error before "subwindow"
/usr/include/tk.h:586: parse error before "time"
/usr/include/tk.h:586: `time' redeclared as different kind of symbol
/usr/include/time.h:184: previous declaration of `time'
/usr/include/tk.h:591: parse error before "same_screen"
/usr/include/tk.h:597: parse error before "Bool"
/usr/include/tk.h:599: parse error before "window"
/usr/include/tk.h:601: parse error before "XActivateEven
 
How to make it work? 
 
Thank you in advance,
 
Piotr
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python variable assignement

2007-09-24 Thread mihai

This is the code:

begin = select_point()
if begin == None:
return

end = select_point()
while end != None:
record = Record(begin, end)
id = add(record)
begin = end
end = select_point()
# here (sometimes) begin has the same value (or points to the
same object) like end, the newly selected one

Is there a way to see if the names points to the same variables or
that there are different variables with the same values?

The problem is that the problem is more like an bug,
it happens only in certain conditions, and I have no idea why.

I have checked the values returned by select_point() and are different
in all the cases,
so the problem is with that variables names/values.

Thank you again,
Mihai.

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


Re: database persistence with mysql, sqlite

2007-09-24 Thread Gerardo Herzig
coldpizza wrote:

>Hi,
>
>I want to run a database query and then display the first 10 records
>on a web page. Then I want to be able to click the 'Next' link on the
>page to show the next 10 records, and so on.
>
>My question is how to implement paging, i.e. the 'Next/Prev' NN
>records without reestablishing a database connection every time I
>click Next/Prev? Is it at all possible with cgi/mod_python?
>
>For example, in a NON-web environment, with sqlite3 and most other
>modules, I can establish a database connection once, get a cursor
>object on which I run a single 'SELECT * FROM TABLE' statement and
>then use cursor.fetchmany(NN) as many times as there are still results
>left from the initial query.
>
>How do I do the same for the web? I am not using any high-level
>framework. I am looking for a solution at the level of cgi or
>mod_python (Python Server Pages under Apache). To call
>cursor.fetchmany(NN) over and over I need to pass a handle to the
>database connection but how do I keep a reference to the cursor object
>across pages? I use mysql and sqlite3 as databases, and I am looking
>for an approach that would work with both database types (one at a
>time). So far I have successfully used the following modules for
>database access: sqlite3, mysqld, and pyodbc.
>  
>
Apache/cgi just dont work this way. When apache receives a new request 
(a cgi being called), it starts a new thread, it execute him, and gives 
the client some result. AND THEN KILL THE THREAD. Altough i never used 
it, what i think you need is fast cgi (fcgi), wich takes care of 
persistent connections to a web server.

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


Re: An Editor that Skips to the End of a Def

2007-09-24 Thread Neil Cerutti
On 2007-09-22, Lawrence D'Oliveiro
<[EMAIL PROTECTED]> wrote:
> In message <[EMAIL PROTECTED]>, Bjoern
> Schliessmann wrote:
>> Nah. Use vim.
>
> Every other text editor I have ever used understands that the
> current position in a file is _between_ two characters (or
> before the first character, or after the last character), not
> _on_ a character. But not vi and its ilk.
>
> Try the following in vi/vim: Move to some point in the middle
> of a line. Press "i" to get into insert mode. Press escape to
> get out again. You'll end up one position to the left of where
> you were before. Press "i", and then escape again--you've moved
> another position left. Why is it incapable of keeping track of
> such a simple thing as your current position in the file?

That's a silly question. Of course it knows your current
position--it just chooses to modify your position when you exit
insert mode.

> Why does it need two different insert commands, "i" versus "a"?
> Because one of them can't insert at the end of a line, and the
> other can't insert at the beginning.

i and a are two of *many* ways to enter insert mode. I'm not sure
all of them are completely justified (I've never uses s or S, for
example). I typically use o, O, i, I and A the most. I don't have
much use for a.

> And why have command-versus-insert mode at all? No other text
> editor still surviving uses such an antiquated concept.

The existence of command mode allows plain old keystrokes to be
commands--it potentially makes commands easier to type. Emacs
users don't find it to be a compelling advantage. ;)

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


Re: rules from an xml file

2007-09-24 Thread Marc 'BlackJack' Rintsch
On Mon, 24 Sep 2007 13:42:05 +0200, Diez B. Roggisch wrote:

> jonny wrote:
> 
>> 
>>
>>   
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>>Something is wrong!
>> 
>>
>> ...  
>> ...   
>> 
>> […]
> […]
> Just a note: the use of "par_X" as attributes is unfortunate, to say the
> least. It doesn't allow for easy argument swapping, can cause troubles
> because you delete one attribute and miss renaming the others, and in
> general it's not good design to have arbitrary numbers of parameters.

Quite the same is true for numbers in tag names.  If you (the OP) need to
number the rules better use an attribute for the numbers.

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

Re: python variable assignement

2007-09-24 Thread Carsten Haese
On Mon, 2007-09-24 at 12:12 +, mihai wrote:
> [...]
> id = add(record)
> [...]

Not that this causes your problem, but I'd still like to point out that
'id' is the name of a built-in function. Shadowing built-in names can
lead to surprising behavior.

> Is there a way to see if the names points to the same variables or
> that there are different variables with the same values?

Yes. "==" tests whether two objects are equal, whereas "is" tests
whether two objects are actually the same object. Examples:

Two different list objects with equal contents:

>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a==b
True
>>> a is b
False

Two names for the same list object:

>>> a = [1,2,3]
>>> b = a
>>> a==b
True
>>> a is b
True

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: rules from an xml file

2007-09-24 Thread Diez B. Roggisch
Marc 'BlackJack' Rintsch wrote:

> On Mon, 24 Sep 2007 13:42:05 +0200, Diez B. Roggisch wrote:
> 
>> jonny wrote:
>> 
>>> 
>>>
>>>   
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>>Something is wrong!
>>> 
>>>
>>> ...  
>>> ...   
>>> 
>>> […]
>> […]
>> Just a note: the use of "par_X" as attributes is unfortunate, to say the
>> least. It doesn't allow for easy argument swapping, can cause troubles
>> because you delete one attribute and miss renaming the others, and in
>> general it's not good design to have arbitrary numbers of parameters.
> 
> Quite the same is true for numbers in tag names.  If you (the OP) need to
> number the rules better use an attribute for the numbers.

I meant of course


  0
  +


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

Re: An Editor that Skips to the End of a Def

2007-09-24 Thread Bruno Desthuilliers
W. Watson a écrit :
(top-post corrected)
> Bruno Desthuilliers wrote:
>> W. Watson a écrit :
>>> How about in the case of MS Win?
>>>
>>> Ben Finney wrote:

 (Please don't top-post. Instead, reply below each point to which
 you're responding, removing quoted text irrelevant to your response.)

>>
>> Wayne, may I second Ben on his suggestion to stop top-posting ?
> 
 > Well, you may. Unfortunately, there are many NGs that do the opposite.
 >
Unfortunately (for you at least), c.l.p is not one of those.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python variable assignement

2007-09-24 Thread Duncan Booth
mihai <[EMAIL PROTECTED]> wrote:

> 
> This is the code:
> 
> begin = select_point()
> if begin == None:
> return
> 
> end = select_point()
> while end != None:
> record = Record(begin, end)
> id = add(record)
> begin = end
> end = select_point()
> # here (sometimes) begin has the same value (or points to the
> same object) like end, the newly selected one
> 
> Is there a way to see if the names points to the same variables or
> that there are different variables with the same values?

You can check whether two names refer to the same object with the 'is' 
operator. So you would use:

   if begin is end: continue

to skip over any duplicate
> 
> The problem is that the problem is more like an bug,
> it happens only in certain conditions, and I have no idea why.
> 
> I have checked the values returned by select_point() and are different
> in all the cases,
> so the problem is with that variables names/values.

Are you sure that nothing you do can change the list of points you are 
iterating over: usually iteration returning unexpected duplicates is 
because you inserted something new into the middle of the list.

A few other unrelated points: the convention is to use 'is' when 
checking for None, and you can reduce the number of calls to 
'select_point' if you use the 'iter' function. Putting those together:

begin = select_point()
if begin is None:
return

for end in iter(select_point, None):
if begin is end:
continue
record = Record(begin, end)
id = add(record)
begin = end
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SOAPpy Error

2007-09-24 Thread linuxprog
linuxprog a écrit :
> hi all
>
> i'm building a webservice client with soappy
>
> when i send some informations it's returns an error
> here is the informations that generates the error
>var = SOAPpy.structType()
>var._addItem("code", u"XysZjd")
>var._addItem("value", 1)
> when i send the var variable SOAPpy prints this
>
>  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 473, in 
> __call__
>return self.__r_call(*args, **kw)
>  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 495, in 
> __r_call
>self.__hd, self.__ma)
>  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 366, in 
> __call
>config = self.config)
>  File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 228, in call
>data = r.getfile().read()
> AttributeError: 'NoneType' object has no attribute 'read'
>
> when i have activate debug , the debug mode shows :
> code :  -1
> msg : headers : None
>
> it should prints some thing like this if all goes well :
> code :  200
> msg :  OK
> headers : Date: Mon, 24 Sep 2007 09:08:45 GMT
> Server: Apache/2.2.3 (Debian) PHP/5.2.0-8+etch7
> X-Powered-By: PHP/5.2.0-8+etch7
> Content-Length: 2116
> Connection: close
> Content-Type: text/xml; charset=utf-8
>
> wha's wrong ?
>
> Thanks
>
still no answer !?
-- 
http://mail.python.org/mailman/listinfo/python-list


Converting numbers to unicode charaters

2007-09-24 Thread byte8bits
Here's how I'm doing this right now, It's a bit slow. I've just got
the code working. I was wondering if there is a more efficient way of
doing this... simple example from interactive Python:

>>> word = ''
>>> hexs = ['42', '72', '61', '64']
>>> for h in hexs:
...   char = unichr(int(h, 16))
...   word += char
...   print char
...
B
r
a
d
>>> print word
Brad


Each hex_number is two digits. unichr converts that to a character
that I append to previous ints that have been converted to chars. In
this way, I convert a string of hex numbers to ints to letters, to
words.

Perhaps I'm doing it wrong... any tips?

Thanks,
Brad

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


Re: sorting a list numbers stored as strings

2007-09-24 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> hi,
> 
> I have the following list -
> 
> ["1", "11", "2", "22"]
> 
> how do I sort it like this -
> 
> ["1", "2", "11", "22"]
> 
> thanks,
> 
> aine

Try:

  lst.sort(key = lambda s: int(s))

Assuming, of course, that "lst" is your original list; this will sort it 
in place.  Also, you should probably read about the "sorted" function 
here:

 

Cheers,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange behavious of the logging module?

2007-09-24 Thread Christian Meesters
Thanks Peter and Gabriel,

I see, so I should provide the application with an additional handler for
the file in order to gain maximum independence of the two handlers (console
& file stream).

>> Also, adding %(funcName)-8s to the formatter in basigConfig does not work
>> for me: instead of the functions name the level in lower case gets
>> inserted
>> into the logfile.
> 
> Looks like a bug...
> 

Well, the documentation -- as far as I understand it ;-) -- says the
behaviour should be different, you two basically agree ... think I should
file a report.

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


Re: strange behavious of the logging module?

2007-09-24 Thread Vinay Sajip
On Sep 24, 8:03 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>
> It would still be a good idea to file a bug report.

Not sure where the bug is. The script below, when called, prints
"Information" to the console and "INFO some_func Information" to
mc_rigid.log, as I would expect. (Python 2.5.1)

Best regards,

Vinay

import logging
logging.basicConfig(level=logging.DEBUG,
format='%(levelname)-8s %(funcName)-8s %
(message)s',
filename='mc_rigid.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the
sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

def some_func():
logging.info("Information")

if __name__ == "__main__":
some_func()


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


Re: Converting numbers to unicode charaters

2007-09-24 Thread Laurent Pointal
[EMAIL PROTECTED] a écrit :
> Here's how I'm doing this right now, It's a bit slow. I've just got
> the code working. I was wondering if there is a more efficient way of
> doing this... simple example from interactive Python:
> 
 word = ''
 hexs = ['42', '72', '61', '64']
 for h in hexs:
> ...   char = unichr(int(h, 16))
> ...   word += char
> ...   print char
> ...
> B
> r
> a
> d
 print word
> Brad
> 
> 
> Each hex_number is two digits. unichr converts that to a character
> that I append to previous ints that have been converted to chars. In
> this way, I convert a string of hex numbers to ints to letters, to
> words.
> 
> Perhaps I'm doing it wrong... any tips?

You have to go by int conversion to get codes, and by unichr to get 
corresponding unicode chars, so this seem the solution.

You may eventually use a more condensed expression and avoid n 
concatenation of n chars using join, like this:

 >>> u''.join(unichr(int(x,16)) for x in ['42','72','61','64'])
u'Brad'

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


Re: Converting numbers to unicode charaters

2007-09-24 Thread Paul Hankin
On Sep 24, 2:42 pm, [EMAIL PROTECTED] wrote:
> Here's how I'm doing this right now, It's a bit slow. I've just got
> the code working. I was wondering if there is a more efficient way of
> doing this... simple example from interactive Python:
>
> >>> word = ''
> >>> hexs = ['42', '72', '61', '64']
> >>> for h in hexs:
>
> ...   char = unichr(int(h, 16))
> ...   word += char
> ...   print char
> ...
> B
> r
> a
> d>>> print word
>
> Brad
>
> Each hex_number is two digits. unichr converts that to a character
> that I append to previous ints that have been converted to chars. In
> this way, I convert a string of hex numbers to ints to letters, to
> words.

The cleanest code is:

word = ''.join(unichr(int(h, 16)) for h in hexs)

If you want fast, you can build a cache once that maps hex strings to
unicode characters something like this:

cache = dict((hex(i)[2:], unichr(i)) for i in range(256))

Then use something like your code:
word = ''
for h in hexs:
  word += cache[h]

Or a list comprehension:
word = ''.join([cache[h] for h in hexs])

Or a generator:
word = ''.join(cache[h] for h in hexs)

--
Paul Hankin

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


shutil.copy2 error

2007-09-24 Thread Horse
I've written a python script that copies a nightly Oracle backup file
to another server.  Every couple days, the script fails with this
error message:

Error copying Q:/Oradata/GISPROD/Backups/3UISN35R_1_1 to s:/gisprod/
backups/3UISN35R_1_1
[Errno 22] Invalid argument



Here's the code for the function I'm running.  The path names are all
correct, and it works *most of the time*.  It only fails about once or
twice a week.  Anyone know where I can get more info on this "errno 22
invalid argument"?


def CopyNewFiles(SOURCE_DIR, DEST_DIR):
global STATUS
try:
os.chdir(SOURCE_DIR)
for x in os.listdir(SOURCE_DIR):
int_time = os.stat(x)[stat.ST_CTIME]
str_time = time.ctime(int_time)
if datetime.date.fromtimestamp(int_time + 0.00) >
YESTERDAY:
try:
DEST_FILE = os.path.join(DEST_DIR, x)
logfile.write(" Copying " + SOURCE_DIR + x + "
to " + DEST_FILE + "\n")
logfile.flush()
if not os.path.isfile(DEST_FILE):
shutil.copy2(x, DEST_FILE)
else:
logfile.write("File exists.  Skipping.
\n")
logfile.flush()
except (IOError, os.error), why:
logfile.write("\n\nError copying " + SOURCE_DIR +
x + " to " + DEST_FILE + "\n\n")
logfile.write("\n" + str(why) + "\n")
logfile.flush()
STATUS = "FAILED"
except:
logfile.write("\n\nUnhandled error in CopyNewFiles\n\n")
logfile.write("SOURCE_DIR = " + SOURCE_DIR + "\n")
logfile.write("DEST_DIR = " + DEST_DIR + "\n")
logfile.flush()
STATUS = "FAILED"

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


(pyqt) Parameters when connecting a signal to a method?

2007-09-24 Thread exhuma.twn
Some code:

--

def foobar(w):
   print w

QtCore.QObject,connect( my_line_edit,
QtCore.SIGNAL("returnPressed()"), foobar )

--


How can I get this to work so "foobar" prints out the sender of the
signal (i.e. my_line_edit)?

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


problem writing setup script

2007-09-24 Thread Christian Meesters
Hi

I have the following file structure

MANIFEST
README
INSTALL -- all text
setup.py
src/
__init__.py
foo.py
for_ext.pyx 

and this setup-script:

import sys
from distutils.core import setup
from distutils.extension import Extension
try:
from Pyrex.Distutils import build_ext
except ImportError:
__info__ = """
Please install Pyrex
(http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/)
before running this setup script.
"""
sys.exit(__info__)

setup(
name = "foo",
# snip
packages = ['foo'],
package_dir={'foo': 'src/'},
package_data = {'foo': ['README', 'INSTALL']},
ext_package='foo_ext',
ext_modules = [
Extension("foo_ext", ["src/foo_ext.pyx"])
],
cmdclass = {'build_ext' : build_ext}
)

Typing 
sudo python setup.py
runs without warning, however, this results in a file
/usr/lib/python2.5/site-packages/foo/foo.py , which I only can import like
import foo.foo
and not
import foo
in order to access foo's namespace.
Furhtermore a file foo_ext.so will be created
in /usr/lib/python2.5/site-packages, but I would like to see it
in /usr/lib/python2.5/site-packages/foo, since importing foo_ext.so only
makes sense for foo.

Does anybody know how I should change my file structure or the setup-script
to achieve those two goals?

TIA
Christian

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


Re: Converting numbers to unicode charaters

2007-09-24 Thread Duncan Booth
Laurent Pointal <[EMAIL PROTECTED]> wrote:

> You may eventually use a more condensed expression and avoid n 
> concatenation of n chars using join, like this:
> 
> >>> u''.join(unichr(int(x,16)) for x in ['42','72','61','64'])
> u'Brad'

Or even avoid the loop completely:

>>> hexs = ['42', '72', '61', '64']
>>> u'\\x'.join(['']+hexs).decode('string-escape')
'Brad'

(but for that to work you really do need to be sure that all the values are 
2 characters).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (pyqt) Parameters when connecting a signal to a method?

2007-09-24 Thread Diez B. Roggisch
exhuma.twn wrote:

> Some code:
> 
> --
> 
> def foobar(w):
>print w
> 
> QtCore.QObject,connect( my_line_edit,
> QtCore.SIGNAL("returnPressed()"), foobar )
> 
> --
> 
> 
> How can I get this to work so "foobar" prints out the sender of the
> signal (i.e. my_line_edit)?

I _think_ there is a way to get the signals sender in Qt itself. But I'm
unsure how to get that.

Alternatively, you can use a closure to create a reference:

def foobar(source, w):
   print w

def slotgen(source, slot):
def _slot(*args):
return slot(*((source,) + args))
return _slot

my_slot = slotgen(my_line_edit, foobar)

QtCore.QObject,connect( my_line_edit,
QtCore.SIGNAL("returnPressed()"), my_slot )

However, be careful to keep a reference to my_slot around! Otherwise, it
will be garbage collected!

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread NickC
On Sep 24, 9:16 pm, Bruno Desthuilliers  wrote:
> Matthew Woodcraft a écrit :
> > One reason for the different syntax is that functions, unlike most
> > other objects, know their own names (which can be shown in tracebacks
> > and the like).
>
> Nope. They know *one* of their names - the one they've been given when
> first instanciated. Which may or not be the name used to get at them...

That's exactly the point - a function may be given many names through
the assignment statement, just like any other data value. However, the
*first* name given to a function (the one in the def statement) is
special, as that is the name the function knows *itself* by.

While a function *can* be treated like any other piece of data once
you have a reference to one, the original statement does a lot more
than a normal assignment does:
  - being within the scope of a function significantly alters name
binding and lookup
  - return statements and yield statements are meaningful only within
the scope of a function
  - you can attach decorators to a function definition
  - you can include a docstring in a function definition

For the original poster, I suggest trying some of the other
suggestions in this thread, where you skip the def statement and
instead look at manipulating standard library functions like math.sin
and math.cos. Using a dictionary to select a function to run may be a
good trick to illustrate the usefulness of this technique (e.g.
passing in a command line argument to choose a function to call to
generate a test sequence)

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

Re: Building Python with VC8 on x64 Vista

2007-09-24 Thread danfike
On Sep 22, 10:08 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > 1>py_dyn_test.obj : error LNK2001: unresolved external symbol
> > _Py_NoneStruct
>
> Could it be that py_dyn_test.obj is a x86 (not AMD64) object
> file? Run dumpbin.

Hmm - I've never used dumpbin, but I think I like it.

It doesn't look like these are x86, though. See below:

D:\\py_dyn_test\x64\Debug>dumpbin /HEADERS py_dyn_test.obj
Microsoft (R) COFF/PE Dumper Version 8.00.50727.762
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file py_dyn_test.obj

File Type: COFF OBJECT

FILE HEADER VALUES
8664 machine (x64)



D:\\3rdParty\Python25\libs>dumpbin /HEADERS python25_d.lib
Microsoft (R) COFF/PE Dumper Version 8.00.50727.762
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file python25_d.lib

File Type: LIBRARY

FILE HEADER VALUES
8664 machine (x64)
   3 number of sections
46F3CED2 time date stamp Fri Sep 21 09:01:54 2007
 113 file pointer to symbol table
   8 number of symbols
   0 size of optional header
   0 characteristics



  Version  : 0
  Machine  : 8664 (x64)
  TimeDateStamp: 46F3CED2 Fri Sep 21 09:01:54 2007
  SizeOfData   : 001E
  DLL name : python25_d.dll
  Symbol name  : _Py_NoneStruct
  Type : data
  Name type: name
  Hint : 900
  Name : _Py_NoneStruct



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

Can a base class know if a method has been overridden?

2007-09-24 Thread Ratko
Hi all,

I was wondering if something like this is possible. Can a base class
somehow know if a certain method has been overridden by the subclass?
I appreciate any ideas.
Thanks,

Ratko

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-24 Thread Bruno Desthuilliers
NickC a écrit :
> On Sep 24, 9:16 pm, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
>> Matthew Woodcraft a écrit :
>>> One reason for the different syntax is that functions, unlike most
>>> other objects, know their own names (which can be shown in tracebacks
>>> and the like).
>> Nope. They know *one* of their names - the one they've been given when
>> first instanciated. Which may or not be the name used to get at them...
> 
> That's exactly the point - a function may be given many names through
> the assignment statement, just like any other data value. However, the
> *first* name given to a function (the one in the def statement) is
> special, as that is the name the function knows *itself* by.
> 
"knows itself by" ? Really ?-)

 >>> def toto(level):
... print "toto %s" % level
... if level == 0: print "done"
... else: toto(level-1)
...
 >>> toto(3)
toto 3
toto 2
toto 1
toto 0
done
 >>> tutu = toto
 >>> def toto(level):
... print "YADDA YADDA"
...
 >>> tutu(3)
toto 3
YADDA YADDA
 >>>


> While a function *can* be treated like any other piece of data once
> you have a reference to one, the original statement does a lot more
> than a normal assignment does:

Indeed. But :

>   - being within the scope of a function significantly alters name
> binding and lookup

Runtime stuff and 'locals' parameters of te function object initializer 
AFAICT.

>   - return statements and yield statements are meaningful only within
> the scope of a function

s/"within the scope"/"in the code object"/, I'd say... Look at the 
signature of the function object's initializer, it takes a code object.

Please some guru correct me if I'm wrong, but AFAICT, you can have all 
this working without the def statement itself (even if it's quite enough 
of a boring work to justify the existence of the def statement).

Anyway, the OP suggestion was to turn the statement into an expression 
(à la javascript), not to get rid of it.

>   - you can attach decorators to a function definition

@decorators are just syntactic sugar for HOFs. If you want to apply a 
decorator do a lambda, you don't need this syntax - just pass the lambda 
as a param to the decorator.

>   - you can include a docstring in a function definition

And you can add it afterwards too:

>>> toto.__doc__ is None
True
>>> toto.__doc__ = "yadda"
>>> toto.__doc__
'yadda'


Don't get me wrong, I'm not saying the def statement is useless. Just 
that the reasons why this statement exists have very few to do with your 
arguments here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (pyqt) Parameters when connecting a signal to a method?

2007-09-24 Thread exhuma.twn
On Sep 24, 4:47 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> exhuma.twn wrote:
> > Some code:
>
> > --
>
> > def foobar(w):
> >print w
>
> > QtCore.QObject,connect( my_line_edit,
> > QtCore.SIGNAL("returnPressed()"), foobar )
>
> > --
>
> > How can I get this to work so "foobar" prints out the sender of the
> > signal (i.e. my_line_edit)?
>
> I _think_ there is a way to get the signals sender in Qt itself. But I'm
> unsure how to get that.
>
> Alternatively, you can use a closure to create a reference:
>
> def foobar(source, w):
>print w
>
> def slotgen(source, slot):
> def _slot(*args):
> return slot(*((source,) + args))
> return _slot
>
> my_slot = slotgen(my_line_edit, foobar)
>
> QtCore.QObject,connect( my_line_edit,
> QtCore.SIGNAL("returnPressed()"), my_slot )
>
> However, be careful to keep a reference to my_slot around! Otherwise, it
> will be garbage collected!
>
> diez

Thanks diez. This works :)
Although, I still have to digest *what* this closure does, but I will
leave this as an exercise to myself. ;)

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


Re: strange behavious of the logging module?

2007-09-24 Thread Peter Otten
Vinay Sajip wrote:

> On Sep 24, 8:03 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>>
>> It would still be a good idea to file a bug report.
> 
> Not sure where the bug is. The script below, when called, prints
> "Information" to the console and "INFO some_func Information" to
> mc_rigid.log, as I would expect. (Python 2.5.1)

I get

$ python vinaj.py 
Information
$ cat mc_rigid.log 
INFO info Information

Maybe a platform issue (I'm on Ubuntu 7.04)?

It seems Logger.findCaller() gets puzzled by the following discrepancy:

>>> logging.info.func_code.co_filename
'logging/__init__.py'
>>> logging._srcfile
'/usr/lib/python2.5/logging/__init__.py'

I don't think I have messed with paths manually on that machine, by the
way.

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


Re: Can a base class know if a method has been overridden?

2007-09-24 Thread Bruno Desthuilliers
Ratko a écrit :
> Hi all,
> 
> I was wondering if something like this is possible. Can a base class
> somehow know if a certain method has been overridden by the subclass?

If your use case is to make sure a given ('abstract') method has been 
overriden, the canonical solution is to raise NotImplementedError in the 
base class's implementation, ie:


class Parent(object):
   def method(self):
 raise NotImplementedError

class GoodGirl(Parent):
   def method(self):
 print "I'm a good girl"

class BadBoy(Parent):
   pass


Else, this may be possible using a custom metaclass (or possibly just 
specializing the __new__ method), but there may be better solutions 
(depending on what you're really trying to do)..

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


Re: Google and Python

2007-09-24 Thread Alex Martelli
Bryan Olson <[EMAIL PROTECTED]> wrote:
   ...
> > YouTube (one of Google's most valuable properties) is essentially
> > all-Python (except for open-source infrastructure components such as
> > lighttpd).  Also, at Google I'm specifically "Uber Tech Lead, Production
> > Systems": while I can't discuss details, my main responsibilities relate
> > to various software projects that are part of our "deep infrastructure",
> > and our general philosophy there is "Python where we can, C++ where we
> > must". 
> 
> Good motto. So is most of Google's code base now in
> Python? About what is the ratio of Python code to C++
> code? Of course lines of code is kine of a bogus measure.
> Of all those cycles Google executes, about what portion
> are executed by a Python interpreter?

I don't have those numbers at hand, and if I did they would be
confidential: you know that Google doesn't release many numbers at all
about its operations, most particularly not about our production
infrastructure (not even, say, how many server we have, in how many data
centers, with what bandwidth, and so on).

Still, I wouldn't say that "most" of our codebase is in Python: there's
a lot of Java, a lot of C++, a lot of Python, a lot of Javascript (which
may not correspond to all that many "cycles Google executes" since the
main point of coding in Javascript is having it execute in the user's
browser, of course, but it's still code that gets developed, debugged,
deployed, maintained), and a lot of other languages including ones that
Google developed in-house such as
 .


> > Python is definitely not "just a tiny little piece" nor (by a
> > long shot) used only for "scripting" tasks; 
> 
> Ah, sorry. I meant the choice of scripting language was
> a tiny little piece of Google's method of operation.

In the same sense in which other such technology choices (C++, Java,
what operating systems, what relational databases, what http servers,
and so on) are similarly "tiny pieces", maybe.  Considering the number
of technology choices that must be made, plus the number of other
choices that aren't directly about technology but, say, about
methodology (style guides for each language in use, mandatory code
reviews before committing to the shared codebase, release-engineering
practices, standards for unit-tests and other kinds of tests, and so on,
and so forth), one could defensibly make a case that each and every such
choice must of necessity be "but a tiny little piece" of the whole.

> "Scripting language" means languages such as Python,
> Perl, and Ruby.

A widespread terminology, but nevertheless a fundamentally bankrupt one:
when a language is used to develop an application, it's very misleading
to call it a "scripting language", as it implies that it's instead used
only to "script" something else.  When it comes time to decide which mix
of languages to use to develop a new application, it's important to
avoid being biased by having tagged some languages as "scripting" ones,
some (say Java) as "application" ones, others yet (say C++) as "system"
ones -- the natural subconscious process would be to say "well I'm
developing an X, I should use an X language, not a Y language or a Z
language", which is most likely to lead to wrong choices.


> > if the mutant space-eating
> > nanovirus should instantly stop the execution of all Python code, the
> > powerful infrastructure that has been often described as "Google's
> > secret weapon" would seize up.
> 
> And the essence of the Google way is to employ a lot of
> smart programmers to build their own software to run on
> Google's infrastructure. Choice of language is triva.

No, it's far from trivial, any more than choice of operating system, and
so on.  Google is a technology company: exactly which technologies to
use and/or develop for the various necessary tasks, far from being
trivial, is the very HEART of its operation.

Your ludicrous claim is similar to saying that the essence of a certain
hedge fund is to employ smart traders to make a lot of money by
sophisticated trades (so far so reasonable) and (here comes the idiocy)
"choice of currencies and financial instruments is trivia" (?!?!?!) --
it's the HEART of such a fund, to pick and choose which positions to
build, unwind, or sell-on, and which (e.g.) currencies should be
involved in such positions is obviously *crucial*, one of the many
important decisions those "smart traders" make every day, and far from
the least important of the many.  And similarly, OF COURSE, for choices
of technologies (programming languages very important among those) for a
technology company, just like, say, what horticultural techniques and
chemicals to employ would be for a company whose "essence" was
cultivating artichokes for sale on the market, and so on.


> I think both Python Google are great. What I find
> ludicrous is the idea that the bits one hears about how
> Google builds its software make a case for how others
>

Re: Can a base class know if a method has been overridden?

2007-09-24 Thread Michele Simionato
On Sep 24, 5:23 pm, Ratko <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I was wondering if something like this is possible. Can a base class
> somehow know if a certain method has been overridden by the subclass?
> I appreciate any ideas.
> Thanks,
>
> Ratko


The first time I used Zope, I immediately had an issue of overriding a
predefined
methods without knowing it (there were 400+ methods inherited from
dozens of base
classes). So I wrote this utility:


def check_if_I_am_overriding_names():
"""Prints a message if we are overriding a name. Useful for
framework
beginners. Example in Zope:

>> from OFS.Folder import Folder
>> class MyFolder(OFS.Folder):
..check_if_I_am_overriding_names()
..id = 'pippo'
..
AlreadyDefinedNameWarning: id
"""

def makecls(name, bases, dic):
for nam, val in dic.iteritems():
if nam.endswith("__") or nam == "meta_types":
# ignore redefinitions of special names
# and redefinition of meta_types (for Zope code)
continue
any_base_has_name = [base for base in bases
 if hasattr(base, nam)]
if any_base_has_name:
print "AlreadyDefinedNameWarning: " + nam
return type(name, bases, dic)

f = sys._getframe(1)
f.f_locals["__metaclass__"] = makecls

Michele Simionato

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


To Andrey Khavryuchenko <[EMAIL PROTECTED]> was: Who can develop the following Python script into working application ?

2007-09-24 Thread http://members.lycos.co.uk/dariusjack/
to Andrey Khavryuchenko <[EMAIL PROTECTED]>
he said:
"
Actually, I am a python (and django) developer, looking for a
contract,
owning Nokia 770 and contacted original poster with no response.

--
Andrey V Khavryuchenko   http://a.khavr.com/
Chytach - unflood your feeds http://www.chytach.com/
Software Development Company http://www.kds.com.ua/
"

I didn't get any email from you.
Please have a look at your mailbox to verify the above.

Darius

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


Re: Can a base class know if a method has been overridden?

2007-09-24 Thread Ratko
> If your use case is to make sure a given ('abstract') method has been
> overriden, the canonical solution is to raise NotImplementedError in the
> base class's implementation

I am not really interested in forcing the subclass to implement a
method. I am interested in knowing *whether* it did implement it or
not.


> Else, this may be possible using a custom metaclass (or possibly just
> specializing the __new__ method), but there may be better solutions
> (depending on what you're really trying to do)..

I have a base class EvtHandler that has methods defined to handle
certain events. You then subclass from EvtHandler and override the
methods for the events you want to receive. If a method has been
overridden, the base class will automatically register for those
events to make sure that they are even delivered to this handler
(which is why I would need to know whether a method has been
overridden or not). Of course, there are other ways of doing this
which would require a bit more work from the subclass... I just
thought this would be a neat "automatic" way of registering for
events.

For example:

class EvtHandler:
def __init__(self):
if onKey is overridden:
 register_for_key_events()

def onKey(self):
pass


class MyHandler(EvtHandler):
def onKey(self):
# do something here

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


Re: Newbie completely confused

2007-09-24 Thread Jeroen Hegeman
Thanks for the comments,

>
> (First, I had to add timing code to ReadClasses: the code you posted
> doesn't include them, and only shows timings for ReadLines.)
>
> Your program uses quite a bit of memory. I guess it gets harder and
> harder to allocate the required amounts of memory.

Well, I guess there could be something in that, but why is there a  
significant increase after the first time? And after that, single- 
trip time pretty much flattens out. No more obvious increases.

>
> If I change this line in ReadClasses:
>
>  built_classes[len(built_classes)] = HugeClass(long_line)
>
> to
>
>   dummy = HugeClass(long_line)
>
> then both times the files are read and your data structures are built,
> but after each run the data structure is freed. The result is that  
> both
> runs are equally fast.

Isnt't the 'del LINES' supposed to achieve the same thing? And  
really, reading 30MB files should not be such a problem, right? (I'm  
also running with 1GB of RAM.)

> I'm not sure how to speed things up here... you're doing much  
> processing
> on a lot of small chunks of data. I have a number of observations and
> possible improvements though, and some might even speed things up a  
> bit.

Cool thanks, let's go over them.

>
> You read the files, but don't use the contents; instead you use
> long_line over and over. I suppose you do that because this is a test,
> not your actual code?

Yeah ;-) (Do I notice a lack of trust in the responses I get? Should  
I not mention 'newbie'?)

Let's get a couple of things out of the way:
- I do know about meaningful variable names and case-conventions,  
but ... First of all I also have to live with inherited code (I don't  
like people shouting in their code either), and secondly (all the  
itemx) most of these members normally _have_ descriptive names but  
I'm not supposed to copy-paste the original code to any newsgroups.
- I also know that a plain 'return' in python does not do anything  
but I happen to like them. Same holds for the sys.exit() call.
- The __init__ methods normally actually do something: they  
initialise some member variables to meaningful values (by calling the  
clear() method, actually).
- The __clear__ method normally brings objects back into a well- 
defined 'empty' state.
- The __del__ methods are actually needed in this case (well, in the  
_real_ code anyway). The python code loads a module written in C++  
and some of the member variables actually point to C++ objects  
created dynamically, so one actually has to call their destructors  
before unbinding the python var.

I tried to get things down to as small as possible, but when I found  
out that the size of the classes seems to contribute to the issue  
(removing enough member variables will bring you to a point where all  
of a sudden the speed increases a factor ten, there seems to be some  
breakpoint depending on the size of the classes) I could not simply  
remove all members but had to give them funky names. I kept the main  
structure of things, though, to see if that would solicit comments.  
(And it did...)

>
>
> In a number of cases, you use a dict like this:
>
>  built_classes  = {}
>  for i in LINES:
>  built_classes[len(built_classes)] = ...
>
> So you're using the indices 0, 1, 2, ... as the keys. That's not what
> dictionaries are made for; lists are much better for that:
>
>  built_classes = []
>  for i  in LINES:
>  built_classes.append(...)

Yeah, I inherited that part...

>
> Your readLines() function reads a whole file into memory. If you're
> working with large files, that's not such a good idea. It's better to
> load one line at a time into memory and work on that. I would even
> completely remove readLines() and restructure ReadClasses() like this:

Actually, part of what I removed was the real reason why readLines()  
is there at all: it reads files in blocks of (at most) some_number  
lines, and keeps track of the line offset in the file. I kept this  
structure hoping that someone would point out something obvious like  
some internal buffer going out of scope or whatever.

All right, thanks for the tips. I guess the issue itself is still  
open, though.

Cheers,
Jeroen

Jeroen Hegeman
jeroen DOT hegeman AT gmail DOT com

WARNING: This message may contain classified information. Immediately  
burn this message after reading.



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


Re: Newbie completely confused

2007-09-24 Thread Jeroen Hegeman

>
> Your code does NOT include any statements that could have produced the
> above line of output -- IOW, you have not posted the code that you
> actually ran.

Oh my, I must have cleaned it up a bit too much, hoping that people  
would focus on the issue instead of the formatting of the output  
strings! Did you miss your morning coffee???

> Your code is already needlessly monstrously large.
Which I realised and apologised for beforehand.

>
> And Python 2.5.1 does what? Strike 3.

Hmm, I must have missed where it said that you can only ask for help  
if you're using the latest version... In case you're wondering, 2.5.1  
is not _really_ that wide-spread as most of the older versions.

> For handling the bit extraction stuff, either
[snip]
> (b) do a loop over the bit positions

Now that sounds more useful. I'll give that a try.

Thanks,
Jeroen

Jeroen Hegeman
jeroen DOT hegeman AT gmail DOT com

WARNING: This message may contain classified information. Immediately  
burn this message after reading.



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


Re: Can a base class know if a method has been overridden?

2007-09-24 Thread Marc 'BlackJack' Rintsch
On Mon, 24 Sep 2007 15:48:07 +, Ratko wrote:

> I have a base class EvtHandler that has methods defined to handle
> certain events. You then subclass from EvtHandler and override the
> methods for the events you want to receive. If a method has been
> overridden, the base class will automatically register for those
> events to make sure that they are even delivered to this handler
> (which is why I would need to know whether a method has been
> overridden or not). Of course, there are other ways of doing this
> which would require a bit more work from the subclass... I just
> thought this would be a neat "automatic" way of registering for
> events.
> 
> For example:
> 
> class EvtHandler:
> def __init__(self):
> if onKey is overridden:
>  register_for_key_events()
> 
> def onKey(self):
> pass
> 
> 
> class MyHandler(EvtHandler):
> def onKey(self):
> # do something here

Maybe "tagging" the original `on_key()`:

class EvtHandler:
def __init__(self):
if not hasattr(self.on_key, 'dummy'):
 print 'register_for_key_events()'

def _dummy_handler(self):
pass
_dummy_handler.dummy = True

on_key = _dummy_handler
on_whatever = _dummy_handler


class MyHandler(EvtHandler):
def on_key(self):
print 'Do something...'

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


Re: Can a base class know if a method has been overridden?

2007-09-24 Thread Chris Mellon
On 9/24/07, Ratko <[EMAIL PROTECTED]> wrote:
> > If your use case is to make sure a given ('abstract') method has been
> > overriden, the canonical solution is to raise NotImplementedError in the
> > base class's implementation
>
> I am not really interested in forcing the subclass to implement a
> method. I am interested in knowing *whether* it did implement it or
> not.
>
>
> > Else, this may be possible using a custom metaclass (or possibly just
> > specializing the __new__ method), but there may be better solutions
> > (depending on what you're really trying to do)..
>
> I have a base class EvtHandler that has methods defined to handle
> certain events. You then subclass from EvtHandler and override the
> methods for the events you want to receive. If a method has been
> overridden, the base class will automatically register for those
> events to make sure that they are even delivered to this handler
> (which is why I would need to know whether a method has been
> overridden or not). Of course, there are other ways of doing this
> which would require a bit more work from the subclass... I just
> thought this would be a neat "automatic" way of registering for
> events.
>
> For example:
>
> class EvtHandler:
> def __init__(self):
> if onKey is overridden:
>  register_for_key_events()
>
> def onKey(self):
> pass
>
>
> class MyHandler(EvtHandler):
> def onKey(self):
> # do something here

Clumsy, but it seems to work. Using a sentinel value as Marc Rintsch
suggests might be better:

>>> class A(object):
... def vMethod(self, x):
... raise NotImplemented
... def is_implemented(self, method):
... if getattr(type(self), method.__name__).im_func is not
method.im_func:
... return True
... def otherMethod(self, x):
... raise NotImplemented
...
>>> class B(A):
... def vMethod(self, x):
... print x
...
>>> b = b()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'B' object is not callable
>>> b = B()
>>> b.otherMethod(10)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 8, in otherMethod
TypeError: exceptions must be classes, instances, or strings
(deprecated), not NotImplementedType
>>> b.vMethod(10)
10
>>> b.is_implemented(A.vMethod)
True
>>> b.is_implemented(A.otherMethod)
>>>


(Note that I accidentally raised NotImplemented instead of
NotImplementedError, oops.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: building a GUI

2007-09-24 Thread Oleg Batrashev
On Sep 23, 5:21 pm, yadin <[EMAIL PROTECTED]> wrote:
> if i were up to make a GUI chich are the advantages of choosing python
> over matlab or java?

Haven't seen any free visual layout program for swing, swing is
somewhat messy - unnecessary complex layout classes. Compile - run
cycle without visual layouting is pain. Swing look is unnatural,
native looks are buggy.

glade + pygtk works well for me (in linux).

Oleg

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


Re: database persistence with mysql, sqlite

2007-09-24 Thread coldpizza
On Sep 24, 7:23 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message <[EMAIL PROTECTED]>, coldpizza
> wrote:
>
> > So far, with mysql I use 'SELECT * FROM TABLE LIMIT L1, L2' where L1
> > and  L2 define the range for the 'Next' and 'Previous' commands. I
> > have to run the query every time a click a 'Next/Prev' link. But I am
> > not sure that this is the best and most efficient way.

> Try it first, then see what happens. Remember, premature optimization is the
> root of all (programming) evil.

It turned out that the method above ('SELECT * FROM TABLE LIMIT L1,
L2') works ok both with mysql and sqlite3, therefore I have decided to
stick with it until I find something better. With Sqlite3 you are
supposed to use LIMIT 10 OFFSET NN, but it also apparently supports
the mysql syntax (LIMIT NN, 10) for compatibility reasons.

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


Re: building a GUI

2007-09-24 Thread cyberco
Try BoaConstructor and the wxPython library, both are wonderfull. If
you don't mind using Java Swing, and there are good reasons for that,
go for jython. It simplifies the java swingcode so much you don't have
to use a graphical GUI builder anymore :)

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


CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS!

2007-09-24 Thread Sword, Robyn

how do you claim your tickets?


 


CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS!

CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS! lisawill4u at yahoo.com
 
Sat Nov 20 21:35:53 CET 2004 

*   Previous message: Python Tutorials, about 100 and sorted by
Topic or Category


*   Next message: CGI email script


*   Messages sorted by: [ date ]
  [ thread ]
  [ subject ]
  [ author ]
  



An HTML attachment was scrubbed...
URL:
http://mail.python.org/pipermail/python-list/attachments/20041120/341599
3d/attachment.htm 



*   Previous message: Python Tutorials, about 100 and sorted by
Topic or Category


*   Next message: CGI email script


*   Messages sorted by: [ date ]
  [ thread ]
  [ subject ]
  [ author ]
  



More information about the Python-list mailing list
 



This e-mail, including attachments, may include confidential and/or 
proprietary information, and may be used only by the person or entity to 
which it is addressed. If the reader of this e-mail is not the intended 
recipient or his or her authorized agent, the reader is hereby notified 
that any dissemination, distribution or copying of this e-mail is 
prohibited. If you have received this e-mail in error, please notify the 
sender by replying to this message and delete this e-mail immediately.

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

Re: Converting numbers to unicode charaters

2007-09-24 Thread Peter Otten
Duncan Booth wrote:

> Laurent Pointal <[EMAIL PROTECTED]> wrote:
> 
>> You may eventually use a more condensed expression and avoid n 
>> concatenation of n chars using join, like this:
>> 
>> >>> u''.join(unichr(int(x,16)) for x in ['42','72','61','64'])
>> u'Brad'
> 
> Or even avoid the loop completely:
> 
 hexs = ['42', '72', '61', '64']
 u'\\x'.join(['']+hexs).decode('string-escape')
> 'Brad'
> 
> (but for that to work you really do need to be sure that all the values are 
> 2 characters).

Or

>>> "".join(['42', '72', '61', '74']).decode("hex").decode("latin1")
u'Brat'

(same caveat)

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


  1   2   >