Re: using super

2008-01-01 Thread Michele Simionato
On Jan 1, 7:56 am, iu2 <[EMAIL PROTECTED]> wrote:
> no one has to remember to call the parent's get_name method. It's done
> automatically.
>
> (A PEP maybe? I sense you don't really like it.. ;-)
> What do you think? Good? Too implicit?
>
> iu2

No PEP, this would never pass. There would be no way
to stop a method from calling its parent: you would
lose control of your classes, so I think this is a
bad idea. Having said so, it is easy to implement
what you want with a metaclass:

def callParent(*methodnames):
 class Meta(type):
 def __init__(cls, name, bases, dic):
 for methodname in methodnames:
 if methodname in dic:
 def new_meth(self, method=methodname):
 parent = getattr(super(cls, self), method,
None)
 if parent: parent()
 child = dic.get(method)
if child: child(self)
 setattr(cls, methodname, new_meth)
 return Meta

class B(object):
__metaclass__ = callParent('get_name')
def get_name(self):
print "This is B.get_name"

class C(B):
def get_name(self):
print "This is C.get_name"


C().get_name()


Now every subclass of B defining a get_name method
will automagically call its parent method.

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


Re: pexpect ssh login and ls | grep

2008-01-01 Thread Karthik Gurusamy
On Dec 31 2007, 6:46 pm, crybaby <[EMAIL PROTECTED]> wrote:
> 1) what are these characters:
> \x1b]0;
> ~\x07\x1b[?1034h
>
> in line '\x1b]0;[EMAIL PROTECTED]:[EMAIL PROTECTED] ~]'?

These are probably escape sequences in your shell prompt string.
Typically they are interpreted by the terminal, like xterm, to update
title bar.

>
> 2) Also, how come I don't get 0 or 2(excuting ls command exit code)
> from result.split('\r\n')[0] or result.split('\r\n')[1] ?

I don't think your expect worked fine to capture the desired output.

>
> This is what I get:>>> import pexpect
> >>> child=pexpect.spawn('ssh [EMAIL PROTECTED]')
> >>> child.sendline("ls mytest.log > /dev/null 2>&1; echo $?")
> 41
> >>> child.before
> >>> print child.before
> None
> >>> print child.after
> None

before/after makes sense only after an expect. At this point there is
only a sendline; not expect. So the above None output is expected.

> >>> child.expect([pexpect.TIMEOUT, '\$ '])
> 1

1 implies it matched the second pattern. You want to use raw strings.
r'\$' or else the re sent down is a plain $ which re interprets as end
of buffer.
Most important here is your prompt doesn't end with a $ (it's
something like [EMAIL PROTECTED] ~]). Thus make it,

child.expect(r'.*]')

Try the ls command and rest of the statements.

Karthik

> >>> result=child.before
> >>> print result.split('\r\n')[1]
> [EMAIL PROTECTED] ~]
> >>> print result.split('\r\n')[0]
>
> Last login: Mon Dec 31 20:52:09 2007 from com1>>> print result.split('\r\n')
>
> ['Last login: Mon Dec 31 20:52:09 2007 from com1\r',
> '\x1b]0;[EMAIL PROTECTED]:[EMAIL PROTECTED] ~]']

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


M I-5'Per secution ' the BB C, televis ion an d rad io

2008-01-01 Thread imvmifvm
-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
-= the BBC, television and radio. -=
-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=

The first incident in June 1990 was when a BBC newsreader made what. seemed
to be a reaction. to something which had happened in my home, and out of
context of what they were reading. My first reaction was. disbelief; nothing
of the sort had ever happened before,. the idea that such a thing could
occur had not crossed my. mind, yet there was no doubt of what had just
taken. place. My disbelief eroded as this recurred time after time. Besides
the news, offenders. included shows such as Crimewatch (!), Newsnight, and
"entertainment" shows. There seems to. be very little moral understanding
among the people who make. these programmes; they just assume they will
never. be caught, so they carry on without a thought for the illegality or
amorality of what they do. The only time I. ever heard a word raised in
doubt was. by Paxman being interviewed by someone else (I think by Clive
Anderson) back in 1990; referring to the "watching" he said it. troubled
him, and when asked by the host what you could do about. it, replied "Well,
you could just switch it off" (meaning the. surveillance monitor in the
studio). He. clearly didn't let his doubts stand in the way of continued
surreptitious spying from his own or other. people's shows, though.

Now you're convinced this is. a troll, aren't you? This story has been the
subject of much debate on the. uk.* Usenet newsgroups for over a year, and
some readers believe. it to be an invention (it has even been suggested that
a group of psychology students are responsible!), others. think it
symptomatic of a derangement of the author, and a few give it. credence.
Quite a few people do know part or all. of the story already, so this text
will fill in the. gaps in their knowledge. For the rest, what may persuade
you of the third possibility is that some of the incidents. detailed are
checkable against any archives. of radio and TV programmes that exist; that
the incidents involve named people (even. if those hiding in the shadows
have not made their. identity or affiliations evident), and those people
may be persuaded to come out with the truth;. and that the campaign of
harassment is continuing today both in the UK and on the. American
continent, in a. none-too-secret fashion; by its nature the significant risk
of exposure. increases with time.

On several occasions people said to my face that harassment from the. TV was
happening. On the first day I worked in. Oxford, I spent the evening in the
local pub with the company's technical director. Ian, and Phil, another
employee. Ian made a few references to me and said to. Phil, as if in an
aside, "Is he the bloke who's been. on TV?" to which Phil replied, "Yes, I
think. so".

I. made a number of efforts to find the bugs, without success; last year we
employed professional. counter-surveillance people to scan for bugs (see
later) again without result. In. autumn 1990 I disposed of my TV and watched
virtually no. television for the next three years. But harassment from TV
stations has gone. on for over six years and continues to this day. This is
something that many people. obviously know is happening; yet the TV staff
have the morality of. paedophiles, that because they're getting away with it
they. feel no wrong.

Other people who were involved in the. abuse in 1990 were DJs on BBC radio
stations,. notably disc jockeys from Radio 1 and other stations (see the
following section). Again, since they don't have sense in. the first place
they can't be expect to have the moral sense not to be part of. criminal
harassment.

343

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


M-I,5`Persecu tion ` buggi ng an d counter-surveillan ce

2008-01-01 Thread mimvev
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-= MI5: bugging. and counter-surveillance -=
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

PO: >Did. you ever look for the bugs in your house ? If not, why not ? I mean if
PO: >I thought that was happening. to me, I'd search the place from top to 
bottom,
PO: >I mean. I live there I would know if anything was out of place. If I was
PO: >really suspicious, I would call in one of those bug detection. teams which
PO: >have those machines that pick up the transmitted radio. waves. This
PO:. >reminds me of BUGS, that new programme on BBC1 on

That's exactly what we did. We went to. a competent, professional detective
agency in London, paid them over 400 quid to debug our house.. They used
scanner devices which go to over 1. GHz and would pick up any nearby
transmitter in that range, they also checked. the phones and found
nothing... but if the tap was at the exchange, then. they wouldn't find
anything,. would they?

CS: >Doesn't this suggest. to you that there are, in fact, no bugs to be found?

You can assume that they've done this sort of. thing to other people in more
"serious" cases, where they would know the targets. would suspect the
presence of electronic. surveillance. So they will have developed techniques
and devices which are not readily detectable either by. visual inspection or
by. electronic means. What those techniques might be, I couldn't guess.

In this case,. the existence of bugging devices was clear from the
beginning, and they "rubbed it in" with what was said by. the boy on the
coach. It was almost. as if they wanted counter-surveillance people to be
called in, who they knew. would fail to detect the bugging devices, causing
loss of credibility to the other things I would have. to say relating to the
harassment.

I did all the things someone in my situation would do to try. to find the
bugs. In addition to calling in professional help using. electronic
counter-surveillance, I made a close. visual inspection of electrical
equipment, plus any points where audio or video. surveillance devices might
have been concealed. Of course, I found nothing.. Normal surveillance
"mini-cameras" are quite noticeable. and require visible supporting
circuitry. It seems to me the best place to. put a small video surveillance
device. would be additional to a piece of electronic equipment such as a TV
or video. It would be necessary to physically break in to a property. to fit
such a. device.

2773

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


M'I-5 Persecutio n , Capita l R adio - Chri s Tarran t

2008-01-01 Thread vimfefv
-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
-=. Capital Radio - Chris Tarrant -=
-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=

Capital Radio DJs have been "in on it". from the start. One of the first
things I heard in the summer of 1990 was from a Capital DJ who said,. "If
he listens to Capital then he. can't be all bad" (supportive, you see. We're
not bastards). Much of. what came over the radio in 1990 is now so far away
the precise details have. been obliterated by time. No diary was kept of the
details, and although archives if they exist may give. pointers, the
ambiguity of what broadcasters said would leave that. open to
re-interpretation.

In spring 1994,. Chris Tarrant on his Capital morning show made an aside to
someone else in the studio, about a person. he didn't identify. He said,
"You know this. bloke? He says we're trying to kill him. We should be done
for attempted. manslaughter".

That mirrored something I had said a day. or two before. What Tarrant said
was understood by the staff member in the. studio he was saying it to; they
said, "Oh no, don't say that" to Tarrant. If any archives. exist of the
morning show (probably unlikely) then it. could be found there; what he said
was so out of context that he would be very hard. put to find an explanation.
A couple of days. later, someone at the site where I was working repeated the
remark although in a. different way; they said there had been people in a
computer room when automatic fire extinguishers. went off and those people
were. "thinking of suing for attempted manslaughter".

Finally, this isn't confined. to the established radio stations. In 1990
after I. had listened to a pirate radio station in South London for about
half an. hour, there was an audible phone call in the background, followed
by total. silence for a few moments, then shrieks of laughter. "So what are
we supposed to say now? Deadly torture? He's. going to talk to us now, isn't
he?", which meant that they could hear what I would say in my. room.

5203

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


Re: Bizarre behavior with mutable default arguments

2008-01-01 Thread Arnaud Delobelle
On Jan 1, 5:26 am, NickC <[EMAIL PROTECTED]> wrote:
> On Jan 1, 3:22 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>
> > On Dec 31, 10:58 am, Odalrick <[EMAIL PROTECTED]> wrote:
>
> > > I'm surprised noone has said anything about the why of default
> > > mutables. I think it is becasue it isn't easy to do it an other way.
>
> > [...]
>
> > There is an easy enough way: evaluate default values when the function
> > is called rather than when it is defined.  This behaviour comes with
> > its own caveats as well I imagine, and it's not 'as easy' to implement
> > as the current one.
>
> As Odalrick notes, there is no way to give different calls to a
> function their own copies of mutable default arguments without re-
> evaluating the defaults every time the function is called. The
> horrendous performance implications mean that that simply isn't going
> to happen. So the status quo, where the defaults are calculated once
> when the function is defined and the result cached in the function
> object is unlikely to change.

I'm in no way advocating a change, in fact I wouldn't like things to
change.  I was just saying that it was not difficult (technically) to
alter the behaviour, but that this change wouldn't be desirable
because it would make code more difficult to reason on.  OTOH a very
common idiom in python is

def foo(x, y, z=None):
if z is None: z = ['a', 'mutable', 'object']
# stuff that foo does

This the current way to say "I want the default value of z to be
reevaluated each time it is used".  I use this much more often than

def bar(x, y, z=ExpensiveImmutableCreation())

So I'm not so convinced with the performance argument at face value
(though it's probably pertinent:)

> > What's good about the current behaviour is that it is easy to reason
> > with (once you know what happens), even though you almost have to get
> > bitten once.  But using this to have static variable is extremely ugly
> > IMHO.
>
> The only thing it doesn't give you is a static variable that isn't
> visible to the caller. Py3k's keyword-only arguments (PEP 3102) will
> make those cases a little tidier, since it won't be possible to
> accidentally replace the static variables by providing too many
> positional arguments.

I was always a bit puzzled by this PEP.  If this is one of the
underlying reasons for it, then I am even more puzzled.

> I believe the suggestion of permitting static variables after the **
> entry in a function's parameter list was raised during the PEP 3102
> discussions, but never gained much traction over a '_cache={}' keyword-
> only argument approach (and the latter has the distinct advantage of
> being *much* easier to test, since you can override the cache from the
> test code to ensure it is being handled correctly).

Well I'm glad that didn't go through, argument lists in function
definitions are complicated enough already!

--
Arnaud

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


M-I,5.Perse cution - cost of the operati on

2008-01-01 Thread vfmevm
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-= MI5: cost of the. operation -=
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Here's what a couple of other people on Usenet (uk.misc) had to. say
regarding the cost. of running such an operation...

PO: >Have some sense, grow up. and smell reality. What you are talking about
PO: >would take loads of planning, tens of thousands of pounds and. lots of
PO: >people involved. in the planning, execution and maintenance of it. You
PO: >must have a very high opinion of yourself to think you are. worth it.

PM: >But. why? And why you? Do you realize how much it would cost to keep
PM: >one person under continuous. surveillance for five years? Think about
PM: >all the man/hours. Say they. _just_ allocated a two man team and a
PM:. >supervisor. OK., Supervisor's salary, say, #30,000 a year. Two men,
PM: >#20,000 a year each. But. they'd need to work in shifts -- so it would
PM: >be six men at #20,000 (which with on-costs would work. out at more like
PM: >#30,000 to the. employer.) 
PM:. >
PM: >So, we're talking. #30,000 x 6. #180,000. plus say, #40,000 for the 
PM: >supervisor. #220,000. Then you've got the hardware involved.. And 
PM: >any transcription that needs doing. You don't think. the 'Big Boss'
PM: >would listen. to hours and hours of tapes, do you.
PM:. >
PM: >So, all in all, you couldn't actually do. the job for much less than
PM: >a quarter million a year. Over five years. What are you doing that. makes
PM: >it worth the while of the state to spend over one and a quarter. million
PM: >on. you?

Those are pretty much the sort of calculations that went through. my head
once I stopped to consider what it must be. costing them to run this
operation. The partial answer is,. there have been periods when the
intensity. has been greater, and times when little has happened. In fact,
for. much of 1993 and the first half of 1994, very little happened. Although
I. don't think that was for reasons of money - if they can tap into the
taxpayer they're not going to be short of resources,. are they?

The more complete answer is in the enormity of what. they're doing. Relative
to the cost to British pride of seeing their country humiliated. for the
persecution of their own citizens, isn't is worth the. cost of four or five
people to try. to bring things to a close in the manner they would wish? To
the government a million or. two is quite honestly nothing - if they can
convince themselves of the necessity of what. they're doing, resources will
not be the limiting. factor.

7633

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


Re: using super

2008-01-01 Thread iu2
On Jan 1, 9:59 am, Michele Simionato <[EMAIL PROTECTED]>
wrote:

> No PEP, this would never pass. There would be no way
> to stop a method from calling its parent: you would
> lose control of your classes, so I think this is a
> bad idea.

Not all classes, only classes the programmer chooses to have this
behaviour.

>Having said so, it is easy to implement
> what you want with a metaclass:
>
> def callParent(*methodnames):
>      class Meta(type):
>          def __init__(cls, name, bases, dic):
...
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree should parse string and file in the same way

2008-01-01 Thread Stefan Behnel
Peter Pei wrote:
> To be preise
[...]

Preise the lord, not me. :)

Happy New Year!

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


Re: using super

2008-01-01 Thread Steven D'Aprano
On Mon, 31 Dec 2007 22:56:41 -0800, iu2 wrote:

> Indeed I might want to chain methods in all sort of ways:
> @chain_call_before - call the parent's method before the derived method
> @chain_call_after - call the parent's method after the derived method
> @chain_call_sum - sum the result of the parent's method with the result
> of the derived method
> @chain_call_list - make a list from the result of the parent's method
> and the result of the derived method

Indeed there are all sorts of ways you might want to call the parent 
class' method. How about a 

@chain_call__multiply_by_seven_and_append_to_list

decorator?


[snip]

>>simply remind people to call
>> A.foo(self, ) within the definition of foo in B.
> 
> Sorry, I can't agree to this (although there is nothing else I can do.. 
> . Reminding is not "simply" at all. Why REMIND people do stuff and not
> let Python handle it automatically? 

But Python can't handle it automatically, not unless you do

import read_my_mind_and_do_what_I_want

first. (Module expected in Python 9.7, due out in 2058.)

Since you have to call the superclass yourself, there's not that much 
difference between reminding people to call the superclass by hand, and 
reminding them to call some decorator.

Admittedly, a decorator for the most common cases would be easier to use 
than super(), but I don't think it would make enough of a difference that 
it is worth changing Python's object model just to make it possible. As 
the Zen of Python says:

"Special cases aren't special enough to break the rules."

(or in this case, to change the rules).

And as others have pointed out, if you really want this desperately 
enough, you can create a metaclass to handle it.



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


Re: pdf library.

2008-01-01 Thread Piet van Oostrum
> Shriphani <[EMAIL PROTECTED]> (S) wrote:

>S> I tried pyPdf for this and decided to get the pagelinks. The trouble
>S> is that I don't know how to determine whether a particular page is the
>S> first page of a chapter. Can someone tell me how to do this ?

AFAIK PDF doesn't have the concept of "Chapter". If the document has an
outline, you could try to use the first level of that hierarchy as the
chapter starting points. But you don't have a guarantee that they really
are chapters.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


M,I-5,Persecu tion w ho kn ows abou t it?

2008-01-01 Thread vivfvfifi
-=-=-=-=-=-=-=-=-=-=-=-=-
-= who knows about it?. =-
-=-=-=-=-=-=-=-=-=-=-=-=-

Many people know, both in the establishment and media, and. among the
general. public. Despite an absence of its target from the UK for more than
two years, the echoes of paranoia can still. be heard loud and clear from
across the water. When it started in 1990, the only. people who knew were
those in BBC television who were. spying on my home, and a few radio
broadcasters. There were a few cases of public harassment, but. very little
compared to the situation that developed a couple of years. later.

The list today includes BBC. TV staff (newsreaders such as Martyn Lewis,
Michael Buerk, Nicholas. Witchell), people from radio stations such as
Chris Tarrant of Capital and. Radio 1 DJs, people in the print media, but
also many. people in the general public. All united in a conspiracy which
breaks the laws which the UK does have regarding. harassment, and all
completely uncaring for any semblance. of decency or elementary respect
for. individual rights.

The British police (obviously) do know the nature of the. harassment and in
all probability the identity of those behind. it. Some time ago I made a
complaint to my local police station in London, without positive. result.
The UK police are failing in their. duty to see the law enforced in not
checking the. abuse.

2773

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


M-I,5`Persecution ` B ernard Levin expre sses hi s vie ws

2008-01-01 Thread eieimemiv

The article of which part. is reproduced below was penned by Bernard Levin
for the. Features section of the Times on 21 September 1991. To my mind, it
described the situation at the time and in particular a recent. meeting with
a friend, during which I for the first time admitted to someone. other than
my GP that I had. been subjected to a conspiracy of harassment over the
previous year. and a half.

>There is a madman running loose about. London, called David Campbell; I have
>no reason to believe. that he is violent, but he should certainly be
>approached with caution. You may. know him by the curious glitter in his
>eyes and a persistent. trembling of his hands; if that does not suffice, you
>will find him attempting to thrust no fewer than 48 books. into your arms,
>all hardbacks, with a promise that, if you should return to the. same
>meeting-place next year, he will heave. another 80 at you.
>
>If, by now, the police have arrived and are keeping a close watch on. him,
>you may. feel sufficiently emboldened to examine the books. The jackets are
>a. model of uncluttered typography, elegantly and simply laid out; there is
>an unobtrusive colophon of. a rising sun, probably not picked at random.
>Gaining confidence - the lunatic is smiling by now, and. the policemen, who
>know about such things, have. significantly removed their helmets - you
>could do. worse than take the jacket off the first book in the pile. The
>only. word possible to describe the binding is sumptuous; real cloth in a
>glorious shade of dark green, with the title and author in black. and gold
>on. the spine.
>
>Look at it more closely; your eyes do not deceive you - it truly does. have
>real top-bands and tail-bands, in yellow,. and, for good measure, a silk
>marker ribbon in a lighter green. The. paper is cream-wove and acid-free,
>and the book is sewn,. not glued.
>
>Throughout the encounter, I. should have mentioned, our loony has been
>chattering away, although what he. is trying to say is almost impossible to
>understand; after a time, however, he becomes sufficiently coherent to. make
>clear that he. is trying to sell the books to you. Well, now, such quality
>in. bookmaking today can only be for collectors' limited editions at a
>fearsome price -. #30, #40, #50?
>
>No, no, he. says, the glitter more powerful than ever and the trembling of
>his hands rapidly. spreading throughout his entire body; no, no - the books
>are priced variously at. #7, #8 or #9, with the top price #12.
>
>At this, the policemen understandably put their helmets. back on; one of
>them draws his truncheon and the. other can be heard summoning
>reinforcements on his walkie-talkie. The madman. bursts into tears, and
>swears it is all. true.
>
>And. it is.
>
>David Campbell has. acquired the entire rights to the whole of the
>Everyman's. Library, which died a lingering and shameful death a decade or
>so ago, and he proposes to start it. all over again - 48 volumes this
>September. and 80 more next year, in editions I have described, at the
>prices specified.. He proposes to launch his amazing venture simultaneously
>in Britain and the. United States, with the massive firepower of Random
>Century at his back in this country, and the dashing cavalry of. Knopf
>across the water, and no. one who loves literature and courage will forbear
>to. cheer.

At the time this article was written I had believed for. some time that
columnists in the Times and. other journalists had been making references to
my situation. Nothing. unusual about this you may think, plenty of people
have the same sort of ideas. and obviously the papers aren't writing about
them, so why should my beliefs not be as false. as those of others?

What makes this article. so extraordinary is that three or four days
immediately preceding its publication, I had a meeting with. a friend,
during the course of. which we discussed the media persecution, and in
particular that by Times columnists. It seemed to. me, reading the article
by Levin in Saturday’s. paper, that he was describing in some detail his
"artist’s impression" of that. meeting. Most telling are the final
sentences, when. he writes, "The madman bursts into tears, and swears it is
all true. And it is." Although I did not "burst into tears" (he. seems to be
using a bit of. poetic licence and exaggerating) I did try hard to convince
my friend that it was all true; and. I am able to concur with Mr Levin,
because, of. course, it is.

At the beginning of the piece Levin reveals a. fear of being attacked by the
"irrational" subject of his. story, saying "I have no reason to believe that
he is violent, but. he should certainly be approached with caution". This
goes back. to the xenophobic propaganda of "defence" against a "threat"
which was seen at the very beginning of the harassment. The impression. of a
"madman running loose" who needs to be controlled through. an agency which
assigns to itself the mantle. of the "police" is also one which had 

Re: pdf library.

2008-01-01 Thread Shriphani
On Jan 1, 4:28 pm, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
> >Shriphani<[EMAIL PROTECTED]> (S) wrote:
> >S> I tried pyPdf for this and decided to get the pagelinks. The trouble
> >S> is that I don't know how to determine whether a particular page is the
> >S> first page of a chapter. Can someone tell me how to do this ?
>
> AFAIK PDF doesn't have the concept of "Chapter". If the document has an
> outline, you could try to use the first level of that hierarchy as the
> chapter starting points. But you don't have a guarantee that they really
> are chapters.
> --
> Piet van Oostrum <[EMAIL PROTECTED]>
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: [EMAIL PROTECTED]

How would a pdf to html conversion work ? I've seen Google's search
engine do it loads of times. Just that running a 500odd page ebook
through one of those scripts might not be such a good idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree should parse string and file in the same way

2008-01-01 Thread Diez B. Roggisch
Steven D'Aprano schrieb:
> On Tue, 01 Jan 2008 01:53:47 +, Peter Pei wrote:
> 
>> You are talking shit. It is never about whether it is hard to write a
>> wrapper. It is about bad design. I should be able to parse a string and
>> a file in exactly same way, and that should be provided as part of the
>> package.
> 
> Oh my, somebody decided to start the new year with all guns blazing.
> 
> Before abusing anyone else, have you considered asking *why* ElementTree 
> does not treat files and strings the same way? I believe the writer of 
> ElementTree, Fredrik Lundh, frequents this newsgroup.
> 
> It may be that Fredrik doesn't agree with you that you should be able to 
> parse a string and a file the same way, in which case there's nothing you 
> can do but work around it. On the other hand, perhaps he just hasn't had 
> a chance to implement that functionality, and would welcome a patch.
> 
> Fredrik, if you're reading this, I'm curious what your reason is. I don't 
> have an opinion on whether you should or shouldn't treat files and 
> strings the same way. Over to you...

I think the decision is pretty clear to everybody who is a code-monkey 
and not a Peter-Pei-School-of-Excellent-And-Decent-Designers-attendant:

when building a XML-document, you start from a Element or Elementtree 
and often do things like


root_element = 
for child in some_objects:
 root_element.append(XML("" % 
child.attribute))

Which is such a common usage-pattern that it would be extremely annoying 
to get a document from XML/fromstring and then needing to extract the 
root-element from it.

And codemonkeys know that in python

doc = et.parse(StringIO(string))

is just one import away, which people who attend to 
Peter-Pei-School-of-Excellent-And-Decent-Designers may have not learned 
yet - because they are busy praising themselves and coating each other 
in edible substances before stepping out into the world and having all 
code-monkeys lick off their greatness in awe.

http://www.youtube.com/watch?v=FM7Rpf1x7RU

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


Re: pdf library.

2008-01-01 Thread Marc 'BlackJack' Rintsch
On Tue, 01 Jan 2008 04:21:29 -0800, Shriphani wrote:

> On Jan 1, 4:28 pm, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
>> >Shriphani<[EMAIL PROTECTED]> (S) wrote:
>> >S> I tried pyPdf for this and decided to get the pagelinks. The trouble
>> >S> is that I don't know how to determine whether a particular page is the
>> >S> first page of a chapter. Can someone tell me how to do this ?
>>
>> AFAIK PDF doesn't have the concept of "Chapter". If the document has an
>> outline, you could try to use the first level of that hierarchy as the
>> chapter starting points. But you don't have a guarantee that they really
>> are chapters.
>
> How would a pdf to html conversion work ? I've seen Google's search
> engine do it loads of times. Just that running a 500odd page ebook
> through one of those scripts might not be such a good idea.

Heuristics?  Neither PDF nor HTML know "chapters".  So it might be
guesswork or just in your head.

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


M I-5'Per secution Be rnard Levi n ex presses hi s views

2008-01-01 Thread mfefe

The article of which part is reproduced below. was penned by Bernard Levin
for the Features section of the Times on 21 September 1991. To my. mind, it
described the situation at the time. and in particular a recent meeting with
a friend,. during which I for the first time admitted to someone other than
my GP that I had been subjected to a conspiracy of. harassment over the
previous. year and a half.

>There is a madman running loose about London, called David. Campbell; I have
>no reason to believe that he is. violent, but he should certainly be
>approached with caution. You. may know him by the curious glitter in his
>eyes and a. persistent trembling of his hands; if that does not suffice, you
>will find. him attempting to thrust no fewer than 48 books into your arms,
>all hardbacks, with a promise that, if. you should return to the same
>meeting-place next. year, he will heave another 80 at you.
>
>If, by now, the police have arrived and are keeping a close watch. on him,
>you may feel. sufficiently emboldened to examine the books. The jackets are
>a model of uncluttered typography,. elegantly and simply laid out; there is
>an unobtrusive colophon of. a rising sun, probably not picked at random.
>Gaining confidence - the lunatic is smiling by now,. and the policemen, who
>know about such things, have significantly. removed their helmets - you
>could do worse than take the jacket off the first book in the. pile. The
>only word possible to describe the binding is sumptuous; real cloth in. a
>glorious shade of dark green,. with the title and author in black and gold
>on the. spine.
>
>Look at it more closely; your eyes do not deceive. you - it truly does have
>real top-bands and tail-bands,. in yellow, and, for good measure, a silk
>marker ribbon in a lighter green. The paper is cream-wove and. acid-free,
>and the book is. sewn, not glued.
>
>Throughout the encounter, I should have mentioned,. our loony has been
>chattering away, although what he is trying to. say is almost impossible to
>understand;. after a time, however, he becomes sufficiently coherent to make
>clear that he is trying to sell the books to you. Well,. now, such quality
>in bookmaking today can only be for collectors' limited editions at. a
>fearsome price - #30, #40,. #50?
>
>No, no, he says, the glitter more powerful than ever. and the trembling of
>his hands rapidly spreading throughout his. entire body; no, no - the books
>are priced variously. at #7, #8 or #9, with the top price #12.
>
>At this, the policemen understandably put their helmets back on; one. of
>them draws his truncheon and the other can be. heard summoning
>reinforcements on. his walkie-talkie. The madman bursts into tears, and
>swears it is. all true.
>
>And it. is.
>
>David Campbell has acquired the entire rights to the whole. of the
>Everyman's Library, which. died a lingering and shameful death a decade or
>so ago, and he proposes to start it all over again. - 48 volumes this
>September and 80 more next year, in editions I have described, at. the
>prices. specified. He proposes to launch his amazing venture simultaneously
>in Britain and. the United States, with the massive firepower of Random
>Century at his back in this country,. and the dashing cavalry of Knopf
>across the water, and no one who loves. literature and courage will forbear
>to. cheer.

At the time this article was written I had. believed for some time that
columnists in the Times. and other journalists had been making references to
my situation. Nothing unusual about this you may think,. plenty of people
have the same sort of. ideas and obviously the papers aren't writing about
them, so why should my beliefs not be as false as those. of others?

What makes this article so extraordinary is that three or. four days
immediately preceding. its publication, I had a meeting with a friend,
during the course of which. we discussed the media persecution, and in
particular that by Times. columnists. It seemed to me, reading the article
by Levin in Saturday’s paper, that he. was describing in some detail his
"artist’s impression" of that meeting. Most telling are. the final
sentences, when he writes, "The madman bursts into tears,. and swears it is
all true. And it is." Although I did not "burst into tears". (he seems to be
using a bit of poetic licence and exaggerating). I did try hard to convince
my friend that it was all true;. and I am able to concur with Mr Levin,
because,. of course, it is.

At the beginning of. the piece Levin reveals a fear of being attacked by the
"irrational" subject of his story, saying "I have no reason to. believe that
he is. violent, but he should certainly be approached with caution". This
goes back to the xenophobic. propaganda of "defence" against a "threat"
which was seen at the very beginning. of the harassment. The impression of a
"madman running loose" who needs to be. controlled through an agency which
assigns to itself the mantle of. the "police" is also one which had 

Network Module

2008-01-01 Thread Sunil Ghai
Hello people,
I am searching for a python module to interact with the network
connections/interfaces. For example the number of active TCP/IP connections
via eth0 interface and all that stuff.
I have done googling and search at pythonorg but couldn't find any.

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

Re: using super

2008-01-01 Thread iu2
On Jan 1, 12:32 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
>
> import read_my_mind_and_do_what_I_want
>
> first. (Module expected in Python 9.7, due out in 2058.)

That's because it seems to you like some esoteric feature.
To me it seems natural with OO.


> "Special cases aren't special enough to break the rules."

I thought about this mechanism each time I had to call a base class
method.
Lisp has it, out of the box.
May be it's not so special...


> Since you have to call the superclass yourself, there's not that much
> difference between reminding people to call the superclass by hand, and
> reminding them to call some decorator.

Not necessarily. Once a class is declared with chains, its
deriveratives don't really need the decorator (Python will know about
it).
And even with a decorator, what if the class has 5 methods? That's one
decorator against 5 superclass calls.

> Admittedly, a decorator for the most common cases would be easier to use
> than super(), but I don't think it would make enough of a difference that
> it is worth changing Python's object model just to make it possible. As
>  ...
> And as others have pointed out, if you really want this desperately
> enough, you can create a metaclass to handle it.
>
That's right.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree should parse string and file in the same way

2008-01-01 Thread Steven D'Aprano
On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote:

> And codemonkeys know that in python
> 
> doc = et.parse(StringIO(string))
> 
> is just one import away

Yes, but to play devil's advocate for a moment, 

doc = et.parse(string_or_file)

would be even simpler.

Is there any reason why it should not behave that way? It could be as 
simple as adding a couple of lines to the parse method:

if isinstance(arg, str):
import StringIO
arg = StringIO(arg)

I'm not saying it *should*, I'm asking if there's a reason it *shouldn't*.

"I find it aesthetically distasteful" would be a perfectly acceptable 
answer -- not one I would agree with, but I could accept it.



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


Code - working in one system and not working in the other.

2008-01-01 Thread Amal
The following code works in a system with python 2.4.3 and does not work in
the system with python 2.4.2.

And both the systems directly connect to the internet.

import urllib2

url = "http://www.abcd.com";
username = "abcd"
passowrd = "efgh"


password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, url, username, passowrd)

authHandler = urllib2.HTTPBasicAuthHandler(password_manager)

opener = urllib2.build_opener(authHandler)

urllib2.install_opener(opener)

pagehandle = urllib2.urlopen(url)

s =  pagehandle.read()

print s

url = url+"current/"

pagehandle = urllib2.urlopen(url)

s =  pagehandle.read()
print s

url = url+"20071128.zip"

pagehandle = urllib2.urlopen(url)

fp = open("hello.zip", 'wb')
a = pagehandle.readline();
while a != "":
fp.write(a)
a = pagehandle.readline();

#fp.write(pagehandle.read())
fp.close()

in the system it does not run, it gives a urllib2.HTTPError : HTTP Error
401: Authorization required ecception.
With the same user name and password the code runs in another system.


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

SVGDraw is where?

2008-01-01 Thread Shane Geiger
Does someone know where SVGDraw has gone?  It used to be here: 
http://www2.sfk.nl/svg/

Googling hasn't helped me locate it.  :-\

-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

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


Re: how to connect to a remote machine using python........ pexpect help

2008-01-01 Thread vinoj davis





  Hi,My aim is to connect to a remote machine and execute commands at the remote machine.. such as ifconfig... i found out a module named pexpect if anyone can help me out in thatThanking youRegards,     ---ViNOJ DAViS---Regards,     ---ViNOJ DAViS---


   Forgot the famous last words? Access your message archive online. Click here.

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

Using mouse

2008-01-01 Thread Lucas Prado Melo
I would like to control mouse events (i.e. I would like to "click" and
move mouse around by code).
How do I do this in python?

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


WXPython - Using inline images

2008-01-01 Thread Sick Monkey
I have a question about WXPython and using inline images.  The code that I
have included into this email comes from the following URL:
http://www.daniweb.com/code/snippet654.html

As you can see from the code below, that this application will take an
inline JPG image, and will create a local copy of the image called
zzz777.jpg.  Is there anyway WXPython can just use the inline image without
having to create a physical copy?  I know this can be done in TKinter using
inline gifs, but was wondering if anyone knew of a clever way to do this in
WXPython?

---
CODE
--
import wx
import cStringIO
import base64
BG_Egypt_jpg_b64='''\
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU
FhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo
KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgACADASIA

AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm

p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK

U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB2taqm
lRI7pAsCxQDi0WVizqo7KzEln9+v55f/AAlsZ/5dp+f+oI//AMa9/wDPc8c8wW3f97p3v/HD9f8A

P66mtaqmlRI7pAsCxQDi0WVizqo7KzEln9+v5+J9+9tDQy/+EtjP/LtPz/1BH/8AjXv/AJ7x67q0
9xo8Lxp5AlurUc2ggk2mdAeCoYAgn6g9wea2r+Inv7aK3tILpZZLm3yV0t4fl85C2X8sYG3OeeQS
O/N3xzzBbd/3une/8cP1/wA/qbWab36gHjnmC27/AL3Tvf8Ajh+v+f1PHPMFt3/e6d7/AMcP1/z+

uXr2sDV1hRIb553urU86fLGoVJYz3QKAFH+e+hresafcXapJDfSiHyDxYTsvmRhCOQhDAMo9QfcH
k1te3W4Fu98UW0E/kQW8xWNEQkaQ7gsFAb5vLO75ieckHtnvia9rA1dYUSG+ed7q1POnyxqFSWM9
0CgBR/nvqf8ACWxn/l2n5/6gj/8Axr3/AM9z/hLYz/y7T8/9QR//AI17/wCe58mB/9k=
'''
jpg1 = base64.b64decode(BG_Egypt_jpg_b64)
# save the image to a file ...
# (couldn't figure out any other way to use with wx.Bitmap)
tile_file = "zzz777.jpg"
fout = open(tile_file, "wb")
fout.write(jpg1)
fout.close()

self.bmp1 = wx.Bitmap(tile_file)
wx.EVT_PAINT(self, self.on_paint)
-
-- 
http://mail.python.org/mailman/listinfo/python-list

File Info

2008-01-01 Thread Navid Parvini
Dear All,

Would you please tell me if there is another function instead of stat that 
gives the same information ( such as the size of the file) but faster?

Thank you in advance.
Navid

   
-
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Using mouse

2008-01-01 Thread Grant Edwards
On 2007-12-31, Lucas Prado Melo <[EMAIL PROTECTED]> wrote:

> I would like to control mouse events (i.e. I would like to
> "click" and move mouse around by code). How do I do this in
> python?

http://python-xlib.sourceforge.net/doc/html/python-xlib_14.html

-- 
Grant Edwards   grante Yow!  Pardon me, but do you
  at   know what it means to be
   visi.comTRULY ONE with your BOOTH!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tab indentions on different platforms?

2008-01-01 Thread Steven D'Aprano
On Mon, 31 Dec 2007 12:36:11 +1100, Ben Finney wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
> 
>> On Sun, 30 Dec 2007 20:41:09 +, Thorsten Kampe wrote:
>> 
>> > Anyway: the consequence of your well done argumentation is that
>> > someone editing Python code has to use a specialised editor to
>> > prevent screwing up tab indented code - and that's bad.
>> 
>> You just need to use an editor that inserts tab characters when the tab
>> key is pressed, just like you use an editor that inserts s characters
>> when the s key is pressed.
> 
> No, that's not all you need to do. You also need to keep your code away
> from the majority of programmers, who use their default editor in its
> default settings

I question that. On my system at least (Fedora 7), here are the default 
settings on the editors I have available:

vi  default is tab character
emacs   default is tab character
gedit   default is tab character
nanodefault is tab character
joe default is tab character
kedit   always uses tab character
kwrite  default is tab character
katedefault is tab character
scribes default is tab character
eclipse default is tab character

With every Linux distro being slightly different, your mileage may vary, 
but with not even a single editor on my system defaulting to spaces, I 
hope you can excuse my skepticism.

And if you extend your view to the 90% of the computing world that 
doesn't use a Unix-like operating system, we can consider:

VisualStudiodefault is tab character
Epsilon default is tab character
Notepad always uses tab character
Wordpad always uses tab character

No doubt there are a hundred other Windows text editors, but I'm not 
familiar with them. Nor am I familiar with OS X based text editors, 
although back in the 1990s Apple Mac text editors invariably inserted a 
tab when you pressed the tab key.



> and who expect that horizontal whitespace is produced
> by the U+0020 space character (even if they don't know the specifics of
> the character coding).
> 
> Saying that the tabs-only argument and the spaces-only argument are of
> equal value is philosophically true, but practically worthless. They're
> of equal value *only* in isolated environments where you can control the
> expectations of *every* programmer who will *ever* edit the file.

Ah, and now we're getting somewhere! It's not so much that tabs are 
intrinsically harmful (as people like Thorsten keep insisting), but that 
in a world supposedly dominated by people who indent with spaces, using 
tabs might lead to inconsiderate programmers ignoring your project's 
coding standards and inserting spaces into your code base.

Yes, I can see that is a problem. I believe it is best solved by refusing 
contributions from such inconsiderate programmers. After all, if they're 
going to ignore your project's code standards in one aspect, they're 
invariably going to ignore others as well.

Ben, I'm surprised that you of all people should take such a pragmatic 
view that "tabs are bad because the majority use spaces". By that 
reasoning, you should be driving a SUV (much safer than riding a bike!), 
sending HTML-only emails written in Outlook (with Word as your editor 
naturally) and publishing data solely in proprietary binary formats 
like .doc. Everybody else does it, why buck the trend?

There's a very good reason to buck the trend whenever practical: tabs 
have the considerable benefit that they decouple the presentation of the 
code from the structure of the code.

When you use tabs to indent code, the reader can place their tab stops 
where ever they wish, according to their own needs and preferences: every 
eight spaces, or four, or three, or twenty-seven spaces if they want. One 
tab means one indent level (structure), and the width of that indent 
(presentation) is up to the reader.

But when you use spaces, you are essentially forcing your presentation 
onto all your readers, whatever their wishes. Sure, some editors let you 
re-indent code at the press of a button, and some of them might even get 
it right more often than not -- but for Python at least, if you want to 
contribute code back to the project, you can't afford to do that. You're 
stuck using whatever presentation the project manager chooses.

Using spaces is fundamentally broken because it turns a structural single 
level of indentation into a presentational four spaces -- or eight, or 
two, or five, whatever the project's coding standard insists on.


> To form an indentation policy based only on hypothetical
> fully-controlled isolated environments is foolish, to say the least.

Just say I'm tilting at windmills.



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


Re: TK 8.5

2008-01-01 Thread Leon
> We are planing to use Tcl/Tk 8.5 for Python 2.6 and 3.0. The topic is
> currently being discussed but nothing has been decided yet.

Great news!
I hope you'll decide to use Tcl/Tk 8.5 !
I'm sure I'm not the only one !!!

On this page : http://www.python.org/dev/peps/pep-0361/

We can read : "the initial 2.6 target is for April 2008"

Great !

But I found nothing about Tk 8.5 ?

Leon


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


Re: Tab indentions on different platforms?

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

Steven D'Aprano writes:

> [...]
>
> Ah, and now we're getting somewhere! It's not so much that tabs
> are intrinsically harmful (as people like Thorsten keep
> insisting), but that in a world supposedly dominated by people who
> indent with spaces, using tabs might lead to inconsiderate
> programmers ignoring your project's coding standards and inserting
> spaces into your code base.
>
> Yes, I can see that is a problem. I believe it is best solved by
> refusing contributions from such inconsiderate programmers. After
> all, if they're going to ignore your project's code standards in
> one aspect, they're invariably going to ignore others as well.

No, you cannot have both tabs and spaces.  The whole community must
settle on a single method.  I cannot adjust my editor's settings to
the respective SVN tree I'm looking at, nor can I incorporate other
project's code into mine if the indentation method is not the same.

Of course, there is no intrinsic benefit from spaces but it is the
method that has won.

Tschö,
Torsten.

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


Re: Cheat sheet

2008-01-01 Thread Riccardo T.
Riccardo T. ha scritto:
> I wrote a little cheat sheet for this wonderful language, but because of
> my still little experience with it, I would like to have a feedback
> Could you have a look at it and tell me what do you think about, please?
> 
> http://greyfox.imente.org/index.php?id=73
> 
> --
> GreyFox

Thanks to all your advices, the new version is now available. There's a
new gif file with less graphic that you can download faster.


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



Re: Choosing a new language

2008-01-01 Thread Joachim Durchholz
> Xah Lee <[EMAIL PROTECTED]> wrote:
>> [...] PHP and Perl are practically identical in their
>> high-levelness or expressiveness or field of application (and
>> syntax),

That must have been a very, very distant point of view with narrowly 
squinted eyes.

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


Re: Bizarre behavior with mutable default arguments

2008-01-01 Thread bukzor
On Dec 30 2007, 11:01 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 30 Dec 2007 20:00:14 -0800, bukzor wrote:
> > I think you struck at the heart of the matter earlier when you noted
> > that this is the simplest way to declare a static variable in python.
> > Using the 'global' keyword is the other way, and is much more explicit,
> > and much more widely used. I also see this as the main use of the
> > 'notlocal' keyword to be introduced in py3k (it also fixes the example
> > given by Istvan above).
>
> There doesn't appear to be any reference to a "notlocal" keyword in
> Python 3 that I can find. Have I missed something? It sounds like an
> April Fool's gag to me. Do you have a reference to a PEP or other
> official announcement?
>
> --
> Steven

I got it slightly wrong. It's 'nonlocal':
http://www.python.org/dev/peps/pep-3104/

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


Re: pexpect ssh login and ls | grep

2008-01-01 Thread Dikkie Dik
> shell_cmd = 'ls -l | grep mytest.log'
> child = pexpect.spawn ('ssh [EMAIL PROTECTED]')


I think you can give the ssh command an option to execute a file 
remotely. That way, one command would be enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK 8.5

2008-01-01 Thread Martin v. Löwis
> But I found nothing about Tk 8.5 ?

Python is not tied to any specific Tk version; you can use
any Python release with any Tk version, most of the time.

Hence, there is no need to talk about this very much. That
Python "supports" Tk 8.5 is too minor to mention - I think
even Python 2.4 supports Tk 8.5.

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


Re: Bizarre behavior with mutable default arguments

2008-01-01 Thread bukzor
On Dec 31 2007, 1:30 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> On Dec 31, 2007 2:08 PM, Odalrick <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 31 Dec, 18:22, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> > > On Dec 31, 10:58 am, Odalrick <[EMAIL PROTECTED]> wrote:
>
> > > > On 30 Dec, 17:26, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > > > > On Dec 29, 9:14 pm, bukzor <[EMAIL PROTECTED]> wrote:
>
> > > > > > Here's the answer to the 
> > > > > > question:http://www.python.org/doc/faq/general/#why-are-default-values-shared-...
>
> > > > > > It looks like Guido disagrees with me, so the discussion is closed.
>
> > > > > Note that the FAQ mainly explains *what* happens, not *why* was this
> > > > > decision taken. Although it shows an example where "this feature can
> > > > > be useful", it's neither the only way to do it nor is memoization as
> > > > > common as wanting fresh default arguments on every call.
>
> > > > I'm surprised noone has said anything about the why of default
> > > > mutables. I think it is becasue it isn't easy to do it an other way.
>
> > > [...]
>
> > > There is an easy enough way: evaluate default values when the function
> > > is called rather than when it is defined.  This behaviour comes with
> > > its own caveats as well I imagine, and it's not 'as easy' to implement
> > > as the current one.
>
> > Adding overhead to *all* function calls, even the ones without mutable
> > defaults. That doesn't sound like an attractive tradeoff.
>
> And also removing the only way you can currently do early binding in
> Python. I agree that it's a gotcha, but unless someone comes up with
> an answer to the following questions, I'll stick with the status quo
> (Note that this is not blind Python group-think as a previous poster
> implied, but a pragmatic decision that this is the most practical
> solution):
>
> a) If we don't evaluate default arguments at function compilation,
> when do we do it?
> b) If you do it at call time, how do you implement early binding?
> c) If you want to introduce new syntax for the current behavior, what
> is it and can you justify it?
> d) What are the performance implications of your proposal versus the
> current behavior?
>
> Note that the desired behavior can be implemented under the current
> behavior, at the expense of verbosity - using factories and sentinel
> values as the default arguments, and then expanding them in the
> function. It's not possible to implement the current behavior of
> early-bound arguments if default arguments are evaluated with every
> call. This alone is a good reason to keep the current behavior until
> someone actually has a good alternative that covers the current use
> cases and isn't just upset by the behavior.

I'm confused by what you mean by 'early binding'. Can you give a quick-
n-dirty example?

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


Re: Bizarre behavior with mutable default arguments

2008-01-01 Thread Neil Cerutti
On Jan 1, 2008 12:26 AM, NickC <[EMAIL PROTECTED]> wrote:

> On Jan 1, 3:22 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> > On Dec 31, 10:58 am, Odalrick <[EMAIL PROTECTED]> wrote:
> >
> > > I'm surprised noone has said anything about the why of default
> > > mutables. I think it is becasue it isn't easy to do it an other way.
> >
> > [...]
> >
> > There is an easy enough way: evaluate default values when the function
> > is called rather than when it is defined.  This behaviour comes with
> > its own caveats as well I imagine, and it's not 'as easy' to implement
> > as the current one.
>
> As Odalrick notes, there is no way to give different calls to a
> function their own copies of mutable default arguments without re-
> evaluating the defaults every time the function is called.


There's a policy solution: stipulate that default arguments must be
immutable (or hashable, as Python prefers to call it).

The
> horrendous performance implications mean that that simply isn't going
> to happen.


Are the performance implications truly horrendous, though? Considering that
the "poorly performing" solution seems to be the functionality that the
uninformed expect, perhaps they *want* it to perform that way?

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

Re: WXPython - Using inline images

2008-01-01 Thread Vlastimil Brom
2007/12/31, Sick Monkey <[EMAIL PROTECTED]>:
...
Is there anyway WXPython can just use the inline image without having to
create a physical copy? I know this can be done in TKinter using inline
gifs, but was wondering if anyone knew of a clever way to do this in
WXPython?
...

I think, you can use a stream and wx.ImageFromStream for that
see the wxPython Demo ...\demo\images.py for some examples.

Greetings,
Vlasta
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Using mouse

2008-01-01 Thread Gabriel Genellina
En Tue, 01 Jan 2008 12:54:54 -0200, Grant Edwards <[EMAIL PROTECTED]>  
escribi�:

> On 2007-12-31, Lucas Prado Melo <[EMAIL PROTECTED]> wrote:
>
>> I would like to control mouse events (i.e. I would like to
>> "click" and move mouse around by code). How do I do this in
>> python?
>
> http://python-xlib.sourceforge.net/doc/html/python-xlib_14.html

On Windows, use the mouse_event function  
http://msdn2.microsoft.com/en-us/library/ms646260.aspx
Available on pywin32 https://sourceforge.net/projects/pywin32/ or using  
ctypes directly.

-- 
Gabriel Genellina

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

Re: Bizarre behavior with mutable default arguments

2008-01-01 Thread bukzor
On Jan 1, 9:00 am, bukzor <[EMAIL PROTECTED]> wrote:
> On Dec 31 2007, 1:30 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 31, 2007 2:08 PM, Odalrick <[EMAIL PROTECTED]> wrote:
>
> > > On 31 Dec, 18:22, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> > > > On Dec 31, 10:58 am, Odalrick <[EMAIL PROTECTED]> wrote:
>
> > > > > On 30 Dec, 17:26, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > > > > > On Dec 29, 9:14 pm, bukzor <[EMAIL PROTECTED]> wrote:
>
> > > > > > > Here's the answer to the 
> > > > > > > question:http://www.python.org/doc/faq/general/#why-are-default-values-shared-...
>
> > > > > > > It looks like Guido disagrees with me, so the discussion is 
> > > > > > > closed.
>
> > > > > > Note that the FAQ mainly explains *what* happens, not *why* was this
> > > > > > decision taken. Although it shows an example where "this feature can
> > > > > > be useful", it's neither the only way to do it nor is memoization as
> > > > > > common as wanting fresh default arguments on every call.
>
> > > > > I'm surprised noone has said anything about the why of default
> > > > > mutables. I think it is becasue it isn't easy to do it an other way.
>
> > > > [...]
>
> > > > There is an easy enough way: evaluate default values when the function
> > > > is called rather than when it is defined.  This behaviour comes with
> > > > its own caveats as well I imagine, and it's not 'as easy' to implement
> > > > as the current one.
>
> > > Adding overhead to *all* function calls, even the ones without mutable
> > > defaults. That doesn't sound like an attractive tradeoff.
>
> > And also removing the only way you can currently do early binding in
> > Python. I agree that it's a gotcha, but unless someone comes up with
> > an answer to the following questions, I'll stick with the status quo
> > (Note that this is not blind Python group-think as a previous poster
> > implied, but a pragmatic decision that this is the most practical
> > solution):
>
> > a) If we don't evaluate default arguments at function compilation,
> > when do we do it?
> > b) If you do it at call time, how do you implement early binding?
> > c) If you want to introduce new syntax for the current behavior, what
> > is it and can you justify it?
> > d) What are the performance implications of your proposal versus the
> > current behavior?
>
> > Note that the desired behavior can be implemented under the current
> > behavior, at the expense of verbosity - using factories and sentinel
> > values as the default arguments, and then expanding them in the
> > function. It's not possible to implement the current behavior of
> > early-bound arguments if default arguments are evaluated with every
> > call. This alone is a good reason to keep the current behavior until
> > someone actually has a good alternative that covers the current use
> > cases and isn't just upset by the behavior.
>
> I'm confused by what you mean by 'early binding'. Can you give a quick-
> n-dirty example?
>
> Thanks,
> --Buck

Is an 'early bound' variable synonymous with a 'static' variable (in
C)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect ssh login and ls | grep

2008-01-01 Thread crybaby
I don't get 0 or 2(excuting ls command exit code)
from result.split('\r\n')[0] or result.split('\r\n')[1].  I have to
try another method.

Regular shell ssh login:

[EMAIL PROTECTED] ~]$ ssh [EMAIL PROTECTED]
Last login: Mon Dec 31 20:51:09 2007 from com1
[EMAIL PROTECTED] ~]$

Pexpect Login:
>>> import pexpect
>>> child=pexpect.spawn("ssh [EMAIL PROTECTED]")
>>> child.sendline("ls mytest.log > /dev/null 2>&1; echo $? ")
42
>>> child.expect([pexpect.TIMEOUT, r"\$"])
1
>>> result1=child.before
>>> result2=child.after
>>> print result1
Last login: Tue Jan  1 11:22:05 2008 from com1
[EMAIL PROTECTED] ~]
>>> print result2
$
>>> print result1.split('\r\n')[1]
[EMAIL PROTECTED] ~]
>>> print result1.split('\r\n')[0]
Last login: Tue Jan  1 11:22:05 2008 from com1

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


Re: using super

2008-01-01 Thread Scott David Daniels
iu2 wrote:
> On Jan 1, 12:32 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> import read_my_mind_and_do_what_I_want
>> first. (Module expected in Python 9.7, due out in 2058.)
> 
> That's because it seems to you like some esoteric feature.
> To me it seems natural with OO.
And the language should not bend to the sense of "natural" of one with
a minor commitment to building that language.  If this really is a
great idea, implement it, put it out, support it and respond to the
rigors of real use.  You'll not convince me, but you needn't.  Too
many people want to go to a PEP (or even skip that step) once they have
an idea they think might be good.

The lesson I take from the histories of Ada and C++ are that "the
less in the language the better."  It is not enough that a language
be chock-a-block with good ideas; each idea in the language must be
compelling enough to counter-balance the mass that adding that idea
adds.

>> "Special cases aren't special enough to break the rules."
> 
> I thought about this mechanism each time I had to call a base class
> method.  Lisp has it, out of the box.  May be it's not so special...

We accept this seems natural to you.  You don't seem to understand why
others might not think so.  I fear this is the kind of thing that
separates programmers into two classes: the smart ones that can set up
the chains, and the others to whom you say "don't worry your pretty
little head about it; it all happens auto-magically."  Python is
remarkably free of such things, and I am loathe to give that up.
The value reduced auto-magic is that the users of the language
can learn smoothly, rather than climbing steep mountains of 
understanding.  Since you are relatively new to the language (I
presume so, since you left self out of several method definitions),
see how the language works on its terms first, before suggesting
how to make it more like some other language you like.

The explicit super call inside a method, and the disposition of
its results makes experimentation with different ways to use the
result tempting.  There is a temptation to play with the arguments
as well, that runs afoul of the vagaries of multiple inheritance,
that is the reason that I said "if they don't want to understand
super, then just explicitly name the superclass."

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using mouse

2008-01-01 Thread Scott David Daniels
Lucas Prado Melo wrote:
> I would like to control mouse events (i.e. I would like to "click" and
> move mouse around by code).
> How do I do this in python?

A python doesn't have a mouse for long; it eats them up.

It is your display and user I/O system that deals with mice,
and so, inevitably, the answer to your question (and, indeed
whether such a thing is even possible) depends on the OS and
display packages you are using.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK 8.5

2008-01-01 Thread Kevin Walzer
Martin v. Löwis wrote:
>> But I found nothing about Tk 8.5 ?
> 
> Python is not tied to any specific Tk version; you can use
> any Python release with any Tk version, most of the time.
> 
> Hence, there is no need to talk about this very much. That
> Python "supports" Tk 8.5 is too minor to mention - I think
> even Python 2.4 supports Tk 8.5.

In terms of building and linking Python to Tk 8.5, this is certainly true.

However, I think most people who ask about Python "supporting" Tk 8.5 
are probably asking how easily can the new features in Tk 8.5 be 
accessed from Python, particularly the platform-specific themed widgets. 
The answer to that question is, "At present, not very easily." There is 
currently no support at all in lib-tk for themed widgets, for instance. 
The external Tile.py module that I maintain at 
http://tkinter.unpythonic.net/wiki/TileWrapper works well enough, but as 
I am not the original author of this module, I cannot really offer it 
for inclusion in the core Python distribution. As such, someone will 
have to step up and write a new implememtation.

--Kevin

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Some specific exec behavior ?

2008-01-01 Thread Stef Mientki
hello,

I find 2 strange behaviors in exec-function,
and I can't find anything in the documentation.
(Python 2.4.3 Enthought edition)

1. A function definition may not span more than 1 line, e.g.
This generates an exception:
def _func (x,y):
return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)

while this works correct:
def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)

2. an emtpy line at the end also generates an exception

Is this behavior correct ?
where should I find information about it ?

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre behavior with mutable default arguments

2008-01-01 Thread Gabriel Genellina
En Tue, 01 Jan 2008 15:45:00 -0200, bukzor <[EMAIL PROTECTED]>  
escribi�:
> On Jan 1, 9:00 am, bukzor <[EMAIL PROTECTED]> wrote:
>> On Dec 31 2007, 1:30 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
>>
>> > And also removing the only way you can currently do early binding in
>> > Python. I agree that it's a gotcha, but unless someone comes up with
>> > an answer to the following questions, I'll stick with the status quo
>> > (Note that this is not blind Python group-think as a previous poster
>> > implied, but a pragmatic decision that this is the most practical
>> > solution):
>>
>> > a) If we don't evaluate default arguments at function compilation,
>> > when do we do it?
>> > b) If you do it at call time, how do you implement early binding?
>>
>> I'm confused by what you mean by 'early binding'. Can you give a quick-
>> n-dirty example?
> Is an 'early bound' variable synonymous with a 'static' variable (in
> C)?

No. It means, in which moment the name gets its value assigned. Usually  
Python does "late binding", that is, names are resolved at the time the  
code is executed, not when it's compiled or defined.
Consider this example:

z = 1
def foo(a)
   print a+z
foo(3) # prints 4
z = 20
foo(3) # prints 23

The second time it prints 23, not 4, because the value for z is searched  
when the code is executed, so the relevant value for z is 20.
Note that if you later assign a non-numeric value to z, foo(3) will fail.

If you want to achieve the effect of "early binding", that is, you want to  
"freeze" z to be always what it was at the time the function was defined,  
you can do that using a default argument:

z = 1
def foo(a, z=z)
   print a+z
z = None
foo(3) # prints 4

This way, foo(3) will always print 4, independently of the current value  
of z. Moreover, you can `del z` and foo will continue to work.

This is what I think Chris Mellon was refering to. This specific default  
argument semantics allows one to achieve the effect of "early binding" in  
a language which is mostly "late binding". If someone changes this, he has  
to come with another way of faking early binding semantics at least as  
simple as this, else we're solving an [inexistant for me] problem but  
creating another one.

-- 
Gabriel Genellina

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

Re: Push to Make (Single Pole) Button running a loop

2008-01-01 Thread Sambo
Hendrik van Rooyen wrote:
>  "Jon Todd"  wrote:
> 
> 
>>I'd like to have a button that when pressed executes a loop (this could be a
>>thread) and then stops execution when it's released (Push to Make - Single
>>Pole in electronics terms).
>>
>>I've tried the regular way of associating the procedure with a callback and
>>tried using  and  bindings but am getting nowhere
>>fast (in the latter case the button release event seems to occur anyhows).
>>
> 
> 
> You are a bit stymied :
> 
> Afaik, Button needs the click on the button, leaving it depressed,
> while ButtonRelease needs a click on the button, and the release can be 
> anywhere
> for drag and drop implementation.  So it is possible to call two routines with
> one
> click and release.
> 
> But there is another hassle - you would have to code the loop as a separate
> thread,
> started by the first, while the second routine sets some variable that is
> checked by
> the loop to kill itself, as the GUI will not be responsive until the first
> command
> returns, because the command "captures" the main loop...
> 
> HTH - Hendrik
> 
> 
Perhaps besides all the multithreading issues you should be looking at 
different kind
of control/button ei. checkbox or radio button (windows terminology)?

My first experience at GUI with Tk/TCL?? was not a good one due to both
lack of docs and fear it wouldn't work on both LUNUX and vindows.

Wish there was a simple library with basic primitives like create_windows 
resize,
get_client_area and of course some functions to hand of control to the system.
At least for me, that way I could get much further much faster than trying to
find the learn the behavior of all the currently available controls.
Another point I came across recently is that there is no information on proper 
cleanup after TCL, don't remember exactly why it was a problem it is after all 
OOP sy. 
So, you may have to read the sourcecode for everything you are using and it 
ain't easy, 

Good Luck.

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


Re: at what complexity, a comparison fails ?

2008-01-01 Thread Stef Mientki
Robert Kern wrote:
> Stef Mientki wrote:
>   
>> hello,
>>
>> I had a program that worked perfectly well.
>> In this program modules were dynamically added,
>> just by putting the file in a predefined directory.
>>
>> Now one of the interface mechanisms was to see if some parameter was 
>> changed in a an instance,
>> by comparing the value from the instance with its previous value
>>
>> This went all well, untill I added a too complex variable,
>> then the program stopped working, without generating exceptions.
>>
>> So it seems that comparing a too complex value isn't allowed.
>> the variable was something like:
>>
>>   A = [ , , ..., [,,...], [, 
>> , ... ] ]
>>
>> So what I need was something like:
>> if  A != A_prev :
>> ... do something
>> A_prev = A
>>
>> And this crashes, or at least it doesn't work but also doesn't generate 
>> exceptions.
>> It does seems to work, if A only contains 1 array.
>>
>> Why am I not allowed to compare A and A_prev ??
>> And in general, how complex might a list be to make a valid comparison,
>> or what are the rules ?
>> 
>
> Remember that numpy arrays use rich comparisons. (ndarray1 != ndarray2) gives
> another array, not a boolean value. The resulting array cannot be used in an
> "if" clause.
>
>   
thanks guys,
I'm glad that Python behaves as expected and can compare complex 
structures ;-)
Robert you hit the nail right on its head, indeed I should be quit 
carefully with numpy arrays.

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some specific exec behavior ?

2008-01-01 Thread Gabriel Genellina
En Tue, 01 Jan 2008 16:39:21 -0200, Stef Mientki <[EMAIL PROTECTED]>  
escribi�:

> I find 2 strange behaviors in exec-function,
> and I can't find anything in the documentation.
> (Python 2.4.3 Enthought edition)
>
> 1. A function definition may not span more than 1 line, e.g.
> This generates an exception:
> def _func (x,y):
> return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)
>
> while this works correct:
> def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)
>
> 2. an emtpy line at the end also generates an exception
>
> Is this behavior correct ?
> where should I find information about it ?

It's correct; source lines must be separated by '\n' only (NOT '\r\n' as  
in a Windows text file) and the last line must end in '\n'.
It's documented, but under the compile() built-in function:  
http://docs.python.org/lib/built-in-funcs.html; perhaps the docs for exec  
should refer there.

-- 
Gabriel Genellina

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

Re: Newbie: Why doesn't this work

2008-01-01 Thread petr . jakes . tpc
Hi all,

I am trying to understand new-style classes in Python and I have found
your postings here.

Gabriel, if I understand it properly, it is necessary to define get/
set/del/doc methods for each attribute for which I want to set the
"property" data descriptor (which triggers get/set/del/doc function
calls upon access to defined attribute).

My question is: is it possible to set the "property" for any attribute
when I do not know what will be the name of the attribute in the
future?

Thanks for your reply

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


Re: pexpect ssh login and ls | grep

2008-01-01 Thread crybaby
I did try to excute the ssh and shell ls grep command in all in one
like so:

ssh  [EMAIL PROTECTED] "ls mytest.log > /dev/null 2>&1; echo $?"

This seem to work, but also throwing exceptions.  Also, including ssh
and shell command together would be a problem when I later add a pass
phrase to ssh key.  Can someone provide little insight on this?


>>> import pexpect
>>> child=pexpect.spawn('ssh  [EMAIL PROTECTED] "ls mytest.log > /dev/null 
>>> 2>&1; echo $?"')
>>>
>>> child.expect([pexpect.TIMEOUT, '\$'])
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib/python2.4/site-packages/pexpect.py", line 1064, in
expect
return self.expect_list(compiled_pattern_list, timeout,
searchwindowsize)
  File "/usr/lib/python2.4/site-packages/pexpect.py", line 1132, in
expect_list
raise EOF (str(e) + '\n' + str(self))
pexpect.EOF: End Of File (EOF) in read_nonblocking(). Exception style
platform.

version: 2.1 ($Revision: 395 $)
command: /usr/bin/ssh
args: ['/usr/bin/ssh', '[EMAIL PROTECTED]', 'ls mytest.log > /dev/null 2>&1;
echo $?']
patterns:
pexpect.TIMEOUT
\$
buffer (last 100 chars):
before (last 100 chars): 0

after: pexpect.EOF
match: None
match_index: None
exitstatus: 0
flag_eof: True
pid: 3524
child_fd: 3
closed: False
timeout: 30
delimiter: pexpect.EOF
logfile: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.1
delayafterclose: 0.1
delayafterterminate: 0.1
>>>
>>> result=child.before
>>> result2=child.after
>>> print result
0

>>> print result2
pexpect.EOF
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Why doesn't this work

2008-01-01 Thread Gabriel Genellina
En Tue, 01 Jan 2008 16:57:41 -0200, <[EMAIL PROTECTED]> escribi�:

> Gabriel, if I understand it properly, it is necessary to define get/
> set/del/doc methods for each attribute for which I want to set the
> "property" data descriptor (which triggers get/set/del/doc function
> calls upon access to defined attribute).

Yes. Not all of them, just what you need (by example, a read-only property  
doesn't require a set method; I think the get() docstring is used if no  
explicit doc is provided; most of the time I don't care to define del...)
You don't "have" to define anything you don't need; moreover, you don't  
have to define a property if you don't actually need it. The very first  
example in the builtin functions documentation for "property" is a bad  
example: if all your property does is to wrap a stored attribute, forget  
about the property and use the attribute directly.

> My question is: is it possible to set the "property" for any attribute
> when I do not know what will be the name of the attribute in the
> future?

Uhm... I don't understand the question. Perhaps if you think of a concrete  
case...?

-- 
Gabriel Genellina

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

Re: ElementTree should parse string and file in the same way

2008-01-01 Thread Steven Bethard
Steven D'Aprano wrote:
> On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote:
> 
>> And codemonkeys know that in python
>>
>> doc = et.parse(StringIO(string))
>>
>> is just one import away
> 
> Yes, but to play devil's advocate for a moment, 
> 
> doc = et.parse(string_or_file)
> 
> would be even simpler.

I assume the problem with this is that it would be ambiguous. You can 
already use either a string or a file with ``et.parse``. A string is 
interpreted as a file name, while a file object is used directly.

How would you differentiate between a string that's supposed to be a 
file name, and a string that's supposed to be XML?

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


Re: parallel processing in standard library

2008-01-01 Thread Konrad Hinsen
Emin.shopper Martinian.shopper wrote:

> Is there any hope of a parallel processing toolkit being  
> incorporated into the python standard library? I've seen a wide  
> variety of toolkits each with various features and limitations.  
> Unfortunately, each has its own API. For coarse-grained  
> parallelism, I suspect I'd be pretty happy with many of the  
> existing toolkits, but if I'm going to pick one API to learn and  
> program to, I'd rather pick one that I'm confident is going to be  
> supported for a while.

I don't think that parallel computing is mature enough to allow the  
standardization of APIs, except within a given and well specified  
parallel computing model such as message passing.

The Python Wiki has an impressive list of parallel processing options  
for Python (see http://wiki.python.org/moin/ParallelProcessing). With  
the exception of the various MPI interfaces, I don't think that any  
two of them are based on the same parallel computing model. I don't  
expect this situation to change any time soon, as parallel computing  
is still very much experimental. Whereas sequential computing has  
well-tested software engineering techniques, reliable libraries that  
can be combined into programs, and ever improving testing techniques,  
none of these exist for parallel computing.

For an overview of parallel computing models and for a more detailed  
description of one of them as implemented in Python, please see my  
recent article in "Computing in Science and Engineering":

http://www.computer.org/portal/site/cise/index.jsp? 
pageID=cise_level1&path=cise/2007/n6&file=sci.xml&xsl=article.xsl

Konrad.


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


Re: Some specific exec behavior ?

2008-01-01 Thread Stef Mientki
Gabriel Genellina wrote:
> En Tue, 01 Jan 2008 16:39:21 -0200, Stef Mientki <[EMAIL PROTECTED]>  
> escribi�:
>
>   
>> I find 2 strange behaviors in exec-function,
>> and I can't find anything in the documentation.
>> (Python 2.4.3 Enthought edition)
>>
>> 1. A function definition may not span more than 1 line, e.g.
>> This generates an exception:
>> def _func (x,y):
>> return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)
>>
>> while this works correct:
>> def _func (x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)
>>
>> 2. an emtpy line at the end also generates an exception
>>
>> Is this behavior correct ?
>> where should I find information about it ?
>> 
>
> It's correct; source lines must be separated by '\n' only (NOT '\r\n' as  
> in a Windows text file) and the last line must end in '\n'.
> It's documented, but under the compile() built-in function:  
> http://docs.python.org/lib/built-in-funcs.html; perhaps the docs for exec  
> should refer there.
>
>   
Thanks Gabriel,
that explains everything !

cheers,
Stef


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

Re: Bizarre behavior with mutable default arguments

2008-01-01 Thread Arnaud Delobelle
On Jan 1, 6:48 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Tue, 01 Jan 2008 15:45:00 -0200, bukzor <[EMAIL PROTECTED]>  
> escribi�:
[...]
> >> I'm confused by what you mean by 'early binding'. Can you give a quick-
> >> n-dirty example?
> > Is an 'early bound' variable synonymous with a 'static' variable (in
> > C)?
>
> No. It means, in which moment the name gets its value assigned. Usually  
> Python does "late binding", that is, names are resolved at the time the  
> code is executed, not when it's compiled or defined.
> Consider this example:
>
> z = 1
> def foo(a)
>    print a+z
> foo(3) # prints 4
> z = 20
> foo(3) # prints 23
>
> The second time it prints 23, not 4, because the value for z is searched  
> when the code is executed, so the relevant value for z is 20.
> Note that if you later assign a non-numeric value to z, foo(3) will fail.
>
> If you want to achieve the effect of "early binding", that is, you want to  
> "freeze" z to be always what it was at the time the function was defined,  
> you can do that using a default argument:
>
> z = 1
> def foo(a, z=z)
>    print a+z
> z = None
> foo(3) # prints 4
>
> This way, foo(3) will always print 4, independently of the current value  
> of z. Moreover, you can `del z` and foo will continue to work.
>
> This is what I think Chris Mellon was refering to. This specific default  
> argument semantics allows one to achieve the effect of "early binding" in  
> a language which is mostly "late binding". If someone changes this, he has  
> to come with another way of faking early binding semantics at least as  
> simple as this, else we're solving an [inexistant for me] problem but  
> creating another one.
>
> --
> Gabriel Genellina

Let me say again that I believe the current behaviour to be the
correct one.  But I don't think this 'early binding' is critical for
this sort of example.  There are lots of ways to solve the problem of
having persistent state across function calls, for example:

* using classes
* using modules
* or simply nested functions:

def getfoo(z):
def foo(a):
print a + z
return foo

>>> z = 1
>>> foo = getfoo(z)
>>> z = None
>>> foo(3)
4

And with nonlocal, we could even modify z inside foo and this change
would persist across calls.  This will be a much cleaner solution than
the current def bar(x, y, _hidden=[startvalue]).

Also, note that it's easy to implement default arguments in pure
python-without-default-arguments using a decorator:

def default(**defaults):
defaults = defaults.items()
def decorator(f):
def decorated(*args, **kwargs):
for name, val in defaults:
kwargs.setdefault(name, val)
return f(*args, **kwargs)
return decorated
return decorator

Here is your example:

>>> z=1
>>> @default(z=z)
... def foo(a, z):
... print a + z
...
>>> z=None
>>> foo(3)
4

Another example, using mutables:

>>> @default(history=[])
... def bar(x, history):
... history.append(x)
... return list(history)
...
>>> map(bar, 'spam')
[['s'], ['s', 'p'], ['s', 'p', 'a'], ['s', 'p', 'a', 'm']]

--
Arnaud

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

confusion about package/module imports

2008-01-01 Thread Jugdish
Why doesn't the following work?

>>> ls $HOME
$HOME/pkg/__init__.py
$HOME/pkg/subpkg/__init__.py
$HOME/pkg/subpkg/a.py
$HOME/pkg/subpkg/b.py

>>> cat $HOME/pkg/__init__.py
# empty

>>> cat $HOME/pkg/subpkg/__init__.py
import a
import b

>>> cat $HOME/pkg/subpkg/a.py
class A:
pass

>>> cat $HOME/pkg/subpkg/b.py
import pkg.subpkg.a
class B(pkg.subpkg.a.A):
pass

>>> setenv PYTHONPATH $HOME:$PYTHONPATH
>>> python $HOME/pkg/subpkg/b.py
Traceback (most recent call last):
  File "pkg/subpkg/b.py", line 1, in ?
import pkg.subpkg.a
  File "$HOME/pkg/subpkg/__init__.py", line 2, in ?
import b
  File "$HOME/pkg/subpkg/b.py", line 2, in ?
class B(pkg.subpkg.a.A):
AttributeError: 'module' object has no attribute 'subpkg'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Why doesn't this work

2008-01-01 Thread petr . jakes . tpc
> > My question is: is it possible to set the "property" for any attribute
> > when I do not know what will be the name of the attribute in the
> > future?
>
> Uhm... I don't understand the question. Perhaps if you think of a concrete
> case...?

Thanks for reply,

few minutes after i posted my question, I have realized my posting is
probably a "nonsense".

If I understand it properly, it is necessary, in the respect of
encapsulation, to define attributes inside the class (even it is
possible to add a new attribute to the existing object outside class
definition).

The meaning of my question was:
Is it possible to define some general sort of set/get/del/doc rules
for the attributes which are defined in the code AFTER the
instantiation of an object.

I am sending this question even I feel such a "on the fly" creation of
the attribute is probably not a good trick.

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


cloud computing (and python)?

2008-01-01 Thread Aaron Watters
So, in between skiing runs I noticed
a Business Week cover story on
"cloud computing".  The article had
lots of interesting information in it like
about how somebody's mom used to
be an airline stewardess and the
interior decor of various office spaces.
It was a truly excellent piece of
journalism.

However it gave me no idea what
"cloud computing" is and how it
could be used to solve a computational
problem.

Could anyone on this list
which usually has highly informed
readers give me a clue at some
level of technical detail what cloud
computing is about and how it could
be used.  Bonus points if you mention
Python in the response!

An actual example would be great,
if it's not web scraping and searching.

  - Aaron Watters

==
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=snow
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK 8.5

2008-01-01 Thread Martin v. Löwis
>> Hence, there is no need to talk about this very much. That
>> Python "supports" Tk 8.5 is too minor to mention - I think
>> even Python 2.4 supports Tk 8.5.
> 
> In terms of building and linking Python to Tk 8.5, this is certainly true.
> 
> However, I think most people who ask about Python "supporting" Tk 8.5
> are probably asking how easily can the new features in Tk 8.5 be
> accessed from Python, particularly the platform-specific themed widgets.

I just found that there is also "middle ground": would most existing
Tkinter applications work when Python was linked with Tk 8.5; in
particular, would IDLE work?

This is not the case for Python 2.5. Tk 8.5 changed the data types
it returns from certain commands, affecting existing code. Likely,
IDLE should work with Tk 8.5 in Python 2.6 and 3.0, but won't work
for Python 2.5.

> The answer to that question is, "At present, not very easily." There is
> currently no support at all in lib-tk for themed widgets, for instance.
> The external Tile.py module that I maintain at
> http://tkinter.unpythonic.net/wiki/TileWrapper works well enough, but as
> I am not the original author of this module, I cannot really offer it
> for inclusion in the core Python distribution. As such, someone will
> have to step up and write a new implememtation.

That is of no concern for me whatsoever. Contributions are welcome.

I know people are jumping up and down because of these themed widgets;
the "I won't do anything actively" goes beyond that, though: even if
existing widgets get new commands, or new widgets are added, then
support for them in Tkinter is only added through user contributions.

If "supports Tk 8.x" means "Tkinter has wrappers for all commands
and options", then Tkinter has no support for any version of Tk,
as a lot of commands remain unwrapped.

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


Re: confusion about package/module imports

2008-01-01 Thread Scott David Daniels
Jugdish wrote:
> Why doesn't the following work?
> ... 
   [well boiled-down code skipped]
 setenv PYTHONPATH $HOME:$PYTHONPATH
 python $HOME/pkg/subpkg/b.py
> Traceback (most recent call last):
>   File "pkg/subpkg/b.py", line 1, in ?
> import pkg.subpkg.a
>   File "$HOME/pkg/subpkg/__init__.py", line 2, in ?
> import b
>   File "$HOME/pkg/subpkg/b.py", line 2, in ?
> class B(pkg.subpkg.a.A):
> AttributeError: 'module' object has no attribute 'subpkg'

OK, here's a trick for finding import problems:
 python -v 
(shows all imports)

And for this case:
 sprinkle prints to find out what is happening.

so, add "print __name, __file__" to the top of each file where
you wonder what is going on.
I later added prints in pkg/subpkg/__init__.py to make the steps clear.

You'll see that b is executed (making module __main__),
it imports pkg.subpkg.a,
which is accomplished by importing pkg (successfully),
 then by importing pkg.subpkg
   which imports pkg.subpkg.a (successfully)
   and then imports pkg.subpkg.b
   which then attempts to import pkg.subpkg.a
At that point, only the module pkg
and what should eventually become pkg.subpkg.a
have been successfully imported.  pkg.subpkg had not yet been imported.
If you remove the "import b" from subpkg's __init__, you will find
your problems going away.
Alternatively, you can remove the import a / import b from subpkg
and add import subpkg.a, subpkg.b to pkg's __init__.  Essentially,
you need pkg.subpkg fully imported before you import pkg.subpkg.b

Of course, in most of these cases you will have imported the code
for b twice, once as a main program, and once as a module in the
hierarchy, which is probably your actual problem (and why I use
"print __name__, __file__").


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Why doesn't this work

2008-01-01 Thread Steven D'Aprano
On Tue, 01 Jan 2008 13:01:24 -0800, petr.jakes.tpc wrote:

>> > My question is: is it possible to set the "property" for any
>> > attribute when I do not know what will be the name of the attribute
>> > in the future?
>>
>> Uhm... I don't understand the question. Perhaps if you think of a
>> concrete case...?
> 
> Thanks for reply,
> 
> few minutes after i posted my question, I have realized my posting is
> probably a "nonsense".
> 
> If I understand it properly, it is necessary, in the respect of
> encapsulation, to define attributes inside the class (even it is
> possible to add a new attribute to the existing object outside class
> definition).
> 
> The meaning of my question was:
> Is it possible to define some general sort of set/get/del/doc rules for
> the attributes which are defined in the code AFTER the instantiation of
> an object.
> 
> I am sending this question even I feel such a "on the fly" creation of
> the attribute is probably not a good trick.

Like all dynamic modification of classes, it is liable to abuse, but 
Python allows such things and trusts the programmer not to be foolish.

class Parrot(object):
pass


def set_property(cls, propertyname, defaultvalue=None, docstring=''):
"""Make a readable, writable but not deletable property."""
privatename = '_' + propertyname
setattr(cls, privatename, defaultvalue)
def getter(self):
return getattr(self, privatename)
def setter(self, value):
setattr(self, privatename, value)
setattr(cls, propertyname, property(getter, setter, None, docstring))


set_property(Parrot, 'colour', 'red', 
"""Parrots have beautiful coloured plumage.""")



Now that you know how to do it, please don't. Except for the lack of 
docstring, the above is much better written as:


class Parrot(object):
colour = 'red'





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


Re: cloud computing (and python)?

2008-01-01 Thread PatrickMinnesota
On Jan 1, 3:26 pm, Aaron Watters <[EMAIL PROTECTED]> wrote:
> So, in between skiing runs I noticed
> a Business Week cover story on
> "cloud computing".  The article had
> lots of interesting information in it like
> about how somebody's mom used to
> be an airline stewardess and the
> interior decor of various office spaces.
> It was a truly excellent piece of
> journalism.
>
> However it gave me no idea what
> "cloud computing" is and how it
> could be used to solve a computational
> problem.
>
> Could anyone on this list
> which usually has highly informed
> readers give me a clue at some
> level of technical detail what cloud
> computing is about and how it could
> be used.  Bonus points if you mention
> Python in the response!
>
> An actual example would be great,
> if it's not web scraping and searching.
>
>   - Aaron Watters
>
> ==http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=snow

Examples of applications in the cloud:  Google apps, Zoho.com

Examples of cloud storage and bandwidth:  Amazon's S3 for scalable
storage, Amazon's EC2 for scalable serving

The idea is that your data and applications are on the net, rather
than your local hard drive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree should parse string and file in the same way

2008-01-01 Thread Steven D'Aprano
On Tue, 01 Jan 2008 12:59:44 -0700, Steven Bethard wrote:

> Steven D'Aprano wrote:
>> On Tue, 01 Jan 2008 13:36:57 +0100, Diez B. Roggisch wrote:
>> 
>>> And codemonkeys know that in python
>>>
>>> doc = et.parse(StringIO(string))
>>>
>>> is just one import away
>> 
>> Yes, but to play devil's advocate for a moment,
>> 
>> doc = et.parse(string_or_file)
>> 
>> would be even simpler.
> 
> I assume the problem with this is that it would be ambiguous. You can
> already use either a string or a file with ``et.parse``. A string is
> interpreted as a file name, while a file object is used directly.
 
Ah! I wasn't aware that parse() operated on either an open file object or 
a string file name. That's an excellent reason for not treating strings 
the same as files in ElementTree.



> How would you differentiate between a string that's supposed to be a
> file name, and a string that's supposed to be XML?

Well, naturally I wouldn't.

I *could*, if I assumed that a multi-line string that started with "<" 
was XML, and a single-line string with the path separator character or 
ending in ".xml" was a file name, but that sort of Do What I Mean coding 
is foolish in a library function that can't afford to occasionally Do The 
Wrong Thing.


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


Re: cloud computing (and python)?

2008-01-01 Thread PatrickMinnesota
On Jan 1, 3:26 pm, Aaron Watters <[EMAIL PROTECTED]> wrote:
> So, in between skiing runs I noticed
> a Business Week cover story on
> "cloud computing".  The article had
> lots of interesting information in it like
> about how somebody's mom used to
> be an airline stewardess and the
> interior decor of various office spaces.
> It was a truly excellent piece of
> journalism.
>
> However it gave me no idea what
> "cloud computing" is and how it
> could be used to solve a computational
> problem.
>
> Could anyone on this list
> which usually has highly informed
> readers give me a clue at some
> level of technical detail what cloud
> computing is about and how it could
> be used.  Bonus points if you mention
> Python in the response!
>
> An actual example would be great,
> if it's not web scraping and searching.
>
>   - Aaron Watters
>
> ==http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=snow

Oh, and I forgot to mention Python for points.

Python combined with a framework like Django is used with Amazon's
cloud services in various applications.  www.Pownce.com is an example.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cloud computing (and python)?

2008-01-01 Thread Steven D'Aprano
On Tue, 01 Jan 2008 13:55:10 -0800, PatrickMinnesota wrote:

> The idea is that your data and applications are on the net, rather than
> your local hard drive.

Or, to put it another way, your data and applications are controlled by 
another company rather than you.

Not that I wish to be cynical or anything like that.


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


Re: Network Module

2008-01-01 Thread Matthew Franz
Why not just wrap netstat for what you need? or you might be able to
get from /proc entries? Or look at
http://www.psychofx.com/psi/trac/wiki/  (PSI Tools)   If you want
interface statistics you can process the CSV output of bwm-ng
(http://www.gropp.org/?id=projects&sub=bwm-ng)

- mdf

On Jan 1, 2008 7:40 AM, Sunil Ghai <[EMAIL PROTECTED]> wrote:
> Hello people,
> I am searching for a python module to interact with the network
> connections/interfaces. For example the number of active TCP/IP connections
> via eth0 interface and all that stuff.
> I have done googling and search at pythonorg but couldn't find any.
>
> Thanks
> Sunil Kumar Ghai
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matthew Franz
http://www.threatmind.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tab indentions on different platforms?

2008-01-01 Thread Ben Finney
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> On Mon, 31 Dec 2007 12:36:11 +1100, Ben Finney wrote:
> 
> > Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > 
> >> On Sun, 30 Dec 2007 20:41:09 +, Thorsten Kampe wrote:
> >> 
> >> > Anyway: the consequence of your well done argumentation is that
> >> > someone editing Python code has to use a specialised editor to
> >> > prevent screwing up tab indented code - and that's bad.
> >> 
> >> You just need to use an editor that inserts tab characters when
> >> the tab key is pressed, just like you use an editor that inserts
> >> s characters when the s key is pressed.
> > 
> > No, that's not all you need to do. You also need to keep your code
> > away from the majority of programmers, who use their default
> > editor in its default settings

I remind you that the earlier context of this "default settings" was a
discussion of how text editors *render* horizontal whitespace
characters: that the majority of environments make no visual
distinction between a U+0009 TAB and an equivalent sequence of U+0020
SPC characters.

> I question that. On my system at least (Fedora 7), here are the
> default settings on the editors I have available:
> 
> [most editors default to inserting a U+0009 TAB when the Tab key is
> pressed]

Yes. I never raised the point about what happens when the Tab key is
pressed.

My point about default settings, rather, is that most editing
environments in their default settings will not visually distinguish
an *existing* TAB from a SPC sequence.

Instead of talking about *what happens* when the Tab key is pressed,
my argument was rather that many files will be edited such that the
Tab key is *not* pressed for indentation, because:

> > [users of such environments are led to] expect that horizontal
> > whitespace is produced by the U+0020 space character (even if they
> > don't know the specifics of the character coding).
> > 
> > Saying that the tabs-only argument and the spaces-only argument
> > are of equal value is philosophically true, but practically
> > worthless. They're of equal value *only* in isolated environments
> > where you can control the expectations of *every* programmer who
> > will *ever* edit the file.
> 
> Ah, and now we're getting somewhere! It's not so much that tabs are
> intrinsically harmful (as people like Thorsten keep insisting), but
> that in a world supposedly dominated by people who indent with
> spaces, using tabs might lead to inconsiderate programmers ignoring
> your project's coding standards and inserting spaces into your code
> base.

I disagree that such a programmer would be "inconsiderate" by merely
following the least-surprising interpretation of what they see in
front of them.

> Yes, I can see that is a problem. I believe it is best solved by
> refusing contributions from such inconsiderate programmers. After
> all, if they're going to ignore your project's code standards in one
> aspect, they're invariably going to ignore others as well.

Again, your argument rests on the fantasy of being able to exert
control over those who would edit those files.

> Ben, I'm surprised that you of all people should take such a
> pragmatic view that "tabs are bad because the majority use spaces".

I'm sorry if you've been led to believe I'm averse to pragmatism; I'm
very much enamoured of it. What I'm averse to is *false* pragmatism
that turns out merely to be delusion or false economy.

> There's a very good reason to buck the trend whenever practical:
> tabs have the considerable benefit that they decouple the
> presentation of the code from the structure of the code.

Huh? I can only interpret this to mean that you think it's a good
thing for a text file one is *directly editing* to be rendered in such
a way that one cannot tell quite what one is really editing.

I don't consider that a good thing at all. Editing a text file is an
occasion when it is *essential* to know exactly what changes one is
making, at a character-by-character level.

> When you use tabs to indent code, the reader can place their tab
> stops where ever they wish, according to their own needs and
> preferences: every eight spaces, or four, or three, or twenty-seven
> spaces if they want. One tab means one indent level (structure), and
> the width of that indent (presentation) is up to the reader.

That's fine if *all* they do is read the code. I'm coding for those
who will read the code with a view to *editing* it as well. For such a
reader, I want the visual rendering of the file to show the character
structure of the file as obviously as possible, to enable them to edit
it with the least potential for astonishment.

> But when you use spaces, you are essentially forcing your
> presentation onto all your readers, whatever their wishes.

This is an argument against, for example, forcing an HTML document to
render the same way on multiple devices. That argument leads,
correctly in my view, to the conclusion that presentation should be
decoupled f

Re: confusion about package/module imports

2008-01-01 Thread Jugdish
Thanks very much for your helpful response!

> You'll see that b is executed (making module __main__),
> (1) it imports pkg.subpkg.a,
> (2)   which is accomplished by importing pkg (successfully),
> (3)then by importing pkg.subpkg
> (4)  which imports pkg.subpkg.a (successfully)
> (5)   and then imports pkg.subpkg.b
> (6)   which then attempts to import pkg.subpkg.a

What I'm not really understanding here is why this fails at lines (5)
and (6). If pkg.subpkg.a has already been successfully imported at
line (4), then (6) should be detected as a duplicate import and just
be skipped, right? So the import at line (5) should succeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Catching external program exceptions

2008-01-01 Thread Marty
I need to catch exceptions thrown by programs started by the os.system 
function, 
as indicated by a non-zero return code (e.g. the mount utility).  For example, 
if I get the following results in a bash shell:

$mount test
mount: can't find /home/marty/test in /etc/fstab or /etc/mtab

then I want to catch the same exception from the corresponding os.system() 
call, 
i.e. "os.system('mount test')", but it doesn't work as expected:


 >>> import os, sys
 >>> try: os.system('mount test')
... except: print 'error'
...
mount: can't find /home/marty/test in /etc/fstab or /etc/mtab
256
 >>>

I get the same results with popon, popen2, popen3, etc.  Apparently these also 
work only when the program does not generate an exception.  Is there any way to 
catch the return code. or if not, a workaround?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: confusion about package/module imports

2008-01-01 Thread Scott David Daniels
Jugdish wrote:
> Thanks very much for your helpful response!
> 
>> You'll see that b is executed (making module __main__),
>> (1) it imports pkg.subpkg.a,
>> (2)   which is accomplished by importing pkg (successfully),
>> (3)then by importing pkg.subpkg
>> (4)  which imports pkg.subpkg.a (successfully)
>> (5)   and then imports pkg.subpkg.b
>> (6)   which then attempts to import pkg.subpkg.a
> 
> What I'm not really understanding here is why this fails at lines (5)
> and (6). If pkg.subpkg.a has already been successfully imported at
> line (4), then (6) should be detected as a duplicate import and just
> be skipped, right? So the import at line (5) should succeed.

I'm sorry, I used shorthand.  While a module is being imported,
it only provisionally has a name.  Until subpkg is fully imported,
there is no module named pkg.subpkg.  At the root level (pkg, for
example), the module is provisionally added.  Further down the tree,
the module (such as that for pkg/subpkg/__init__.py) is only added
to the symbol table (the packages __dict__) when the module has been
completely imported.

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


pyparsing question

2008-01-01 Thread hubritic
I am trying to parse data that looks like this:

IDENTIFIERTIMESTAMP   T  C   RESOURCE_NAME   DESCRIPTION
2BFA76F6 1208230607   T   S   SYSPROCSYSTEM
SHUTDOWN BY USER
A6D1BD62   1215230807 I
HFirmware Event

My problem is that sometimes there is a RESOURCE_NAME and sometimes
not, so I wind up with "Firmware" as my RESOURCE_NAME and "Event" as
my DESCRIPTION.  The formating seems to use a set number of spaces.

I have tried making RESOURCE_NAME an Optional(Word(alphanums))) and
Description OneOrMore(Word(alphas) + LineEnd(). So the question is,
how can I avoid having the first word of Description sucked into
RESOURCE_NAME when that field should be blank?


The data I have has a fixed number of characters per field, so I could
split it up that way, but wouldn't that defeat the purpose of using a
parser?  I am determined to become proficient with pyparsing so I am
using it even when it could be considered overkill; thus, it has gone
past mere utility now, this is a matter of principle!

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


Re: pyparsing question

2008-01-01 Thread Neil Cerutti
On Jan 1, 2008 6:32 PM, hubritic <[EMAIL PROTECTED]> wrote:

> I am trying to parse data that looks like this:
>
> IDENTIFIERTIMESTAMP   T  C   RESOURCE_NAME   DESCRIPTION
> 2BFA76F6 1208230607   T   S   SYSPROCSYSTEM
> SHUTDOWN BY USER
> A6D1BD62   1215230807 I
> HFirmware Event
>
> My problem is that sometimes there is a RESOURCE_NAME and sometimes
> not, so I wind up with "Firmware" as my RESOURCE_NAME and "Event" as
> my DESCRIPTION.  The formating seems to use a set number of spaces.
>


> The data I have has a fixed number of characters per field, so I could
> split it up that way, but wouldn't that defeat the purpose of using a
> parser?  I am determined to become proficient with pyparsing so I am
> using it even when it could be considered overkill; thus, it has gone
> past mere utility now, this is a matter of principle!


If your data is really in fixed-size columns, then pyparsing is the wrong
tool.

There's no standard Python tool for reading and writing fixed-length field
"flatfile" data files, but it's pretty simple to use named slices to get at
the data.

identifier = slice(0, 8)
timestamp = slice(8, 18)
t = slice(18, 21)
c = slice(21, 24)
resource_name = slice(24, 35)
description = slice(35)

for line in file:
   line = line.rstrip("\n")
   print "id:", line[identifier]
   print "timestamp:", line[timestamp]
   ...etc...
-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pyparsing question

2008-01-01 Thread Neil Cerutti
On Jan 1, 2008 6:54 PM, Neil Cerutti <[EMAIL PROTECTED]> wrote:

> There's no standard Python tool for reading and writing fixed-length field
> "flatfile" data files, but it's pretty simple to use named slices to get at
> the data.
>
> identifier = slice(0, 8)
> timestamp = slice(8, 18)
> t = slice(18, 21)
> c = slice(21, 24)
> resource_name = slice(24, 35)
> description = slice(35)


Oops! I made an errant stab at the slice constructor. That last should be
'slice(35, None)'.

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

Python events, panel with text

2008-01-01 Thread SMALLp
Hy!

I have many small panels with text and I want do bind wx.EVT_LEFT_DOWN 
when clicked on panel, but i need to bind that in parent class. So I 
have instance of that small panel and when i bind it efects only part of 
small panel where is no text.



import wx

class RequestedFilesItems(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER)
sizer = wx.BoxSizer(wx.HORIZONTAL)

upButton = PanelButton(self, -1, "Upload")
upButton.Bind(wx.EVT_LEFT_DOWN, self.upload)
sizer.Add(upButton, 0, wx.LEFT, 15)



self.SetSizer(sizer)

def upload(self, event):
print "Please print this"



class PanelButton(wx.Panel):
def __init__(self, parent, id, buttonName):
wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER)
self.SetBackgroundColour("GREY")
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.text = wx.StaticText(self, -1, buttonName) 
sizer.Add(self.text, -1, wx.EXPAND | wx.ALL, 1)
self.text.Bind(wx.EVT_LEFT_DOWN, self.OnClick)
self.SetSizer(sizer)

def OnClick(self, event):
print "It only works for text, not for panel what I expected 
here"


if __name__ == '__main__':
 app = wx.PySimpleApp()
 frm = wx.Frame(None, wx.ID_ANY, 'Mouse-click test')
 panel = RequestedFilesItems(frm, wx.ID_ANY)
 frm.Show()
 app.MainLoop()



app.MainLoop()


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


Re: Python Trajectory Module?

2008-01-01 Thread Stef Mientki
[EMAIL PROTECTED] wrote:
> Greetings,
>
> I was wondering if there was a python Module/Library out there that
> handles some trajectory/physics stuff like moving an object along a
> straight path in an X,Y 2D (or 3D) plane or calculating parabolic
> arcs. I'd really settle for just the moving of an object along a
> straight line.
>
> I know it's not terribly difficult to implement this on your own, but
> I'd rather not re-invent the wheel if someone else already did a good
> job of it the first time.
>
> Thanks!
>   
Depends on how detailed / graphical you've in mind.
You might be interested in this:
  
http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html

I've put a scanned version of my written notes about the trajectory example.
No need for ODE in my very simple mind, because the functions describing 
the solution are already known.

If you want to view the demos / animations,
be sure to view the demo at the bottom first,
because it explains the philosophy behind the program.
Only 1 major feature is not described in this demo (because when I made 
the demo I had no solution for it, now I think I have)
and that is :
  an integrated help / instruction / assignment / fill-in forms / 
judgement, specially for educational puposes.

The program is not yet released,
because I'm now cleaning it up and debugging it (by making demos ;-)
cheers,
Stef




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


Re: Catching external program exceptions

2008-01-01 Thread Gabriel Genellina
En Tue, 01 Jan 2008 20:57:44 -0200, Marty <[EMAIL PROTECTED]> escribi�:

> I need to catch exceptions thrown by programs started by the os.system  
> function,
> as indicated by a non-zero return code (e.g. the mount utility).  For

Notice that these are two different things. You can wait until the  
external program ends, and get its return code; and you can sometimes read  
a message from its stderr. But none of these things by itself throws an  
exception in Python.

> example,
> if I get the following results in a bash shell:
>
> $mount test
> mount: can't find /home/marty/test in /etc/fstab or /etc/mtab
>
> then I want to catch the same exception from the corresponding  
> os.system() call,
> i.e. "os.system('mount test')", but it doesn't work as expected:

Perhaps it doesn't work as *you* expected, but it does work as specified.  
 From the os.system description at  
http://docs.python.org/lib/os-process.html
"On Unix, the return value is the exit status of the process encoded in  
the format specified for wait(). [...] [That return value] is  
system-dependent."
Later on the same page, describing the wait function, says that the return  
value is "a 16-bit number, whose low byte is the signal number that killed  
the process, and whose high byte is the exit status (if the signal number  
is zero)"
So os.system does NOT raise an exception when the executed program ends  
with a non-zero exit code.

> I get the same results with popon, popen2, popen3, etc.  Apparently  
> these also
> work only when the program does not generate an exception.

An external program cannot generate an exception inside the Python  
program. Only Python itself can do that.

> Is there any way to
> catch the return code. or if not, a workaround?

 From the description above, you could do some math to obtain the exit code  
looking at the os.system return value.
But perhaps it's easier to use subprocess.check_call, see "Convenience  
functions" at http://docs.python.org/lib/module-subprocess.html

-- 
Gabriel Genellina

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

Re: pyparsing question

2008-01-01 Thread John Machin
On Jan 2, 10:32 am, hubritic <[EMAIL PROTECTED]> wrote:

> The data I have has a fixed number of characters per field, so I could
> split it up that way, but wouldn't that defeat the purpose of using a
> parser?

The purpose of a parser is to parse. Data in fixed columns does not
need parsing.

>  I am determined to become proficient with pyparsing so I am
> using it even when it could be considered overkill; thus, it has gone
> past mere utility now, this is a matter of principle!

An extremely misguided "principle".  Would you use an AK47 on the
flies around your barbecue? A better principle is to choose the best
tool for the job.

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


Re: cloud computing (and python)?

2008-01-01 Thread Aaron Watters
On Jan 1, 5:05 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Tue, 01 Jan 2008 13:55:10 -0800, PatrickMinnesota wrote:
> > The idea is that your data and applications are on the net, rather than
> > your local hard drive.
>
> Or, to put it another way, your data and applications are controlled by
> another company rather than you.
>
> Not that I wish to be cynical or anything like that.
>
> --
> Steven

I see.  So cloud computing is
java dickless^H^H^H^H^H^Hskless
workstations warmed over but less
flexible?  I'm having trouble
understanding why people would want
to buy in to this.  For example at
the amazon site I see things like
"it might take a couple minutes
to load your image..."  Are they
joking?

hmmm.  -- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=try+not+to+allocate+too+many+objects+okay

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


Re: Catching external program exceptions

2008-01-01 Thread Ben Finney
Marty <[EMAIL PROTECTED]> writes:

> I need to catch exceptions thrown by programs started by the os.system
> function, as indicated by a non-zero return code (e.g. the mount
> utility).

That's not an exception. It's referred to as an "exit status" or
(often) some short form or variation of that term.

Python can make available the exit status value of an external
process, but isn't going to interpret them to the point of raising
exceptions that you can catch.

The exit status is always available to the parent process, but the
*meaning* of any given value of that status is highly dependent on the
program that was running.

If you want to respond to particular values, you'll have to do so by
explicitly testing the exit status against values to which you've
assigned meaning -- hopefully meanings documented in the manual page
for the program which generates the exit status.

>  For example, if I get the following results in a bash
> shell:
> 
> $mount test
> mount: can't find /home/marty/test in /etc/fstab or /etc/mtab
> 
> then I want to catch the same exception

What's happening isn't an exception. It's a message being emitted to
an output stream (likely the stderr stream of the mount process,
though some programs will put error messages on stdout), followed by
an exit of that process.

The parent of that process will receive an exit status from the
process when it terminates; it will also (on Unix-like systems)
receive a separate value indicating the OS signal that caused the
process to exit. Python's 'os.system' function makes both these values
available as the return value of the function.

http://docs.python.org/lib/os-process.html#l2h-2761>

> from the corresponding os.system() call, i.e. "os.system('mount
> test')", but it doesn't work as expected:
> 
> 
> >>> import os, sys
> >>> try: os.system('mount test')
> ... except: print 'error'
> ...
> mount: can't find /home/marty/test in /etc/fstab or /etc/mtab
> 256
> >>>

The statement within the 'try' block executes the 'os.system()' call;
since you're running inside the interpreter, the return value from
that function is displayed.

The return value, as documented in the 'os.system' documentation,
encodes both the signal number (the low 8 bits, in this case (256 &
0x0F) == 0) and, since the signal number is zero ("no signal
received") the exit status value (the high 8 bits, in this case (256
>> 8) == 1).

No exception is being raised, so the 'try' block completes
successfully and the 'except' block is not invoked.


So, instead of testing for an exception, you should instead be testing
the exit status code returned by the 'os.system' call. First, read the
documentation for the command you're running::

$ man mount
[...]

Unfortunately the 'mount(8)' manual page doesn't (on my system)
mention possible values for the exit status. So, you'll just have to
deduce it, or go with the common convention of "zero status ==
success, non-zero status == error".

MountFailedError = OSError
import os
return_value = os.system('mount test')
signal_number = (return_value & 0x0F)
if not signal_number:
exit_status = (return_value >> 8)
if exit_status:
raise MountFailedError("Oh no!")

Why isn't this standardised? Because the process-call interface is
inconsistent between operating systems, and there's even less
consistency in the implementations of the programs that return these
values.

The Zen of Python says: "In the face of ambiguity, refuse the
temptation to guess." Thus, Python can do little more than present the
values it received from the process call; anything further would be
guessing.

-- 
 \   "I bought some batteries, but they weren't included; so I had |
  `\ to buy them again."  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cloud computing (and python)?

2008-01-01 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Aaron Watters  <[EMAIL PROTECTED]> wrote:
>So, in between skiing runs I noticed
>a Business Week cover story on
>"cloud computing".  The article had
>lots of interesting information in it like
>about how somebody's mom used to
>be an airline stewardess and the
>interior decor of various office spaces.
>It was a truly excellent piece of
>journalism.
>
>However it gave me no idea what
>"cloud computing" is and how it
>could be used to solve a computational
>problem.
>
>Could anyone on this list
>which usually has highly informed
>readers give me a clue at some
>level of technical detail what cloud
>computing is about and how it could
>be used.  Bonus points if you mention
>Python in the response!
>
>An actual example would be great,
>if it's not web scraping and searching.
.
.
.
Aaron, while I make time for a more pertinent response,
http://www.unixreview.com/documents/s=10125/ur0704l/ >
might interest you.

I owe you better examples, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyCairo, PIL and StringIO

2008-01-01 Thread Jair Trejo
I'm doing some image processing in PIL, and I want to
display the results in a GTK window using PyCairo, so
I create a Cairo image surface from the PIL Image like
this:

mfile = StringIO.StringIO()
final.save(mfile, format="PNG")
ima =
cairo.ImageSurface.create_from_png(mfile)
mfile.close()
return ima

Where final is a PIL image. The problem is, I get a
IOError: error while reading from Input Stream.

¿Any idea of why is this happening? I tried saving to
a temporary file, i.e., replace the above code with:

final.save('final.png')
ima =
cairo.ImageSurface.create_from_png('final.png')

Instead of a StringIO object, and it works just fine.


  

¡Capacidad ilimitada de almacenamiento en tu correo!
No te preocupes más por el espacio de tu cuenta con Correo Yahoo!:  

http://correo.yahoo.com.mx/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cloud computing (and python)?

2008-01-01 Thread Neil Hodgson
Cloud computing is mostly about scalability. You do not need to be 
concerned so much about low level infrastructure details such as 
purchasing servers, configuring and maintaining them, hiring space in 
data centres, linking up data centres, etc. It converts a lot of fixed 
costs into lower recurring costs so makes it easier for a start up with 
limited capital to start operating.

There are Python libraries for accessing some of the cloud computing 
services and you can also host Python application code on some services 
that allow code execution. This includes services that can run arbitrary 
code on virtual machines such as EC2 and more restricted computational 
services like Hadoop which can run Jython.

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


Re: cloud computing (and python)?

2008-01-01 Thread PatrickMinnesota
On Jan 1, 7:12 pm, Neil Hodgson <[EMAIL PROTECTED]> wrote:
> Cloud computing is mostly about scalability. You do not need to be
> concerned so much about low level infrastructure details such as
> purchasing servers, configuring and maintaining them, hiring space in
> data centres, linking up data centres, etc. It converts a lot of fixed
> costs into lower recurring costs so makes it easier for a start up with
> limited capital to start operating.
>
> There are Python libraries for accessing some of the cloud computing
> services and you can also host Python application code on some services
> that allow code execution. This includes services that can run arbitrary
> code on virtual machines such as EC2 and more restricted computational
> services like Hadoop which can run Jython.
>
> Neil

I would say that cloud computing to an implementor or company
providing cloud
computing is all about scalability and stuff like S3 and EC3.  There
are
other options for this BTW.

But to the end user, it's about having your data and applications on a
disk
served by a network and server that is somewhere out there on the net
and
accessible from anywhere that you have connectivity. You might travel
with
a laptop, but generally, when in Hong Kong, you'll be screwed if a
chunk of
data is sitting on a disk inside a desktop in your home office and
isn't on
your laptop.  With the 'cloud' concept, it wouldn't matter where you
are,
as long as you have a connection to the internet, you can run the apps
and
access the data.

Issues:  and yes, they are big, who has control over the data, is it
being
backed up and protected, and is your private data being mined without
your approval. Oh,
and what happens if you use Zoho's system and they go out of
business?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tab indentions on different platforms?

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

Ben Finney writes:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>
>> [...]
>>
>> There's a very good reason to buck the trend whenever practical:
>> tabs have the considerable benefit that they decouple the
>> presentation of the code from the structure of the code.
>
> Huh? I can only interpret this to mean that you think it's a good
> thing for a text file one is *directly editing* to be rendered in
> such a way that one cannot tell quite what one is really editing.

No.  It's more like the old battle visual vs. semantic markup in
markup languages.  Both markup is unambiguous.  After all, the width
of a tab is nowhere defined.  It really is a matter of the editor's
settings.  I, for example, dislike too wide indenting.  I use four
columns in Python and two in Delphi.  However, there are Python
projects using eight spaces for each indentation level.

If all Python code used tabs, eveybody could use their own
preferences, for both reading and writing code, and interoperability
would be maintained nevertheless.

Tschö,
Torsten.

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


Re: ElementTree should parse string and file in the same way

2008-01-01 Thread Peter Pei
To answer something posted deep down... It is fine with me if there are two 
functions - one to parse a file or file handler and one to parse a string, 
yet the returned objects should be consistent. 

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


parse text files in a directory?

2008-01-01 Thread jo3c
hi everybody
im a newbie in python, i have a question

how do u parse a bunch of text files in a directory?

directory: /dir
files: H20080101.txt ,
H20080102.txt,H20080103.txt,H20080104.txt,H20080105.txt etc..

i already got a python script to read and insert a single text files
into a postgres db.

is there anyway i can do it in a batch, cause i got like 2000 txt
files.

thanks in advance

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


Re: parse text files in a directory?

2008-01-01 Thread Tim Chase
jo3c wrote:
> hi everybody
> im a newbie in python, i have a question
> 
> how do u parse a bunch of text files in a directory?
> 
> directory: /dir
> files: H20080101.txt ,
> H20080102.txt,H20080103.txt,H20080104.txt,H20080105.txt etc..
> 
> i already got a python script to read and insert a single text files
> into a postgres db.
> 
> is there anyway i can do it in a batch, cause i got like 2000 txt
> files.

>>> import os
>>> for filename in os.path.listdir(directory):
...if is_interesting(filename):
...do_something(filename)

you'll have to implement is_interesting() to catch filenames
you're interested in and you've already implemented the
do_something() body.

You might want to look at the "glob" module which allows for easy
filespec testing and name expansion for your "H*.txt" format:

  for filename in glob.glob('H*.txt'):
 do_something(filename)

If they're in subdirectories, you may want to investigate the
os.walk() generator which will walk the directory tree and allow
you to do something with the files:

  for path, dirs, files in os.walk(directory):
 for filename in files:
filename = os.sep.join(path, filename)
if is_interesting(filename):
do_something(filename)

-tkc






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


Simple server using asyncore/asynchat

2008-01-01 Thread Rick
Hey folks. I'm trying to create a (fairly) simple server that listens for
connections and when it receives one sends a message to the client and then
waits for a response (and would continue to do that). My problem is, every
time my client connects, the server doesn't send the text and then
immediately closes the connection with the client, but DOES print that the
client was connected. Anyone know why? Here's my code:

# conn.py

import socket
import asyncore
import asynchat
import string

host = 'localhost' #socket.gethostname  ()
port = 8017
buf = 1024

class ConnChannel (asynchat.async_chat):

def __init__(self, conn):
self.conn = conn

def handle_connect():
self.send(self.conn, "Hello, Welcome to BasicMUD.\r\n") # it doesn't
do thise
self.numberclients = self.numberclients + 1 # or this
self.send(self.conn, "There are " + self.numberclients + " players
online.") # or this
print "Client connected!" # it prints this

def handle_read(self):
print self.recv(8192)

def handle_write(self):
print "sending"

class ConnTube (asyncore.dispatcher):

def __init__(self, hostd, portd):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM )
self.bind ( ( hostd , portd ) )
self.listen ( 5 )
self.numberclients = 0

def handle_accept(self):
channel, addr = self.accept()
ConnChannel(channel)

connTube = ConnTube(host, port)
asyncore.loop()

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

os.tmpfile()

2008-01-01 Thread jyoung79
Can anyone elaborate on how 'os.tmpfile()' works?  I was thinking it would 
create some sort of temporary file I could quickly add text too and then when I 
was finished would automatically get rid of it.  Here's my questions:

1.  Does it actually create a file somewhere?  If so, where does it store it?  
Does it have to manually be deleted afterwards?
3.  How do you use it?  I tried the following, but it doesn't seem to work:

>>> import os
>>> c = os.tmpfile()
>>> c.write('dude')
>>> c.read()
''
>>> os.path.exists(c)
Traceback (most recent call last):
  File "", line 1, in 
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py",
 line 171, in exists
TypeError: coercing to Unicode: need string or buffer, file found
>>> type(c)

>>> os.path.basename(c)
Traceback (most recent call last):
  File "", line 1, in 
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py",
 line 112, in basename
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py",
 line 77, in split
AttributeError: 'file' object has no attribute 'rfind'
>>> for x in c:
... print x
... 
>>> 

Can you actually 'write' to this file?  And if so, do you have to 'close()' it 
when you're done with it?  Thanks for your help with this...  I'm still 
learning Python and haven't been able to find out much about this in the 
documentation or on-line.

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


Re: Newbie: Why doesn't this work

2008-01-01 Thread petr . jakes . tpc
Steven,
thanks for a nice explanation.

I am trying to experiment a little bit with new-style class and I am
confused why following example always returns 0 (zero). I was
expecting  will return values from 0 to 9 and finaly
an Exception.

class GenExample(object):

def getInfo(self):
for no in range(10):
yield no

myNo=property(getInfo)

gen=GenExample()
print gen.myNo.next()
print gen.myNo.next()
.
.
print gen.myNo.next()

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


Re: Tab indentions on different platforms?

2008-01-01 Thread Ben Finney
Torsten Bronger <[EMAIL PROTECTED]> writes:

> [...] the width of a tab is nowhere defined. It really is a matter
> of the editor's settings.

RFC 678 "Standard File Formats" http://www.ietf.org/rfc/rfc678.txt>:

 Horizontal Tab  

Moves the printer to the next horizontal tab stop.

   The conventional stops for horizontal tabs are every
   eight characters, that is character positions 9, 17, 25,
   ... within the logical page.

Note that it is difficult to enforce these conventions and
it is therefore recommended that horizontal tabs not be used
in document files.

> I, for example, dislike too wide indenting. I use four columns in
> Python and two in Delphi. However, there are Python projects using
> eight spaces for each indentation level.

How many columns to indent source code is an orthogonal question to
how wide an ASCII TAB (U+0009) should be rendered. The former question
is open to matters of style; the latter at least is standardised, even
given the caveats about enforcement.

> If all Python code used tabs, eveybody could use their own
> preferences, for both reading and writing code, and interoperability
> would be maintained nevertheless.

Interoperability isn't the only criterion though. On the contrary,
source code is primarily for reading by programmers, and only
incidentally for reading by the compiler.

-- 
 \"I hate it when my foot falls asleep during the day, because |
  `\ that means it's gonna be up all night."  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.tmpfile()

2008-01-01 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:

> Can anyone elaborate on how 'os.tmpfile()' works?  I was thinking it would 
> create some sort of temporary file I could quickly add text too and then when 
> I was finished would automatically get rid of it.  Here's my questions:
...
> Can you actually 'write' to this file?  And if so, do you have to 'close()' 
> it when you're done with it?  Thanks for your help with this...  I'm still 
> learning Python and haven't been able to find out much about this in the 
> documentation or on-line.

It's a file.  You read strings from it and write strings to it.  It 
isn't a string itself.  Given that what you're trying to do doesn't make 
any sense, it's hard to know where to begin to identify what's confusing 
you.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   And though the odds say improbable / What do they know
-- Stevie Wonder
-- 
http://mail.python.org/mailman/listinfo/python-list


using Tix.FileSelectBox in python

2008-01-01 Thread [EMAIL PROTECTED]
hi
i was using Tix.FileSelectBox to select  imagefiles from a
directory..when i click on image and click my app's okbutton i can
get the selected image name by

self.selimgname=self.myfileselectbox.selection.cget("value")

after this  if i just select a folder and not an image and click
ok then again the myfileselectbox.selection.cget("value") gives
the previously selected image name.

i would like to give an error msg asking the user if he doen't select
an image..how can i do this?

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


Re: Newbie: Why doesn't this work

2008-01-01 Thread Gabriel Genellina
En Wed, 02 Jan 2008 01:11:12 -0300, <[EMAIL PROTECTED]> escribió:

> I am trying to experiment a little bit with new-style class and I am
> confused why following example always returns 0 (zero). I was
> expecting  will return values from 0 to 9 and finaly
> an Exception.
>
> class GenExample(object):
>
> def getInfo(self):
> for no in range(10):
> yield no
>
> myNo=property(getInfo)
>
> gen=GenExample()
> print gen.myNo.next()
> print gen.myNo.next()
> .
> .
> print gen.myNo.next()

Doing it this way, works as intended:

py> gen=GenExample()
py> myNo = gen.myNo
py> print myNo.next()
0
py> print myNo.next()
1
...
py> print myNo.next()
9
py> print myNo.next()
Traceback (most recent call last):
   File "", line 1, in 
StopIteration

Why? I've seen you have read about the descriptor protocol. Methods are  
implemented as non-data descriptors. When you retrieve the "myNo"  
attribute from the "gen" instance, a bound method is created, combining  
the original getInfo function (stored into the class) with the gen  
instance. This is done *each* time the attribute is retrieved, and each  
time you get a different method object. That's why in your original  
example you always got 0: all methods are newly created ones, starting the  
iteration. (After the call finishes, as nobody holds any additional  
reference to it, the method object becomes a candidate to be garbage  
collected and eventually is deleted)

Now it should be clear why my example above does work: I'm using always  
the *same* method object, previously saved into the "myNo" variable.

This also explains a popular optimization technique: move attribute  
lookups out of a critical loop. That is, transforming this:

for item in container:
 out.writerecord(item)

into this:

writerecord = out.writerecord
for item in container:
 writerecord(item)

Of course this should NOT be done blindly.

-- 
Gabriel Genellina

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


Re: os.tmpfile()

2008-01-01 Thread redawgts
Try this:

>>> import os
>>> c = os.tmpfile()
>>> c.write('dude')
>>> c.seek(0)
>>> c.read()
'dude'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tab indentions on different platforms?

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

Ben Finney writes:

> Torsten Bronger <[EMAIL PROTECTED]> writes:
>
>> [...] the width of a tab is nowhere defined. It really is a
>> matter of the editor's settings.
>
> RFC 678 "Standard File Formats"
> http://www.ietf.org/rfc/rfc678.txt>:
>
>  Horizontal Tab  
>
> [...]

As far as I can see, this excerpt of a net standard has been neither
normative nor influential on the behaviour of text editors.

>> I, for example, dislike too wide indenting. I use four columns in
>> Python and two in Delphi. However, there are Python projects
>> using eight spaces for each indentation level.
>
> How many columns to indent source code is an orthogonal question
> to how wide an ASCII TAB (U+0009) should be rendered. [...]

I don't know what you want to say with this.  Obviousy, is is
impossible to indent four columns with 8-columns tabs.  Anyway, my
sentence was supposed just to lead to the following:

>> If all Python code used tabs, everybody could use their own
>> preferences, for both reading and writing code, and
>> interoperability would be maintained nevertheless.
>
> Interoperability isn't the only criterion though. On the contrary,
> source code is primarily for reading by programmers, and only
> incidentally for reading by the compiler.

Well, I, the programmer, want code snippets from different versions
fit together as seemlessly as possible, and I want to use my editor
settings for every piece of Python code that I load into it.

Tschö,
Torsten.

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


Using pexpect with cgi

2008-01-01 Thread vinoj davis
 I am using pexpect with Cgi to ssh into remote machine,Whenever i run a script which does ssh using pexpect from the linux terminal it gives me the correct result, but when i call the script using commands module from the cgi program i am getting the following error.(0, '(256, \'Traceback (most recent call last):\\n  File "/usr/local/https/suid/getdetails.py", line 85, in \\nmain()\\n  File "/usr/local/https/suid/getdetails.py", line 66, in main\\nmac = RemoteCommand(command,passwd)\\n  File "/usr/local/https/suid/getdetails.py", line 42, in RemoteCommand\\nchild = pexpect.spawn(command)\\n  File "/usr/lib/python2.5/site-packages/pexpect.py", line 375, in __init__\\nself.__spawn()\\n  File "/usr/lib/python2.5/site-packages/pexpect..py",
 line 446, in __spawn\\nraise ExceptionPexpect(\\\'Error! pty.fork() failed: \\\' + str(e))\\npexpect.ExceptionPexpect: Error! pty.fork() failed: out of pty devices\')')PLz tell me what is the problem,Thanking you.Regards,     ---ViNOJ DAViS---


   5, 50, 500, 5000 - Store N number of mails in your inbox. Click here.

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

Re: Tab indentions on different platforms?

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

Ben Finney writes:

> Torsten Bronger <[EMAIL PROTECTED]> writes:
>
>> [...] the width of a tab is nowhere defined. It really is a
>> matter of the editor's settings.
>
> RFC 678 "Standard File Formats"
> http://www.ietf.org/rfc/rfc678.txt>:
>
>  Horizontal Tab  
>
> [...]

As far as I can see, this excerpt of a net standard has been neither
normative nor influential on the behaviour of text editors.

>> I, for example, dislike too wide indenting. I use four columns in
>> Python and two in Delphi. However, there are Python projects
>> using eight spaces for each indentation level.
>
> How many columns to indent source code is an orthogonal question
> to how wide an ASCII TAB (U+0009) should be rendered. [...]

I don't know what you want to say with this.  Obviousy, it is
impossible to indent four columns with 8-columns tabs.  Anyway, my
sentence was supposed just to lead to the following:

>> If all Python code used tabs, everybody could use their own
>> preferences, for both reading and writing code, and
>> interoperability would be maintained nevertheless.
>
> Interoperability isn't the only criterion though. On the contrary,
> source code is primarily for reading by programmers, and only
> incidentally for reading by the compiler.

Well, I, the programmer, want code snippets from different origins
fit together as seemlessly as possible, and I want to use my editor
settings for every piece of Python code that I load into it.

Tschö,
Torsten.

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