Friday, February 5, 2010

comp.lang.python - 26 new messages in 10 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* Repost: Read a running process output - 2 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/195cc1de992e13b3?hl=en
* Your beloved python features - 6 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/599b3c9772421ece?hl=en
* C:\Python25\Lib\IDLELIB\idle.pyw won't start - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/0dbc675fff5ecf07?hl=en
* which - 10 messages, 5 authors
http://groups.google.com/group/comp.lang.python/t/5fcc1a3f067c1f50?hl=en
* YAML (was: Python and Ruby) - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/dfe4f6c60032755e?hl=en
* Pickling an extension type subclasses problems - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/9ba740431f0cf33d?hl=en
* method to intercept string formatting % operations - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/f0acce6896bb76cd?hl=en
* Terminating threaded programs - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/3faf7257442cb33f?hl=en
* Drawing a zig-zag Trail in Python? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/b8b3c5802a568680?hl=en
* list.extend([]) Question - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/e742a12b919a473c?hl=en

==============================================================================
TOPIC: Repost: Read a running process output
http://groups.google.com/group/comp.lang.python/t/195cc1de992e13b3?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Feb 5 2010 5:33 am
From: Ashok Prabhu


On Feb 5, 5:58 pm, Alain Ketterlin <al...@dpt-info.u-strasbg.fr>
wrote:
> Ashok Prabhu <ashokprab...@gmail.com> writes:
> >> > p1=Popen('/usr/sunvts/bin/64/vtsk -d',stdout=PIPE,shell=True)
>
> >> Use Popen(['/usr/...','-d'],stdout=PIPE), i.e., no shell.
>
> >> -- Alain.
> > Thanks for the response. However it throws an error. Please find
> > below.
>
> >>>> from subprocess import *
> >>>> p1=Popen('/usr/sunvts/bin/64/vtsk -d',stdout=PIPE)
>
> You forgot to change the monolithic command into a list of words. Since
> you don't use the shell anymore you have to give Popen a pre-parsed
> command line.
>
> -- Alain.

Here is the error again

>>> p1=Popen('/usr/sunvts/bin/64/vtsk','-d',stdout=PIPE)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/subprocess.py", line 494, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer


~Ashok.


== 2 of 2 ==
Date: Fri, Feb 5 2010 5:39 am
From: Ashok Prabhu


On Feb 5, 6:33 pm, Ashok Prabhu <ashokprab...@gmail.com> wrote:
> On Feb 5, 5:58 pm, Alain Ketterlin <al...@dpt-info.u-strasbg.fr>
> wrote:
>
>
>
> > Ashok Prabhu <ashokprab...@gmail.com> writes:
> > >> > p1=Popen('/usr/sunvts/bin/64/vtsk -d',stdout=PIPE,shell=True)
>
> > >> Use Popen(['/usr/...','-d'],stdout=PIPE), i.e., no shell.
>
> > >> -- Alain.
> > > Thanks for the response. However it throws an error. Please find
> > > below.
>
> > >>>> from subprocess import *
> > >>>> p1=Popen('/usr/sunvts/bin/64/vtsk -d',stdout=PIPE)
>
> > You forgot to change the monolithic command into a list of words. Since
> > you don't use the shell anymore you have to give Popen a pre-parsed
> > command line.
>
> > -- Alain.
>
> Here is the error again
>
> >>> p1=Popen('/usr/sunvts/bin/64/vtsk','-d',stdout=PIPE)
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/usr/lib/python2.4/subprocess.py", line 494, in __init__
>     raise TypeError("bufsize must be an integer")
> TypeError: bufsize must be an integer
>
> ~Ashok.

Oops i missed the braces. But still no output.


>>> p1=Popen(['/usr/sunvts/bin/64/vtsk','-d'],stdout=PIPE)
>>> while 1:
... a=p1.stdout.readline()
... print a
...

==============================================================================
TOPIC: Your beloved python features
http://groups.google.com/group/comp.lang.python/t/599b3c9772421ece?hl=en
==============================================================================

== 1 of 6 ==
Date: Fri, Feb 5 2010 5:43 am
From: Bruno Desthuilliers


apeach a écrit :
> I love intuitive type recognition.
>
> no need to 'DIM everything AS Integer' etc.!
>

not to mention the ever hilarious (that is, when you don't have to
maintain it) typical Java idiom:

EveryThing theEveryThing = new EveryThing();

== 2 of 6 ==
Date: Fri, Feb 5 2010 5:45 am
From: Bruno Desthuilliers


Julian a écrit :
> Hello,
>
> I've asked this question at stackoverflow a few weeks ago, and to make
> it clear: this should NOT be a copy of the stackoverflow-thread
> "hidden features of Python".
>
> I want to design a poster for an open source conference, the local
> usergroup will have a table there, and in the past years there were
> some people that came to the python-table just to ask "why should I
> use python?".
>
> For those guys would be a poster quite cool which describes the most
> popular and beloved python features.

My all-time favorite Python feature : it fits my brain.


== 3 of 6 ==
Date: Fri, Feb 5 2010 5:49 am
From: Roald de Vries


On Feb 5, 2010, at 12:03 AM, Julian wrote:

> Hello,
>
> I've asked this question at stackoverflow a few weeks ago, and to make
> it clear: this should NOT be a copy of the stackoverflow-thread
> "hidden features of Python".
>
> I want to design a poster for an open source conference, the local
> usergroup will have a table there, and in the past years there were
> some people that came to the python-table just to ask "why should I
> use python?".
>
> For those guys would be a poster quite cool which describes the most
> popular and beloved python features.
>
> So, may you help me please? If there's a similar thread/blogpost/
> whatever, please give it to me, google couldn't.

My reasoning: I needed a language more powerful than bash, but more
portable and faster to develop (at least small scripts) than C/C++. So
I needed a scripting language. Python, Ruby, Perl, Tcl, ...?

Python seems to be the language with the most libraries available,
programs written in it, OS-support (even runs on my smartphone), has a
good data-model, has a good interactive shell (iPython).

== 4 of 6 ==
Date: Fri, Feb 5 2010 6:42 am
From: Jean-Michel Pichavant


Bruno Desthuilliers wrote:
> Julian a écrit :
>> Hello,
>>
>> I've asked this question at stackoverflow a few weeks ago, and to make
>> it clear: this should NOT be a copy of the stackoverflow-thread
>> "hidden features of Python".
>>
>> I want to design a poster for an open source conference, the local
>> usergroup will have a table there, and in the past years there were
>> some people that came to the python-table just to ask "why should I
>> use python?".
>>
>> For those guys would be a poster quite cool which describes the most
>> popular and beloved python features.
>
> My all-time favorite Python feature : it fits my brain.
Python is simple ... no offense Bruno :D

JM

(sorry couldn't help)


== 5 of 6 ==
Date: Fri, Feb 5 2010 7:24 am
From: Grant Edwards


On 2010-02-04, Julian <mailings@julianmoritz.de> wrote:

> I've asked this question at stackoverflow a few weeks ago, and
> to make it clear: this should NOT be a copy of the
> stackoverflow-thread "hidden features of Python".
>
> I want to design a poster for an open source conference, the
> local usergroup will have a table there, and in the past years
> there were some people that came to the python-table just to
> ask "why should I use python?".
>
> For those guys would be a poster quite cool which describes
> the most popular and beloved python features.

In the fine old tradition:

Python: It sucks less.


A lot less.


--
Grant Edwards grante Yow! You should all JUMP
at UP AND DOWN for TWO HOURS
visi.com while I decide on a NEW
CAREER!!


== 6 of 6 ==
Date: Fri, Feb 5 2010 7:49 am
From: Bruno Desthuilliers


Jean-Michel Pichavant a écrit :
> Bruno Desthuilliers wrote:
>>
>> My all-time favorite Python feature : it fits my brain.
> Python is simple ... no offense Bruno :D

!-)

But FWIW, that's exactly the point : even a stoopid like me can manage
to learn and use Python, and proceed to write working apps without
spending more time reading the doc than actually solving the problem.

==============================================================================
TOPIC: C:\Python25\Lib\IDLELIB\idle.pyw won't start
http://groups.google.com/group/comp.lang.python/t/0dbc675fff5ecf07?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Feb 5 2010 5:49 am
From: Duncan Booth


Anthra Norell <anthra.norell@bluewin.ch> wrote:

>> Using pythonw.exe will start the program with all error output dumped in
>> the bit bucket. Running from a command prompt with python.exe will at
>> least let you see if there are any errors.
>>
> python.exe from the command line works all right in a DOS window. The
> problem must be with idle.pyw. I tried the old idle.pyw (2.4) with the
> new python.exe. (2.5) and that didn't work either.
> What is the bit bucket? If I had a clue, I could go from there. What
> puzzles me is that version 2.4 has been working fine and one wouldn't
> think that the changes from 2.4 to 2.5 would be so extensive as to cause
> a major malfunction. For the time being 2.4 works fine. I'd much prefer
> 2.5, though, because it includes the image library (PIL), whereas 2.4
> cannot even use it.

Bit bucket: http://en.wikipedia.org/wiki/Bit_bucket

If you are seeing nothing at all when running it with python.exe instead of
pythonw.exe then something bizarre must be happening.

My guess would have been that you had a problem importing something: e.g.
if Tkinter isn't installed properly then running Idle under pythonw.exe
would exit with an error message but you wouldn't see the error message.
However since you don't see an error message when running it with
python.exe it isn't that.

Sorry, I'm out of ideas for now.

--
Duncan Booth http://kupuguy.blogspot.com

==============================================================================
TOPIC: which
http://groups.google.com/group/comp.lang.python/t/5fcc1a3f067c1f50?hl=en
==============================================================================

== 1 of 10 ==
Date: Fri, Feb 5 2010 6:21 am
From: mk

if isinstance(cmd, str):
self.cmd = cmd.replace(r'${ADDR}',ip)
else:
self.cmd = cmd

or

self.cmd = cmd
if isinstance(cmd, str):
self.cmd = cmd.replace(r'${ADDR}',ip)


== 2 of 10 ==
Date: Fri, Feb 5 2010 6:30 am
From: Steve Holden


mk wrote:
>
> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)
> else:
> self.cmd = cmd
>
> or
>
> self.cmd = cmd
> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)
>
>
My own preference is for the latter, but I am sure you will find that
opinions are mixed on this. In recent versions of Python you might want
to take the possibility that cmd is Unicode into account by using

id isinstance(cmd, basestring):

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 3 of 10 ==
Date: Fri, Feb 5 2010 6:41 am
From: Jean-Michel Pichavant


mk wrote:
>
> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)
> else:
> self.cmd = cmd
>
> or
>
> self.cmd = cmd
> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)
>
>
I would vote for the first one. But I could use the second as well, I
would'nt fight for it.

What is worrying me the most in your code sample is that self.cmd can
hold diferrent types (str, and something else). That is usually a bad
thing to do (putting None aside).
However, my remark could be totally irrelevant of course, that depends
on the context.

JM

== 4 of 10 ==
Date: Fri, Feb 5 2010 7:15 am
From: mk


Jean-Michel Pichavant wrote:
>
> What is worrying me the most in your code sample is that self.cmd can
> hold diferrent types (str, and something else). That is usually a bad
> thing to do (putting None aside).
> However, my remark could be totally irrelevant of course, that depends
> on the context.

That's a valid criticism - but I do not know how to handle this
otherwise really, because the program can be called with "cmd" to run,
or a script to run (or a directory to copy) and in those cases cmd is None.

I guess I could use

if cmd:
self.cmd = ...


But. Suppose that under some circumstances cmd is not string. What then?

I know that isinstance is typically not recommended, but I don't see
better solution here.


Regards,
mk


== 5 of 10 ==
Date: Fri, Feb 5 2010 7:21 am
From: mk


KDr2 wrote:
> cmd= isinstance(cmd,str) and c.replace('${ADDR}',ip) or cmd

Perlish, but I like that. :-)

Regards,
mk

== 6 of 10 ==
Date: Fri, Feb 5 2010 7:28 am
From: Jean-Michel Pichavant


mk wrote:
> Jean-Michel Pichavant wrote:
>>
>> What is worrying me the most in your code sample is that self.cmd can
>> hold diferrent types (str, and something else). That is usually a bad
>> thing to do (putting None aside).
>> However, my remark could be totally irrelevant of course, that
>> depends on the context.
>
> That's a valid criticism - but I do not know how to handle this
> otherwise really, because the program can be called with "cmd" to run,
> or a script to run (or a directory to copy) and in those cases cmd is
> None.
>
> I guess I could use
>
> if cmd:
> self.cmd = ...
>
>
> But. Suppose that under some circumstances cmd is not string. What then?
>
> I know that isinstance is typically not recommended, but I don't see
> better solution here.
>
>
> Regards,
> mk
>
>
If you can change your program interface, then do it, if not then you're
right you don't have much choice as you are suffering from the program
poor interface.
You can fix this problem by explicitly asking for the thing you want to
do, instead of guessing by inspecting the argument nature.

myProg --help

usage : myProg command [args]
command list:
- cmd: execute the given <arg1> command line
- exec: execute the given script file named <arg1>
- copy: copy <arg1> to <arg2>

example:
>myProg cmd "echo that's cool"
>myProg exec /etc/init.d/myDaemon
>myProg copy /tmp /tmp2

JM


== 7 of 10 ==
Date: Fri, Feb 5 2010 7:42 am
From: John Posner


On 2/5/2010 9:21 AM, mk wrote:
>
> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)
> else:
> self.cmd = cmd
>
> or
>
> self.cmd = cmd
> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)
>
>

(lunatic fringe?)

Last August [1], I offered this alternative:

self.cmd = (cmd.replace(r'${ADDR}',ip)
if isinstance(cmd, str) else
cmd)

But it didn't get much love in this forum!


[1]
http://groups.google.com/group/comp.lang.python/browse_thread/thread/6876917a4d579d59/1f700586f4c4614d?lnk=gst&q=Posner#1f700586f4c4614d


== 8 of 10 ==
Date: Fri, Feb 5 2010 7:49 am
From: Peter Otten <__peter__@web.de>


mk wrote:

> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)
> else:
> self.cmd = cmd
>
> or
>
> self.cmd = cmd
> if isinstance(cmd, str):
> self.cmd = cmd.replace(r'${ADDR}',ip)

Neither.

self.cmd = cmd
self.ip = ip
...
subprocess.call(self.cmd, shell=True, env=dict(ADDR=self.ip))

Please spend a bit more energy on a descriptive subject and an unambiguous
exposition of your problem (in English rather than code) next time.

Peter

== 9 of 10 ==
Date: Fri, Feb 5 2010 7:52 am
From: mk


Jean-Michel Pichavant wrote:
> If you can change your program interface, then do it, if not then you're
> right you don't have much choice as you are suffering from the program
> poor interface.
> You can fix this problem by explicitly asking for the thing you want to
> do, instead of guessing by inspecting the argument nature.
>
> myProg --help
>
> usage : myProg command [args]
> command list:
> - cmd: execute the given <arg1> command line
> - exec: execute the given script file named <arg1>
> - copy: copy <arg1> to <arg2>
>
> example:
> >myProg cmd "echo that's cool"
> >myProg exec /etc/init.d/myDaemon
> >myProg copy /tmp /tmp2
>

I sure can change the interface since I'm the author of the entire
program. But I don't see how I can arrange program in a different way:
the program is supposed to be called with -c parameter (command to run),
-s script to run, or -y file_or_dir_to_copy.

Then, I start instances of SSHThread class to do precisely that,
separately for each ip/hostname:


class SSHThread(threading.Thread):
def __init__(self, lock, cmd, ip, username, sshprivkey=None,
passw=None, port=22, script=None, remotedir=None):

threading.Thread.__init__(self)

self.lock = lock
if isinstance(cmd, str):
self.cmd = cmd.replace(r'${ADDR}',ip)
else:
self.cmd = cmd
self.ip = ip
self.username = username
self.sshprivkey = sshprivkey
self.passw = passw
self.port = port
self.conobj = None
self.conerror = ''
self.msgstr = ''
self.confailed = True
if script:
self.setpathinfo(script, remotedir=remotedir)
self.sentbytes = 0
self.finished = False
self.abort = False

It gets called like this:

th = SSHThread(lock, opts.cmd, ip, username=username,
sshprivkey=opts.key, passw=passw, port=port, script=opts.script,
remotedir=opts.remotedir)


..where all the options are parsed by ConfigParser.OptionParser(). So
they are either strings, or Nones.

So in this context this is fine. But I wanted to make the class more
robust. Perhaps I should do smth like this before setting self.cmd?

assert isinstance(cmd, basestring) or cmd is None, "cmd should be string
or None"

and then:

if cmd:
self.cmd = cmd.replace..


?

Entire source code is here:

http://python.domeny.com/cssh.py

regards,
mk

== 10 of 10 ==
Date: Fri, Feb 5 2010 7:54 am
From: Jean-Michel Pichavant


John Posner wrote:
> On 2/5/2010 9:21 AM, mk wrote:
>>
>> if isinstance(cmd, str):
>> self.cmd = cmd.replace(r'${ADDR}',ip)
>> else:
>> self.cmd = cmd
>>
>> or
>>
>> self.cmd = cmd
>> if isinstance(cmd, str):
>> self.cmd = cmd.replace(r'${ADDR}',ip)
>>
>>
>
> (lunatic fringe?)
>
> Last August [1], I offered this alternative:
>
> self.cmd = (cmd.replace(r'${ADDR}',ip)
> if isinstance(cmd, str) else
> cmd)
>
> But it didn't get much love in this forum!
>
>
> [1]
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/6876917a4d579d59/1f700586f4c4614d?lnk=gst&q=Posner#1f700586f4c4614d
>
Heresy !

JM

==============================================================================
TOPIC: YAML (was: Python and Ruby)
http://groups.google.com/group/comp.lang.python/t/dfe4f6c60032755e?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Feb 5 2010 6:22 am
From: Lou Pecora


In article <00f4bb3a$0$15566$c3e8da3@news.astraweb.com>,
Steven D'Aprano <steve@REMOVE-THIS-cybersource.com.au> wrote:

> On Thu, 04 Feb 2010 09:57:59 -0500, Lou Pecora wrote:
>
> > Well, that looks a bit more complicated than I would like, but maybe
> > it's doing more stuff than I can grok. Here's what I needed and how I
> > did it in Python:
> [...]
> > # Reading same list in:
> > instr=fp.readline()
> > inlist=eval(instr)
> > x1,y1,astr1,z1= inlist
> >
> >
> > That's what I needed. 3 lines to write or read a inhomogeneous
> > collection of variables.
>
> Easy, but also quick and dirty -- good enough for small scripts, but not
> really good enough for production applications.
>
>
> > I can add more variables, shuffle the order,
> > whatever without messing with formatting, etc.
>
> This is nice and easy. But there are at least four catches:
>
>
> * you can't safely treat the data file as human-editable
> (although a sufficiently careful and Python-aware user could edit it)
>
> * you can't use any data that isn't a built-in, or that contains
> something that is not a built-in
>
> * there may be reliability issues with floats - you're at the mercy of
> changes to the underlying repr of float objects, and it almost certainly
> will blow up in your face if you get an inf or nan (at least prior to
> Python 2.6)
>
> * you're using eval, which is a security risk if you can't trust the
> source of the data file.
>
> However, be aware that neither marshal nor pickle guarantees to be safe
> against malicious data either. The docs for both warn against using them
> on untrusted data. YAML or JSON *might* be safer, I haven't looked.

I understand where you are coming from: Production Code. I was just
making a point about Python and my code is only used by me. I can edit
the file for the simple I/O I do. I am not recommending this way for
everyone. Just an example.

--
-- Lou Pecora

==============================================================================
TOPIC: Pickling an extension type subclasses problems
http://groups.google.com/group/comp.lang.python/t/9ba740431f0cf33d?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Feb 5 2010 6:25 am
From: Gaetan de Menten


Hi all,

I am trying to write an (optional!) C extension for SQLAlchemy, and I
am struggling to make an extension type picklable *and* using the same
format as the pure Python version (so that computers with the C
extension can unpickle pickles from computers without it and
vice-versa). Also the extension type (MyBase in the example code
below) only serves as a base class for the type that get pickled
(MyPythonType). MyPythonType also has further subclasses and those
should be picklable too.

My setup is as follow:

On the Python side:
================

try:
from cextension import MyBase
except ImportError:
class MyBase(object):
__slots__ = ('a', 'b', 'c')
def __init__(self, a, b, c):
self.a, self.b, self.c = a, b, c

def __getstate__(self):
...

def __setstate__(self, state):
...
...


class MyPythonType(MyBase):
...

On the .c side:
===========
I implemented a reduce method, which returns

Py_BuildValue("(O(s)N)", Py_TYPE(self), "__state__", state);

and in my BaseRowProxy_init method, I check the number of arguments,
whether the "__state__" marker is present and unpack the state if it
is. This makes the type nicely pickleable, but this is obviously not
the same "pickle format" as the Python version.

What would you recommend in this kind of situation? I'm a bit tired of
trial and error... My last hope is to define __reduce__ on the Python
side too, and make it use a module-level "reconstructor" function as
follow:

def mypythontype_reconstructor(cls, state):
obj = object.__new__(cls, state):
....
return obj

Will this work? Any other idea?

Thanks in advance,
--
Gaëtan de Menten

==============================================================================
TOPIC: method to intercept string formatting % operations
http://groups.google.com/group/comp.lang.python/t/f0acce6896bb76cd?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Feb 5 2010 6:57 am
From: bradallen


Hello,

For container class derived from namedtuple, but which also behaves
like a dictionary by implementing __getitem__ for non-integer index
values, is there a special reserved method which allows intercepting %
string formatting operations? I would like for my container type to
behave appropriately depending on whether the string formatting
operation has a string like this :

"whatever %s yadayada" % mycontainer # needs to act like a tuple

"whatever %(key)s yadayada" % mycontainer # needs to act like a
dictionary

I looked through the Python data model docs at <http://docs.python.org/
reference/datamodel.html#emulating-container-types
> but only found
this:

"If the left operand of a % operator is a string or Unicode object, no
coercion takes place and the string formatting operation is invoked
instead."

Thanks!

== 2 of 2 ==
Date: Fri, Feb 5 2010 7:49 am
From: Jean-Michel Pichavant


bradallen wrote:
> Hello,
>
> For container class derived from namedtuple, but which also behaves
> like a dictionary by implementing __getitem__ for non-integer index
> values, is there a special reserved method which allows intercepting %
> string formatting operations? I would like for my container type to
> behave appropriately depending on whether the string formatting
> operation has a string like this :
>
> "whatever %s yadayada" % mycontainer # needs to act like a tuple
>
> "whatever %(key)s yadayada" % mycontainer # needs to act like a
> dictionary
>
> I looked through the Python data model docs at <http://docs.python.org/
> reference/datamodel.html#emulating-container-types> but only found
> this:
>
> "If the left operand of a % operator is a string or Unicode object, no
> coercion takes place and the string formatting operation is invoked
> instead."
>
> Thanks!
>
>
class toto:
def __getitem__(self, key):
return 'paf'
def __str__(self):
return 'pif'
def toTuple(self):
return (1,2,3)


1/ print '%s %s %s' % toto().toTuple()
'1 2 3'
2/ print '%(key)s ' % toto()
'paf'
3/ print '%s' % toto()
'pif'


1/ I don't know how to spare the explicit toTuple conversion, supporting
tuple() would be tedious
2/ thanks to __getitem__ (duck typing)
3/ thanks to __str__

Anyway why would you want to use the tuple form ? it's beaten in every
aspect by the dictionary form.


JM

"If you need something call me, I'll tell you how to live without it"
(Coluche, about politicians)

==============================================================================
TOPIC: Terminating threaded programs
http://groups.google.com/group/comp.lang.python/t/3faf7257442cb33f?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Feb 5 2010 7:25 am
From: mk


Hello everyone,

I have a problem with a threaded program: it frequently hangs on sys.exit.

The problem is that my program uses threads which in turn use paramiko
library, which itself is threaded.

I try to gracefully close the threads (below), but it doesn't always
work, if paramiko calls happen to be at stage of negotiating ssh
connection or smth similar.

The only workable solution I have is a program sending itself SIGKILL,
which makes it terminated by OS (I think so).

Is there any way to brutally close the threads? I know that normally
that should not be done, but shutdown when you don't care about writing
out to disk is the only situation where it doesn't apply.

def ctrlchandler(signal, frame):
print
print ENDC + "Terminating on Ctrl-C, closing threads for:",
while queue:
for ip, th in queue:
print ip,
try:
lock.acquire()
th.abort = True
lock.release()
except RuntimeError:
pass
queue.remove((ip,th))
print
pid = os.getpid()
print "Finished closing threads."
# suicide - it's the only way of preventing frequent hangup on sys.exit
os.kill(pid, SIGTERM)
os.kill(pid, SIGKILL)
sys.exit(0)


==============================================================================
TOPIC: Drawing a zig-zag Trail in Python?
http://groups.google.com/group/comp.lang.python/t/b8b3c5802a568680?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Feb 5 2010 7:39 am
From: "W. eWatson"


I'd like to draw something like an animal track. Between each point is a
line. Perhaps the line would have an arrow showing the direction of
motion. There should be x-y coordinates axises. PIL? MatPlotLib, ??

==============================================================================
TOPIC: list.extend([]) Question
http://groups.google.com/group/comp.lang.python/t/e742a12b919a473c?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Feb 5 2010 7:55 am
From: aahz@pythoncraft.com (Aahz)


In article <088e7a24-b0d0-4d43-bee7-193e5eaefe57@b7g2000pro.googlegroups.com>,
Dan Brown <fsenzeru@gmail.com> wrote:
>
>Why does extending a list with the empty list result in None? It
>seems very counterintuitive to me, at least --- I expected ['a'].extend
>([]) to result in ['a'], not None.

http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list
--
Aahz (aahz@pythoncraft.com) <*> http://www.pythoncraft.com/

import antigravity


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

No comments:

Post a Comment