Assertion in Python

2006-10-05 Thread vmalhotra
Hi All,

I want to do verification in my scripts. So for that what i am doing
here are shown below:

1. Telnet to one router.
2. Configure router.
3. Configure routing.

Now after doing all these i have to check showinterfaces. So i execute
command show interface and saved the output in one file.

Now the problem which i am facing is how to do assertion from that
output. e.g output is something like this

eth0 is up
  OSPF not enabled on this interface
eth1 is up
  Internet Address 192.168.1.2/24, Area 0.0.0.0
  Router ID 192.168.1.2, Network Type BROADCAST, Cost: 10
  Transmit Delay is 1 sec, State DR, Priority 1
  Designated Router (ID) 192.168.1.2, Interface Address 192.168.1.2
  No backup designated router on this network
  Timer intervals configured, Hello 10, Dead 40, Wait 40, Retransmit 5
Hello due in 00:00:00
  Neighbor Count is 0, Adjacent neighbor count is 0
eth2 is up
  OSPF not enabled on this interface
eth3 is down
  OSPF not enabled on this interface
lo is up
  OSPF not enabled on this interface
sit0 is down
  OSPF not enabled on this interface

In this i want to check Designated Router (ID) 192.168.1.2.

If this is the same Ip which i have gice in configuration then test
case will get pass otherwise Fail.

Can somebody send me the code how to do this.

Thanks in Advance
Vikram Malhotra

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


Re: Python/Tkinter crash.

2006-10-05 Thread Eric Brunel
On Wed, 04 Oct 2006 20:02:56 +0200, Hendrik van Rooyen  
<[EMAIL PROTECTED]> wrote:
>  "Eric Brunel" <[EMAIL PROTECTED]> wrote:
>> I know the problem happens sometimes on one of my Tkinter applications,
>> but I never succeeded in reproducing it systematically. I've browsed the
>> tcl bugs, but didn't find anything. Maybe you'll be luckier than I... If
>> you are, I'm interested in any hint you can find.
>
> Ouch! - this is a bit the wrong answer...

Sorry for that. I realize I wasn't very helpful, here...

> What I have seen, in mucking about today, is that it seems to be related  
> to
> threading - I have a silly sort of thread that runs, updating my meters,  
> more or
> less continuously, to simulate data from the field - it just adds some  
> values to
> the seven display variables and calls the update methods that delete and  
> redraw
> the arcs representing the analogue style meters, deleting and replacing  
> the text
> objects that show the values, and then it sleeps for a while, and does  
> it all
> again.
>
> At the same time, one other thread (other than the main thread), can be  
> created
> to move a component on the canvas around by calling its delete and draw
> methods. - but this is also done more or less continuously, as a new  
> thread is
> created as soon as the previous one dies to move the next object around.
>
> Now these two things are asynchronous with each other, so that given  
> enough
> time, they are bound to make calls to Tkinter in a re-entrant fashion,  
> and I
> suspect that it is this that is causing the problem - my "evidence" for  
> this is
> that I implemented a boolean as a sort of "lock" and had the Meter  
> updating back
> down in favour of the other animation to try and avoid any sort of re -  
> entrancy
> to the Tkinter canvas object's  delete and draw methods...

AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize  
the calls from different threads may seem to work (I never tested it  
actually), but the safest way I found to use threads with Tkinter was to  
call it only from the thread where the main loop executes. The only thing  
that seems to work reliably in secondary threads is to generate custom  
events (widget.event_generate('<>', when='tail')), and to  
treat them in Tkinter's thread via bindings  
(widget.bind('<>', treatment_command)). This makes things a  
bit messy, but it works quite well.

Now, as I said before, someone reported that he *did* get the error you  
got from time to time. So maybe the problem I have is not the same as  
yours, or maybe there are some cases in my application where Tkinter stuff  
still gets called directly from secondary threads. I'll try to investigate  
that when I've time and I'll keep you informed.

HTH a little this time...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to use a non open source bug tracker?

2006-10-05 Thread Steve Holden
Ben Finney wrote:
> Steve Holden <[EMAIL PROTECTED]> writes:
> 
> 
>>And I'd prefer it if you'd drop this subject. So, if you have
>>nothing new to say, kindly leave it.
> 
> 
> I'm happy to, but:
> 
> 
>>You appear to be prepared to go to any length short of providing
>>effort to support the open source tracker.
> 
> 
> This was addressed in a previous post. I don't have the skills nor the
> resources to do this. Yes, as has been pointed out, it actually *is*
> far less effort to point out problems, than to solve them. That
> doesn't detract from the value of pointing out problems.
> 
> This thread was started on the shock of realising that a non-free tool
> was even being *considered* for the new Python bug tracker. Those are
> the terms on which I've been arguing.
> 
> Apparently there are some people who *have* put themselves forward to
> support a free-software tool. Great! My point all along has been that
> Python's developers are well advised to consider *only* free-software
> tools for supporting development of Python, and that from among those
> the best tool for the job should be chosen.
> 
> As you say, nothing new has been said now for a while, so in the
> absence of that I'm happy to leave it here.
> 
In case readers are puzzled by the absence of the message to which Ben 
replies above I should perhaps explain that I cancelled it having 
decided that its language was immoderate and unfair to Ben.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Python/Tkinter crash.

2006-10-05 Thread Fredrik Lundh
Eric Brunel wrote:

> AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize  
> the calls from different threads may seem to work (I never tested it  
> actually), but the safest way I found to use threads with Tkinter was to  
> call it only from the thread where the main loop executes.

the Tkinter binding contains some code that attempts to deal with re- 
entrant calls, but I don't know/remember to what extent it's actually 
supposed to work (in other words, if the observed problems are bugs or 
just limitations).

(maybe Martin's memory is better?)

anyway, I usually play it safe and make sure to use a single thread to 
deal with the UI.



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


Re: How can I correct an error in an old post?

2006-10-05 Thread Tim Roberts
Jorgen Grahn <[EMAIL PROTECTED]> wrote:
>
>On Mon, 02 Oct 2006 16:36:24 +0100, Steve Holden <[EMAIL PROTECTED]> wrote:
>
>> I'd appreciate it if all 
>> concerned would close this thread now.
>
>I think you are overreacting. This was a thread with three (3) postings, in
>a high-volume newsgroup, with no indication that it would continue (except
>maybe with a pointer to whatever posting the OP wanted to correct, or to his
>correction).

I'm confused.  I assumed Steve was just joking with his original request.
Although it might be mirrored on a web site somewhere, this is a Usenet
newsgroup.  It is impossible to "close" a thread.  The concept simply does
not exist.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hex sending

2006-10-05 Thread Tim Roberts
"hiroc" <[EMAIL PROTECTED]> wrote:

>s.send("abc") # send test string
>
>I need to send hex:"10 06 00 0f 02 bc d1" instead of "abc"
>
>hoW?

One ugly way is
  s.send( "\x10\x06\x00\x0f\x02\xbc\xd1" )
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Assertion in Python

2006-10-05 Thread Gabriel Genellina

At Thursday 5/10/2006 04:09, vmalhotra wrote:


Now the problem which i am facing is how to do assertion from that
output. e.g output is something like this

eth0 is up
  OSPF not enabled on this interface
eth1 is up
  Internet Address 192.168.1.2/24, Area 0.0.0.0
  Router ID 192.168.1.2, Network Type BROADCAST, Cost: 10
  Transmit Delay is 1 sec, State DR, Priority 1
  Designated Router (ID) 192.168.1.2, Interface Address 192.168.1.2
  No backup designated router on this network
  Timer intervals configured, Hello 10, Dead 40, Wait 40, Retransmit 5
Hello due in 00:00:00
  Neighbor Count is 0, Adjacent neighbor count is 0
eth2 is up
  OSPF not enabled on this interface
eth3 is down
  OSPF not enabled on this interface
lo is up
  OSPF not enabled on this interface
sit0 is down
  OSPF not enabled on this interface

In this i want to check Designated Router (ID) 192.168.1.2.


This is the idea (assuming you have already read and split the output 
on lines):


for line in output:
  line = line.strip()
  if line.startswith('Designated Router (ID)'):
ipReadStr = line[line.find('(ID)')+4:] # just before the IP starts
ipReadStr = ipReadStr.split(',',1)[0].strip() # up to the next ","
assertEqual(ipReadStr, ipExpected)
break
else:
fail('"Designated Router (ID)" not found')


Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: hex sending

2006-10-05 Thread Paul Rubin
"hiroc" <[EMAIL PROTECTED]> writes:
> s.send("abc") # send test string
> I need to send hex:"10 06 00 0f 02 bc d1" instead of "abc"

See the binascii module:

   import binascii

   # a2b_hex stands for "ascii to binary conversion, hex format"
   # you must remove the spaces
   binary = binascii.a2b_hex ("1006000f02bcd1")

   s.send (binary)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Long Tkinter Menu

2006-10-05 Thread Eric Brunel
On Thu, 05 Oct 2006 02:33:54 +0200, Dustan <[EMAIL PROTECTED]> wrote:

> I don't know if this is because of Tkinter (ie Tk) itself or the
> Windows default way of handling things, but when I create a very long
> menu (my test is shown below), the way it displays is rather sucky; the
> menu stretches from the top of the moniter's window to the bottom (no
> matter the size of the actual application).
>
> Is there any alternative format for how a long menu gets displayed? It
> would be nice if say, I could make the menu only go to the borders of
> the application itself (in this case, not that long).

To limit the menu in the application window, will be difficult. But here  
are two ways of automatically limiting the number of entries that can  
appear in a menu by specializing the Tkinter Menu class:

--
 from Tkinter import *

class LongMenu(Menu):
   """
   Automatically creates a cascade entry labelled 'More...' when the
   number of entries is above MAX_ENTRIES.
   """

   MAX_ENTRIES = 20

   def __init__(self, *args, **options):
 Menu.__init__(self, *args, **options)
 self.nextMenu = None

   def add(self, itemType, cnf={}, **kw):
 if self.nextMenu is not None:
   return self.nextMenu.add(itemType, cnf, **kw)
 nbEntries = self.index(END)
 if nbEntries < LongMenu.MAX_ENTRIES:
   return Menu.add(self, itemType, cnf, **kw)
 self.nextMenu = LongMenu(self)
 Menu.add(self, 'cascade', label='More...', menu=self.nextMenu)
 return self.nextMenu.add(itemType, cnf, **kw)


class AutoBreakMenu(Menu):
   """
   Automatically adds the 'columnbreak' option on menu entries to make
   sure that the menu won't get too high.
   """

   MAX_ENTRIES = 20

   def add(self, itemType, cnf={}, **kw):
 entryIndex =  1 + (self.index(END) or 0)
 if entryIndex % AutoBreakMenu.MAX_ENTRIES == 0:
   cnf.update(kw)
   cnf['columnbreak'] = 1
   kw = {}
 return Menu.add(self, itemType, cnf, **kw)



if __name__ == '__main__':
   root = Tk()

   menubar = Menu(root)

   def fillMenu(menu):
 for i in xrange(100):
   menu.add_command(label=str(i), command=root.quit)
 menu.add_command(label="Exit", command=root.quit)

   menu1 = LongMenu(menubar, tearoff=0)
   fillMenu(menu1)
   menu2 = AutoBreakMenu(menubar, tearoff=0)
   fillMenu(menu2)

   menubar.add_cascade(label="Test1", menu=menu1)
   menubar.add_cascade(label="Test2", menu=menu2)

   root.config(menu=menubar)

   root.mainloop()
--

If your application is more complicated than that (e.g if you insert menu  
entries after the first adds), you'll have to change the code above a bit,  
since it doesn't handle calls to insert at all. But you get the idea.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Universe Set

2006-10-05 Thread Duncan Booth
Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:

> Jorgen Grahn wrote:
>> - the wildcard object, which compares equal to everything else
>> - infinite xrange()s
>> - the black hole function 'def f(*args): pass'
>> - the identity function 'def f(x): return x'
> 
> Any use cases for these?
> 

I guess the first one could be useful if you want to compare two data 
structures but prune part of the structure in the comparison (e.g. in a 
unit test assertion). So not forgetting that this only works when the 
wildcard is on the left of the comparison:

>>> class DontCareClass(object):
def __eq__(self, other):
return True


>>> dontcare = DontCareClass()
>>> [1, dontcare, 3]==[1, 2, 3]
True
>>> [1, dontcare, 3]==[1, 4, 3]
True
>>> [1, dontcare, 3]==[1, 4, 2]
False

I think for more general use though it's a non-starter. If Python had it 
builtin it should compare equal in *all* situations and what on earth 
should aDict[dontcare] do?

I can think of one use for a black hole function, but it is very specific. 
It would be kind of nice to have a variation on 'super' which traps 
AttributeError and returns the black hole instead, or perhaps just an 
optional third argument for a default to return (c.f. dict.get). So you 
could write:

class C(object):
def method(self, arg):
super(C, self, blackhole).method(arg)
... whatever ...

and method would call any base class definition of method but not care if 
there isn't one. The alternative to this is either to catch and ignore the 
exception (which is a pain), or better to create a dummy base class which 
implements the interface but doesn't propagate the calls.

I suppose the same argument could be made for any pattern of calling the 
result of getattr when the attribute might not exist. Replace:

m = getattr(obj, key, None)
if m is not None:
   m(something)
or:

   if hasattr(obj, 'somekey'):
   obj.somekey(whatever)

with:

getattr(obj, key, blackhole)(something)

The catch here is that the current pattern often has an 'else' clause as 
well and you can't replace those ones with blackhole.

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


Applications written in TkInter

2006-10-05 Thread Franz Steinhaeusler
Hi,

I wonder, if there is a site with a collection
of written TkInter programs.

I did not find any summary.

for pyGtk there exist for example:

http://www.pygtk.org/applications.html

and for wxPython:

http://wiki.wxpython.org/index.cgi/wxPythonPit_Apps

-- 
Franz Steinhaeusler

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


Re: Where is Python in the scheme of things?

2006-10-05 Thread Bruno Desthuilliers
gord wrote:
> As a complete novice in the study of Python, I am asking myself where this 
> language is superior or better suited than others. For example, all I see in 
> the tutorials are lots of examples of list processing, arithmetic 
> calculations - all in a DOS-like environment.

s/DOS-like/command line/

The command line interface is widely used on unix-like systems, and is
very handy for a lot of things.

> What is particularly disappointing is the absence of a Windows IDE, 
> components and an event driven paradigm. 

Disappointing ? Python is a general-purpose, cross-platform language,
not a Windows-only GUI-only environment. What you're looking for does
exist, but as 3rd part libs and programs. You could check Boa
Constructor (a wxPython based Delphi-like RAD/IDE), or any combination
of a Windows-compatible GUI toolkit / GUI builder / IDE.

> How does Python stand relative to 
> the big 3, namely Visual C++, Visual Basic and Delphi?

Ever tried writing a cross-platform web application server with any of
these "big 3" ?

> I realize that these 
> programming packages are quite expensive 

and Windows-only, and proprietary...

> now while Python is free 

free as in "free beer", yes, but also free as in "free speech". And
Python is portable too (most of my programs would run on Windows or
MacOS X or BSD etc without any modification).

> (at least 
> for the package I am using - ActivePython).

> Please discuss where Python shines.

Application programming and admin scripts. Note that application
programming doesn't imply GUI - I'm mostly doing web development FWIW.

Now if you're doing Windows-only, Python is quite good with COM/ActiveX
etc AFAIK.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to use a non open source bug tracker?

2006-10-05 Thread Georg Brandl
Ilias Lazaridis wrote:
> Giovanni Bajo wrote:
>> Hello,
>>
>> I just read this mail by Brett Cannon:
>> http://mail.python.org/pipermail/python-dev/2006-October/069139.html
>> where the "PSF infrastracture committee", after weeks of evaluation, 
>> recommends
>> using a non open source tracker (called JIRA - never heard before of course)
>> for Python itself.
>>
>> Does this smell "Bitkeeper fiasco" to anyone else than me?
>> --
>> Giovanni Bajo
> 
> Fascinating.
> 
> The python foundation suggests a non-python non-open-source bugtracking
> tool for python.

Actually, it suggests two bugtracking tools, one of them written in
Python.

> It's like saying: "The python community is not able to produce the
> tools needed to drive development of python forward."

No, it's saying: "if the Python community is able to provide the
required amount of time to do the admin work, we'll use the
tool written in Python."

> Anyway. The whole selection process is intransparent.

Steve has already pointed you to the wiki page.

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


Re: Python/Tkinter crash.

2006-10-05 Thread Hendrik van Rooyen
 "Russell E. Owen" <[EMAIL PROTECTED]> wrote:


> In article <[EMAIL PROTECTED]>,
>  "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>
> >Hi,
> >
> >I get the following:
> >
> >[EMAIL PROTECTED]:~/Controller/lib> python display.py
> >UpdateStringProc should not be invoked for type font
> >Aborted
> >...
> >Everything seems to work fine. - there is a thread that runs to move the
meter
> >values around continuously, and this has been stable for some time now, and I
> >can get the various "machine" parts to move around the screen by pushing the
> >buttons...
>
> You mention threads several times in your posting. Do you have multiple
> threads talking to Tkinter? If so, try recoding to avoid this (e.g. by
> having the background threads communicate with the main thread via
> Queues).
>
> -- Russell

I am not sure how to do this - once I have called the Tkinter mainloop - that
main thread is essentially event driven - and figuring out how to get it to poll
a queue for content is not obvious - I suppose I could arrange some external
wake up event that I could activate to make it look at the queue - must read up
on this...

Thanks it is a good idea as it will make the interface cleaner, and as I have to
sort out inter process communication anyway it will make sense to also use a
queueing mechanism between the threads in this display process.

There is already one queue defined - but its a hack as I use it to pass the main
threads id to get around the problem of referring to a class before its
defined...

- Hendrik


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


Re: Python/Tkinter crash.

2006-10-05 Thread Hendrik van Rooyen
 "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>  "Eric Brunel" <[EMAIL PROTECTED]> wrote:
>
>
> > On Wed, 04 Oct 2006 10:33:55 +0200, Hendrik van Rooyen
> > <[EMAIL PROTECTED]> wrote:
> >
> > > Hi,
> > >
> > > I get the following:
> > >
> > > [EMAIL PROTECTED]:~/Controller/lib> python display.py
> > > UpdateStringProc should not be invoked for type font
> > > Aborted
> > >
> > > and I am back at the bash prompt - this is most frustrating, as there is
> > > no
> > > friendly traceback to help me guess where its coming from.
> > >
> > > And what is worse, the script runs for a varying time before it simply
> > > exits
> > > like this.
> > >
> > > What can I do to dig deeper to try to find a clue? - I don't even know
> > > if its
> > > Python, Tkinter or Linux...
> >
> > Neither of them: it's a tcl problem. The message you get is in the file
> > generic/tclObj.c in the tcl source directory.
> >
> > I know the problem happens sometimes on one of my Tkinter applications,
> > but I never succeeded in reproducing it systematically. I've browsed the
> > tcl bugs, but didn't find anything. Maybe you'll be luckier than I... If
> > you are, I'm interested in any hint you can find.
>
> Ouch! - this is a bit the wrong answer...
>
> What I have seen, in mucking about today, is that it seems to be related to
> threading - I have a silly sort of thread that runs, updating my meters, more
or
> less continuously, to simulate data from the field - it just adds some values
to
> the seven display variables and calls the update methods that delete and
redraw
> the arcs representing the analogue style meters, deleting and replacing the
text
> objects that show the values, and then it sleeps for a while, and does it all
> again.
>
> At the same time, one other thread (other than the main thread), can be
created
> to move a component on the canvas around by calling its delete and draw
> methods. - but this is also done more or less continuously, as a new thread is
> created as soon as the previous one dies to move the next object around.
>
> Now these two things are asynchronous with each other, so that given enough
> time, they are bound to make calls to Tkinter in a re-entrant fashion, and I
> suspect that it is this that is causing the problem - my "evidence" for this
is
> that I implemented a boolean as a sort of "lock" and had the Meter updating
back
> down in favour of the other animation to try and avoid any sort of re -
entrancy
> to the Tkinter canvas object's  delete and draw methods...
>
> Now the Jury is still out on this - it seems to have helped, as the thing has
> been running for some hours now without crashing - but maybe I have just
applied
> a band aid to sword cut - I don't know - if it runs through the night I will
> feel much better...
>
> Will update again as soon as I have more data...

OK - It has run through the night and as I type it is still running, so the band
aid has helped a bit...

Eric - if you are interested and contact me, then I will comment out the "fix"
and email you the bits that you need to run this horror - if you need a reliably
failing thingy to study the problem with :-)
It was your post yesterday or so in another thread here that prompted me to try
this style of fix... Thank you.

BTW - I am curious - in your app that exhibits the same crash - what did you do
to work around the problem ? - Is it also running a thread and calling methods
that are normally event driven commands in the main thread?  Or two other
threads like me?  It would be interesting to try to spot any similarities...

Is it even allowed to asynchronously call a main thread method from another
thread? - it seems to work - but I am not sure why it does - what is the main
thread's mainloop doing while this is going on?  - your other comment in the
other thread here implies that it is a strict no - no...  Is it safe to call
invoke from another thread? - what is the difference between calling invoke and
calling the bound method directly?

- Hendrik



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


Re: Python to use a non open source bug tracker?

2006-10-05 Thread Fredrik Lundh
Georg Brandl wrote:

>> The python foundation suggests a non-python non-open-source bugtracking
>> tool for python.
> 
> Actually, it suggests two bugtracking tools, one of them written in
> Python.

the announcemant's subject line said "recommendation for a new issue 
tracker", though; not "we need the community's help before we can make a 
final recommendation".

in fact, only 20% of the announcement talked about Python; the rest was 
something that looked a lot like a press release from the non-python 
hosting company, so it's not that strange that people missed the few 
sentences in the middle that explained that the subject line wasn't 
entirely accurate.



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


Re: Python to use a non open source bug tracker?

2006-10-05 Thread Georg Brandl
Fredrik Lundh wrote:
> Georg Brandl wrote:
> 
>>> The python foundation suggests a non-python non-open-source bugtracking
>>> tool for python.
>> 
>> Actually, it suggests two bugtracking tools, one of them written in
>> Python.
> 
> the announcemant's subject line said "recommendation for a new issue 
> tracker", though; not "we need the community's help before we can make a 
> final recommendation".

Granted.

> in fact, only 20% of the announcement talked about Python; the rest was 
> something that looked a lot like a press release from the non-python 
> hosting company, so it's not that strange that people missed the few 
> sentences in the middle that explained that the subject line wasn't 
> entirely accurate.

I actually stopped reading after Brett's signature, so I didn't have the
20% figure in my mind :)

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


Re: Python/Tkinter crash.

2006-10-05 Thread Paul Rubin
"Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
> I am not sure how to do this - once I have called the Tkinter
> mainloop - that main thread is essentially event driven - and
> figuring out how to get it to poll a queue for content is not
> obvious - I suppose I could arrange some external wake up event that
> I could activate to make it look at the queue - must read up on
> this...

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to static members from inside a method decorator?

2006-10-05 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> I'm developing a library at the moment that involves many classes, some
> of which have "exposed" capabilities.  I'm trying to design a nice
> interface for both exposing those capabilities, and inspecting
> instances to find out what capabilities they have.
> 
> At the moment, I'm leaning towards a superclass (Exposed) that defines
> a static method which is a decorator (expose) such that any derived
> class can mark a method with @Exposed.expose and it will then be later
> returned by getExposedMethods(), a la:
> 
> class Exposed:
>   @staticmethod
>   def expose( f ):
> ...
> 
>   def getExposedMethods( self ):
> ...
> 
> class Person( Exposed ):
>   @Exposed.expose
>   def talk( self, ... ):
> ...
> 
> I'm trying to implement the decorator by having it populate a static
> member list of whatever class it's in with a reference to the method.
> getExposedMethods() would then return the contents of each of those
> lists from itself back to Exposed in the class hierarchy.  The first
> problem was that having a reference to the method (i.e. talk()) does
> not allow you to get a reference to the enclosing class (I had hoped
> im_class would lead me there). 

Not yet. When your decorator is called, the class object is not yet
created, and what you are decorating is a plain function.

> The real hiccup was that explicitly
> passing the class as an argument to the decorator generates a undefined
> global name error, presumably because at that point of execution the
> class object hasn't been fully created/initialised.

Exactly.

> So how can this be done? 

The simplest thing is to use a two-stages scheme : mark the functions as
exposed, then collect them:

def expose(func):
  func._exposed = True
  return func

def exposed(obj):
  return callable(obj) and getattr(obj, '_exposed', False)

class Exposing(object):
  @classmethod
  def get_exposed_methods(cls):
try:
  exposeds = cls._exposed_methods
except AttributeError:
  exposeds = []
  for name in dir(cls):
obj = getattr(cls, name)
if exposed(obj):
  exposeds.append(obj)
  cls._exposed_methods = exposeds
return exposeds

class Parrot(Exposing):
  @expose
  def parrot(self, what):
return "%s says %s" % (self, str(what))



HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


embedding python -- windows specify problems

2006-10-05 Thread John Pye
Hi all

I have been working on some new code that embeds python in an C 
application. The embedding is working fine under Linux but crashing 
under Windows (XP) when I reach the following step.

PyRun_AnyFile(f,name);

If there's some python exception being thrown by the PyRun_AnyFile call, 
how can I retrieve it from C?

Even when the file (f) being run by Python contains only a 'print' 
statement, the application still crashes on WinXP. The linking to Python 
seems to be working OK, and the following C code that precedes the above 
PyRun_AnyFile statement seems to be working fine:

PyRun_SimpleString("import ascpy");
PyRun_SimpleString("L = ascpy.Library()");
PyRun_SimpleString("print L");

Can anyone suggest what some good diagnostic steps would be?

My embedding code is at the following link. I'm happy to explain the 
architecture in more detail if that helps.
https://pse.cheme.cmu.edu/svn-view/ascend/code/branches/extfn/models/johnpye/extpy/

Any suggestions very much appreciated!

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


Re: Hands on Documentation for Python methods and Library

2006-10-05 Thread Richard Jones
Wijaya Edward wrote:
> One can do the following with Perl
>  
> $ perldoc -f chomp
> $ perldoc -f function_name

$ pydoc dir
$ pydoc function_name

or

$ pydoc math
$ pydoc module_name


Richard




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


Re: Python to use a non open source bug tracker?

2006-10-05 Thread Giovanni Bajo
Martin v. Löwis wrote:

>> In fact, are you absolutely positive that you need so much effort to
>> maintain an existing bugtracker installation? I know for sure that
>> GCC's Bugzilla installation is pretty much on its own; Daniel Berlin
>> does some maintainance every once in a while (upgrading when new
>> versions are out, applying or writing some patches for most
>> requested features in the community, or sutff like that), but it's
>> surely not his job, not even part-time.
>
> Daniel Berlin has put a tremendous amount of work into it. I know,
> because I set up the first bug tracker for gcc (using GNATS), and
> have been followed the several years of pondering fairly closely.
> It was quite some work to set up GNATS, and it was even more work
> to setup bugzilla.
>
> For Python, we don't have any person similar to Daniel Berlin
> (actually, we have several who *could* have done similar work,
>  but none that ever volunteered to do it). Don't underestimate
> the work of somebody else.

Martin, I am by no means understimating Daniel's work. I am just noting that
the spare-time work he did is, by definition, much much lower than the "6-10
people" that the PSF infrastructure committee is calling for. I would like this
statement to be officially reduced to "2-3 people", since it is *really* not
required much more than that to setup a bug tracker installation, and no more
than 1 person to maintain it afterwards. *IF* there are more volunteers, that's
good, they can offload the maintenance work from a single maintainer; but I
think it's unfair to put such a high *requisite*.

We do not have 6-10 people maintaining SVN afterall, even if you wish we had :)
-- 
Giovanni Bajo


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

Multiple calls to logging.config.fileConfig

2006-10-05 Thread Almad
Hi,

our applications can have plugins as subpackages and I'd like to allow
them to use their own logger as well as it's configuration. I thought
that best way will be their own configuration file passed to
fileConfig.

However, I run into problems...

1) It seems that I cannot refer to something from previously loaded
files, i.e. I'd like application config file to specify formatters and
handlers and plugins only referring them.

2) I'm not sure about "appending" loggers; if I specify
[loggers]
keys: web

and then
[loggers]
keys: syncml

Will web not be overwritten?

3) Finally, I run into "root" problem. In second call, if I specify
root logger again:

[loggers]
keys: root,web

(...)

[logger_web]
level: WARNING
qualname: xxx.web
handlers: console

I'll get

Traceback (most recent call last):
  File "/usr/lib/python2.4/logging/config.py", line 143, in fileConfig
llist.remove("root")


If I'll set only web as logger, I'll get standard NoSectionFound
exception.

Any idea how to fix this? It seems that I have to write custom parser
merging all files and config logging directly from code, but I'd like
to assure that it's the standard way...

Regards,

Almad

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


Re: embedding python -- windows specify problems

2006-10-05 Thread Fredrik Lundh
John Pye wrote:

> I have been working on some new code that embeds python in an C
> application. The embedding is working fine under Linux but crashing
> under Windows (XP) when I reach the following step.
>
> PyRun_AnyFile(f,name);
>
> If there's some python exception being thrown by the PyRun_AnyFile call,
> how can I retrieve it from C?
>
> Even when the file (f) being run by Python contains only a 'print'
> statement, the application still crashes on WinXP.

the contents and the layout of the FILE structure isn't defined, so 
PyRun_AnyFile()
only works if you make sure to open the file using *exactly* the same run time 
library
as Python itself uses.

it's usually easier to hand the problem over to the interpreter:

PyRun_SimpleString("execfile('myscript.py')\n");

the same approach can be used to implement custom error handling, stdout/stderr
redirects, etc.

 



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


Re: embedding python -- windows specify problems

2006-10-05 Thread Fredrik Lundh
> the contents and the layout of the FILE structure isn't defined

"isn't standardized", that is.

 



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


Re: dictionary of list from a file

2006-10-05 Thread [EMAIL PROTECTED]
limodou wrote:
> On 4 Oct 2006 13:11:15 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > limodou wrote:
> > > here is my program
> > >
> > > d = {}
> > > for line in file('test.txt'):
> > > line = line.strip()
> > > if line:
> > > k, v = line.strip().split()
> > > d.setdefault(k, []).append(v)
> > > print d
> >
> > Minor nits: you call strip twice, when you don't need to.  just omit
> > the second call.
>
> Yes, I forgot that.
>
> > Also, I'm not sure stripping the line is the right thing per the spec;
> >
> > d = {}
> > for line in [l[:-1] for l in file('test.txt', 'rU') if len(l)>1]:
> > k,v = line.split()
> > d.setdefault(k,[]).append(v)
> >
> [l[:-1] for l in file('test.txt', 'rU') if len(l)>1]
>
> this line I think will create a list, and if the file is large, it'll
> consume many memory I think.
>
> And I think using strip is more clear than list comprehension, except
> for the memory consume.

Good point on memory.

You can use strip in a list (or generator) comprehension just fine.

For example (using a generator to avoid memory consumption):

for line in (l.rstrip("\n") for l in file("test.txt", "rU") if l[0] !=
"\n"):
   k, v = line.split()
   d.setdefault(k, []).append(v)

It's a matter of taste, but I think this isolates the bean-counting
"get rid of newlines/blank lines" stuff from the real processing and
makes it a bit clearer what real work you're doing with each line.

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


Re: Python/Tkinter crash.

2006-10-05 Thread Hendrik van Rooyen
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
> Eric Brunel wrote:
>
> > AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize
> > the calls from different threads may seem to work (I never tested it
> > actually), but the safest way I found to use threads with Tkinter was to
> > call it only from the thread where the main loop executes.
>
> the Tkinter binding contains some code that attempts to deal with re-
> entrant calls, but I don't know/remember to what extent it's actually
> supposed to work (in other words, if the observed problems are bugs or
> just limitations).
>
> (maybe Martin's memory is better?)
>
> anyway, I usually play it safe and make sure to use a single thread to
> deal with the UI.
>
> 

I must be dense - After I have called mainloop, if I have not started another
thread to respond to events that are not generated by the user on the screen (in
this case values of variables to display from the field generated by different
processes - there is other hardware out there), how do I get control back to do
the necessary updating? - I suppose I can use the call back after some time
thingy to implement a polling loop - possibly as Russel Owen suggested - by
polling a queue - but queues are for between threads - and I have seen here
somewhere that sockets also want to be the main thread  - so that leaves a
pipe - and I have had bad experiences with pipes that are unblocked, and if I
don't unblock it, then the gui will grind to a haltso I need a thread for
the pipe between processes, and a queue between threads, and a time out based
polling loop to read the queue, it seems - is it even safe to change a main loop
variable from another thread? , or should I do it all via commands through a
queue, implementing a whole goddam serial protocol just between threads?  and If
I don't have another thread to do the timing for the animation bits, then I must
base that on a timed callback too, and somehow keep state between callbacks...
now is it ok to call widget command methods from a callback in the same thread,
or do I have to use invoke?

My head is beginning to hurt... - what was a nice simple threaded implementation
is turning into a spaghetti monster of timed callbacks - you thought gotos was
bad? - you aint seen nothing yet...

- Hendrik

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


Re: dictionary of list from a file

2006-10-05 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> for line in (l.rstrip("\n") for l in file("test.txt", "rU") if l[0] !=
> "\n"):
>    k, v = line.split()
>    d.setdefault(k, []).append(v)

Note that this snippet will produce the same output with or without the
rstrip() method call.

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


Re: Where is Python in the scheme of things?

2006-10-05 Thread Andy Dingley

gord wrote:

> As a complete novice in the study of Python, I am asking myself where this
> language is superior or better suited than others.

I use it, and see it primarily, as a Perl killer. It also does for Ruby
and our infernal shell scripts.

I've never considered using Python instead of VB. As a VB developer of
many years, I'd see thhe Python language itself as infinitely superior
to VB in almost every aspect, except that of building event driven
Windows GUIs with easy form layout. Maybe there's some wonderful Python
toolkit for doing this, but it's news to me.

I'm undecided as to whether Python beats JSP for web development. So
far I'm still inclined to Java, but that's probably because I know Java
and Java has a huge amount of "beyond Java the language" development
attached to it for web work.

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


Re: releasing memory to malloc

2006-10-05 Thread MrJean1
The memory manager in the latest Python release 2.5 does return freed
memory to the underlying system, if possible. For more details, see the
5th bullet on this page

  .

/Jean Brouwers



[EMAIL PROTECTED] wrote:
> The workaround I went with made use of the shelve module and
> calls to gc.collect() to cap the memory consumed by the Python
> allocator. It was a bit intrusive but it got the job done.
>
> Would a method in the gc module that released memory to malloc
> be something that could get added to Python? Or are there some
> reasons why allowing that would be a bad idea?
>
> Regards,
> Iker
>
> P.S.
> This may be a repeat of an earlier message - it seems that
> google groups may have discarded my earlier post.
>
>
> [EMAIL PROTECTED] wrote:
> > Is there any way to get Python to release memory back to the
> > C allocator? I'm currently running a script that goes through
> > the following steps:
> >
> > 1) Creates a very large number of Python objects to produce
> > a relatively small data structure that sits in a C extension.
> > The Python objects consume quite a bit of memory.
> >
> > 2) Releases all the Python objects.
> >
> > 3) Invokes a function of said C extension for further
> > processing. This step needs as much memory as possible.
> >
> > I'd like step 2 to return memory to the C allocator so that it
> > is available to the extension in step 3 (which uses malloc).
> > 
> > Regards,
> > Iker Arizmendi

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


Re: Python/Tkinter crash.

2006-10-05 Thread Hendrik van Rooyen

"Paul Rubin"  wrote:
> "Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
> > I am not sure how to do this - once I have called the Tkinter
> > mainloop - that main thread is essentially event driven - and
> > figuring out how to get it to poll a queue for content is not
> > obvious - I suppose I could arrange some external wake up event that
> > I could activate to make it look at the queue - must read up on
> > this...
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965
> 
Thank you Paul - this shows how nicely! - Hendrik

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


Why do this?

2006-10-05 Thread Matthew Warren
Ok, not really python focused, but it feels like the people here could
explain it for me :)

Now, I started programming when I was 8 with BBC Basic.

I never took any formal classes however, and I have never become an
expert programmer. I'm an average/hobbyist programmer with quite a few
languages under my belt but I cant do any really fancy tricks with any
of them. (although Python might be nudging me into more advanced things,
now I'm starting to get what all the __method__ thingies and operators
are all about)

I learned over the years to do things like the following, and I like
doing it like this because of readability, something Python seems to
focus on :-

Print "There are "+number+" ways to skin a "+furryanimal

But nowadays, I see things like this all over the place;

print("There are %s ways to skin a %s" % (number, furryanimal))

Now I understand there can be additional formatting benefits when
dealing with numbers, decimal places etc.. But to me, for strings, the
second case is much harder to read than the first.

I hope I'm not being dense.

The result is that I have pathalogically avoided print "%s" % (thing)
because it seems to just over complicate things.


Ta, :)

Matt.





This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Long Tkinter Menu

2006-10-05 Thread Dustan

Eric Brunel wrote:
> On Thu, 05 Oct 2006 02:33:54 +0200, Dustan <[EMAIL PROTECTED]> wrote:
>
> > I don't know if this is because of Tkinter (ie Tk) itself or the
> > Windows default way of handling things, but when I create a very long
> > menu (my test is shown below), the way it displays is rather sucky; the
> > menu stretches from the top of the moniter's window to the bottom (no
> > matter the size of the actual application).
> >
> > Is there any alternative format for how a long menu gets displayed? It
> > would be nice if say, I could make the menu only go to the borders of
> > the application itself (in this case, not that long).
>
> To limit the menu in the application window, will be difficult. But here
> are two ways of automatically limiting the number of entries that can
> appear in a menu by specializing the Tkinter Menu class:
>
> --
>  from Tkinter import *
>
> class LongMenu(Menu):
>"""
>Automatically creates a cascade entry labelled 'More...' when the
>number of entries is above MAX_ENTRIES.
>"""
>
>MAX_ENTRIES = 20
>
>def __init__(self, *args, **options):
>  Menu.__init__(self, *args, **options)
>  self.nextMenu = None
>
>def add(self, itemType, cnf={}, **kw):
>  if self.nextMenu is not None:
>return self.nextMenu.add(itemType, cnf, **kw)
>  nbEntries = self.index(END)
>  if nbEntries < LongMenu.MAX_ENTRIES:
>return Menu.add(self, itemType, cnf, **kw)
>  self.nextMenu = LongMenu(self)
>  Menu.add(self, 'cascade', label='More...', menu=self.nextMenu)
>  return self.nextMenu.add(itemType, cnf, **kw)
>
>
> class AutoBreakMenu(Menu):
>"""
>Automatically adds the 'columnbreak' option on menu entries to make
>sure that the menu won't get too high.
>"""
>
>MAX_ENTRIES = 20
>
>def add(self, itemType, cnf={}, **kw):
>  entryIndex =  1 + (self.index(END) or 0)
>  if entryIndex % AutoBreakMenu.MAX_ENTRIES == 0:
>cnf.update(kw)
>cnf['columnbreak'] = 1
>kw = {}
>  return Menu.add(self, itemType, cnf, **kw)
>
>
>
> if __name__ == '__main__':
>root = Tk()
>
>menubar = Menu(root)
>
>def fillMenu(menu):
>  for i in xrange(100):
>menu.add_command(label=str(i), command=root.quit)
>  menu.add_command(label="Exit", command=root.quit)
>
>menu1 = LongMenu(menubar, tearoff=0)
>fillMenu(menu1)
>menu2 = AutoBreakMenu(menubar, tearoff=0)
>fillMenu(menu2)
>
>menubar.add_cascade(label="Test1", menu=menu1)
>menubar.add_cascade(label="Test2", menu=menu2)
>
>root.config(menu=menubar)
>
>root.mainloop()
> --
>
> If your application is more complicated than that (e.g if you insert menu
> entries after the first adds), you'll have to change the code above a bit,
> since it doesn't handle calls to insert at all. But you get the idea.
>
> HTH
> --
> python -c "print ''.join([chr(154 - ord(c)) for c in
> 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

Thanks, I'll see what I can do with that.

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


Re: Why do this?

2006-10-05 Thread Hari Sekhon
Do whichever makes you happy I'd say

The only real difference is coding style and the formatting options of 
the %s way that I can see.

%s is negligibly slower in my tests, but we're talking the tiniest 
fraction of a second over thousands of iterations, not worth considering...

-h

Hari Sekhon



Matthew Warren wrote:
> Ok, not really python focused, but it feels like the people here could
> explain it for me :)
>
> Now, I started programming when I was 8 with BBC Basic.
>
> I never took any formal classes however, and I have never become an
> expert programmer. I'm an average/hobbyist programmer with quite a few
> languages under my belt but I cant do any really fancy tricks with any
> of them. (although Python might be nudging me into more advanced things,
> now I'm starting to get what all the __method__ thingies and operators
> are all about)
>
> I learned over the years to do things like the following, and I like
> doing it like this because of readability, something Python seems to
> focus on :-
>
> Print "There are "+number+" ways to skin a "+furryanimal
>
> But nowadays, I see things like this all over the place;
>
> print("There are %s ways to skin a %s" % (number, furryanimal))
>
> Now I understand there can be additional formatting benefits when
> dealing with numbers, decimal places etc.. But to me, for strings, the
> second case is much harder to read than the first.
>
> I hope I'm not being dense.
>
> The result is that I have pathalogically avoided print "%s" % (thing)
> because it seems to just over complicate things.
>
>
> Ta, :)
>
> Matt.
>
>
>
>
>
> This email is confidential and may be privileged. If you are not the intended 
> recipient please notify the sender immediately and delete the email from your 
> computer. 
>
> You should not copy the email, use it for any purpose or disclose its 
> contents to any other person.
> Please note that any views or opinions presented in this email may be 
> personal to the author and do not necessarily represent the views or opinions 
> of Digica.
> It is the responsibility of the recipient to check this email for the 
> presence of viruses. Digica accepts no liability for any damage caused by any 
> virus transmitted by this email.
>
> UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
> Reception Tel: + 44 (0) 115 977 1177
> Support Centre: 0845 607 7070
> Fax: + 44 (0) 115 977 7000
> http://www.digica.com
>
> SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
> Africa
> Tel: + 27 (0) 21 957 4900
> Fax: + 27 (0) 21 948 3135
> http://www.digica.com
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/Tkinter crash.

2006-10-05 Thread Steve Holden
Hendrik van Rooyen wrote:
> "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
> 
>>Eric Brunel wrote:
>>
>>
>>>AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize
>>>the calls from different threads may seem to work (I never tested it
>>>actually), but the safest way I found to use threads with Tkinter was to
>>>call it only from the thread where the main loop executes.
>>
>>the Tkinter binding contains some code that attempts to deal with re-
>>entrant calls, but I don't know/remember to what extent it's actually
>>supposed to work (in other words, if the observed problems are bugs or
>>just limitations).
>>
>>(maybe Martin's memory is better?)
>>
>>anyway, I usually play it safe and make sure to use a single thread to
>>deal with the UI.
>>
>>
> 
> 
> I must be dense - After I have called mainloop, if I have not started another
> thread to respond to events that are not generated by the user on the screen 
> (in
> this case values of variables to display from the field generated by different
> processes - there is other hardware out there), how do I get control back to 
> do
> the necessary updating? - I suppose I can use the call back after some time
> thingy to implement a polling loop - possibly as Russel Owen suggested - by
> polling a queue - but queues are for between threads - and I have seen here
> somewhere that sockets also want to be the main thread  - so that leaves a
> pipe - and I have had bad experiences with pipes that are unblocked, and if I
> don't unblock it, then the gui will grind to a haltso I need a thread for
> the pipe between processes, and a queue between threads, and a time out based
> polling loop to read the queue, it seems - is it even safe to change a main 
> loop
> variable from another thread? , or should I do it all via commands through a
> queue, implementing a whole goddam serial protocol just between threads?  and 
> If
> I don't have another thread to do the timing for the animation bits, then I 
> must
> base that on a timed callback too, and somehow keep state between callbacks...
> now is it ok to call widget command methods from a callback in the same 
> thread,
> or do I have to use invoke?
> 
> My head is beginning to hurt... - what was a nice simple threaded 
> implementation
> is turning into a spaghetti monster of timed callbacks - you thought gotos was
> bad? - you aint seen nothing yet...
> 
See if this helps:

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965

It's Jacob Hallen's description of how he solved the problem.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


RE: Why do this?

2006-10-05 Thread Tim Golden
[Matthew Warren]

| Now, I started programming when I was 8 with BBC Basic.

Hey, likewise! (Except I was 12 when it came out!)

| I learned over the years to do things like the following, and I like
| doing it like this because of readability, something Python seems to
| focus on :-
| 
| Print "There are "+number+" ways to skin a "+furryanimal

perfectly sound Python code, as far as it goes, altho' obviously
"Print" is spelt "print" in Python, and if that number is in fact
a number it'll need to be str ()-ed first.

| But nowadays, I see things like this all over the place;
| 
| print("There are %s ways to skin a %s" % (number, furryanimal))

The outermost brackets are (at the moment) unnecessary in python,
altho' print is slated for replacement by a function in Python 3.0
at which point they'll be necessary.

number = 3
animal = "cat"
print "There are %d ways to skin a %s" % (number, animal)

| Now I understand there can be additional formatting benefits when
| dealing with numbers, decimal places etc.. But to me, for strings, the
| second case is much harder to read than the first.

I think what it comes down to is just what's most readable in the
situation in which you're using it. Imagine a rather longer
string, and one where  and  are not short names,
but calls to some function. Sometimes, since %s will call __str__
on anything it's passed, it's a quick way to get a string representation
of a more complex object, which you'd otherwise have to str () at
least.

| I hope I'm not being dense.

Nothing dense about it. Very often a matter of taste and style.
Sometimes 
I find myself using string substitution where a simple string addition 
might suffice simply because of consistency, for example where it's 
surrounded by some more complex cases as described above, and I don't 
want to break the pattern simply because the case is simpler.

Also, for me, substitution often reads more naturally because you're 
not breaking the string up with lots of " +  + "..." + yyy + "...  
stuff. Again, though, depends on what your code looks like, and how 
readable you find it. Certainly, I wouldn't advocate *pathologically* 
avoiding the "%s" % blah style, but it needn't always be the right
thing.

A typical example where it can become cumbersome is when you're
partially
reinventing a templating system with quite a long string, say of HTML,
and
quite a few substitutions right at the end. It may be easier to use the 
dictionary form of the substitution then, eg:

print """
Long string with %(valueA)s and %(valueB)s and %(valueC)s embedded in
it at some distance from the end...
...
""" % dict (valueA=1, valueB="blah", valueC=datetime.datetime.now ())

Obviously that dict would likely be defined elsewhere, or could even
be locals (). Once you get to this stage, though, you might want to 
start looking at templating toolkits like Cheetah, Genshi or any of
the many others knocking around.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Why do this?

2006-10-05 Thread Mikael Olofsson


Matthew Warren wrote:
> I learned over the years to do things like the following, and I like
> doing it like this because of readability, something Python seems to
> focus on :-
>
> Print "There are "+number+" ways to skin a "+furryanimal
>
> But nowadays, I see things like this all over the place;
>
> print("There are %s ways to skin a %s" % (number, furryanimal))
>
> Now I understand there can be additional formatting benefits when
> dealing with numbers, decimal places etc.. But to me, for strings, the
> second case is much harder to read than the first.
>   

I agree that the second alternative isn't too readable. It is also not 
too maintainable. My version of the above is most often

print "There are %(number)s ways to skin a %(furryanimal)s." % vars()

Readable and maintainable.

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


Re: Why do this?

2006-10-05 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Matthew Warren
wrote:

> I learned over the years to do things like the following, and I like
> doing it like this because of readability, something Python seems to
> focus on :-
> 
> Print "There are "+number+" ways to skin a "+furryanimal
> 
> But nowadays, I see things like this all over the place;
> 
> print("There are %s ways to skin a %s" % (number, furryanimal))
> 
> Now I understand there can be additional formatting benefits when
> dealing with numbers, decimal places etc.. But to me, for strings, the
> second case is much harder to read than the first.

For me it's the other way around -- I find the second one more readable
especially without syntax highlighting to see which characters are inside
and which are outside the quotes.

With the second one there's a clear visual separation of the string
literal and the variables, even without colors.

Another advantage of the second way is much easier localization and other
tasks where the sentence itself is not hardcoded but read from files,
databases, etc.

And the '%s' automatically converts the objects to strings.  The
equivalent to the second example without string formatting would be::

  print 'There are' + str(number) + ' ways to skin a ' + str(furryanimal)

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


Re: Why do this?

2006-10-05 Thread Duncan Booth
"Matthew Warren" <[EMAIL PROTECTED]> wrote:

> Print "There are "+number+" ways to skin a "+furryanimal
> 
> But nowadays, I see things like this all over the place;
> 
> print("There are %s ways to skin a %s" % (number, furryanimal))
> 
> Now I understand there can be additional formatting benefits when
> dealing with numbers, decimal places etc.. But to me, for strings, the
> second case is much harder to read than the first.
> 

apart from the spurious parentheses you added in the second one, you also 
missed out this variant:

print "There are", number, "ways to skin a", furryanimal

That only works for print though, not for other uses of strings, but it is 
related to the main reason I use format strings instead of concatenation. 

The problem I have with your first option is the large number of times I've 
written:

print "There are"+number+"ways to skin a"+furryanimal

or at least something equivalent to it. If I try to make the same mistake 
with a format string it jumps out to me as wrong:

"There are%sways to skin a%s" % (number, furryanimal)

Also, having a variable of type str called 'number' seems perverse (and 
probably error prone), so I suspect I might need something like:

   print "There are "+str(number)+" ways to skin a "+furryanimal

but the format string does the conversion for free.

The other main reason for preferring format strings is that they make it 
easier to refactor the code. If you ever want to move the message away from 
where the formatting is done then it's a lot easier to extract a single 
string than it is to clean up the concatenation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Testing if an object is a function

2006-10-05 Thread Claus Tondering
If I want to test if an object, x, is an integer, I can call
isinstance(x, int).

But what do I do if I want to test if x is a function?

I can do this:

 if isinstance(x, type(lambda: None)): ...

But it does not seem very elegant to me.

Surely there is a simpler way to specify a type object that is the type
of a function.

--
Claus Tondering

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


Re: Testing if an object is a function

2006-10-05 Thread Fredrik Lundh
Claus Tondering wrote:

> But what do I do if I want to test if x is a function?
>
> I can do this:
>
> if isinstance(x, type(lambda: None)): ...
>
> But it does not seem very elegant to me.
>
> Surely there is a simpler way to specify a type object that is the type
> of a function.

if callable(x):
...

(if you really want a function object, and not anything that's likely to be 
possible
to call, see the "types" module)

 



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


Re: excepthook doesn't give exact line number

2006-10-05 Thread Hari Sekhon




I've tried the sample code you provided but it seems to just hang, it
must be doing something but unfortunately it must take too long, by
which time a second control-c gives an awful dual traceback message
showing the original traceback and the new one from the tbiter() func.

I've tried a few variations since yesterday but unfortunately those 2
funcs take too long to run to make a viable solution and the script
ends up hanging on an uncaught exception.

If anybody has any improvements, suggestions or alternatives for
getting the proper line number and traceback message inside an
excepthook then I'd be grateful to hear them.

-h
Hari Sekhon


Peter Otten wrote:

  Hari Sekhon wrote:

  
  
The problem is that the excepthook gives the line of the topmost called
function rather that the actual line that generated the error the way
you get it with a normal traceback.

  
  
A look into the traceback module shows that tracebacks are stored as a
linked list. Here's a way to get hold of its tail:

def tbiter(tb):
while tb is not None:
yield tb
tb = tb.tb_next

def last(items):
for  item in items:
pass
return item

# example usage
def myexcepthook(type, value, tb):
tb_tail = last(tbiter(tb))
print tb_tail.tb_lineno
 
Peter
  



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

RE: Why do this?

2006-10-05 Thread Matthew Warren
> 
> | Now, I started programming when I was 8 with BBC Basic.
> 
> Hey, likewise! (Except I was 12 when it came out!)

I think it came out before I was 8, and I started out with print and
input. Not sure if that's 'real' programming - I don't think I graduated
to ifs and thens and gotos and gosubs for a while.. Uhm, Or was it 'def
proc' et al for BBC Basic? Brain holes leaking old stuff out :)

> | Print "There are "+number+" ways to skin a "+furryanimal
> 
> perfectly sound Python code, as far as it goes, altho' obviously
> "Print" is spelt "print" in Python, and if that number is in fact
> a number it'll need to be str ()-ed first.

Blame outlook and AutoCaps. If number were a number I would write

print "There are",number,"ways to skin a "+furryanimal

..something I like about python, 'cause having been pathalogically
avoiding %'s etc.. I have learned to hate going "string "+str(number)+"
string"

> 
> | But nowadays, I see things like this all over the place;
> | 
> | print("There are %s ways to skin a %s" % (number, furryanimal))
> 
> The outermost brackets are (at the moment) unnecessary in python,

Oops :)

> altho' print is slated for replacement by a function in Python 3.0
> at which point they'll be necessary.

? Why do that, point me at a PEP if required and I'll read it :)

> 
> number = 3
> animal = "cat"
> print "There are %d ways to skin a %s" % (number, animal)
> 
> | Now I understand there can be additional formatting benefits when
> | dealing with numbers, decimal places etc.. But to me, for 
> strings, the
> | second case is much harder to read than the first.
> 
> I think what it comes down to is just what's most readable in the
> situation in which you're using it. Imagine a rather longer
> string, and one where  and  are not short names,
> but calls to some function. Sometimes, since %s will call __str__
> on anything it's passed, it's a quick way to get a string 
> representation
> of a more complex object, which you'd otherwise have to str () at
> least.
>
> Also, for me, substitution often reads more naturally because you're 
> not breaking the string up with lots of " +  + "..." + 
> yyy + "...  
> stuff. Again, though, depends on what your code looks like, and how 
> readable you find it. Certainly, I wouldn't advocate *pathologically* 
> avoiding the "%s" % blah style, but it needn't always be the right
> thing.
>

I am a big fan of easily human readable meaningful names for things, to
the extent that I will quite readily use var or function names
ThatCanBeQuiteLongAndExplanatory() For me, it helps retain the
readbility say, when breaking up a string with lots of + xxx + "etc..
Etc.." + lalala

>It may be easier 
> to use the 
> dictionary form of the substitution then, eg:
> 
> print """
> Long string with %(valueA)s and %(valueB)s and %(valueC)s embedded in
> it at some distance from the end...
> ...
> """ % dict (valueA=1, valueB="blah", valueC=datetime.datetime.now ())
> 
> Obviously that dict would likely be defined elsewhere, or could even
> be locals (). Once you get to this stage, though, you might want to 
> start looking at templating toolkits like Cheetah, Genshi or any of
> the many others knocking around.
>

That's something I wasn't aware of, and I think I'll try if I find
myself going

"something"+dict['thingummy']+" red ones and "+dict['colour']+" ones"

The dict substitution does feel a bit easier to read compared to the
concatenation, because of the dict['']  noise.

Matt.




This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Universe Set

2006-10-05 Thread Jorgen Grahn
On Wed, 04 Oct 2006 11:00:28 -0400, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
> Jorgen Grahn wrote:
>> - infinite xrange()s
>
> itertools.count()?

Oops! You're right. The itertools documentation even refers to the SML and
Haskell languages.  And it contains itertools.izip(), another thing on my
wish list.

I have reasons to be Python 2.2 compatible, so I haven't really looked
through the nice things in 2.3 and up (generators are in __future__ in 2.2).
Stupid of me to overlook itertools, which I've read about here many times.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Why do this?

2006-10-05 Thread Matthew Warren
 > Also, having a variable of type str called 'number' seems 
> perverse (and 
> probably error prone), so I suspect I might need something like:
>

And not something I would normally do, but for hastily written contrived
examples I might :)

 
>print "There are "+str(number)+" ways to skin a "+furryanimal
> 
> but the format string does the conversion for free.
> 
> The other main reason for preferring format strings is that 
> they make it 
> easier to refactor the code. If you ever want to move the 
> message away from 
> where the formatting is done then it's a lot easier to 
> extract a single 
> string than it is to clean up the concatenation.
> -- 


This is a benefit of pythons implementation of format strings I hadn't
considered, that __str__() is called to get the representation. And
something I like about python, althgouh at the moment the __xxx__
methods available and their use is something I'm just getting into


This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do this?

2006-10-05 Thread Ivan Voras
Duncan Booth wrote:

> print "There are"+number+"ways to skin a"+furryanimal
> 
> or at least something equivalent to it. If I try to make the same mistake 
> with a format string it jumps out to me as wrong:
> 
> "There are%sways to skin a%s" % (number, furryanimal)

Related to this, formatting with sequences is also much more readable 
when there are complex interpunction and quoting characters present, 
like this:

print "'"+var1+"','"+var2'"+","+var3

the above is much more readable as

print "'%s', '%s', %s" % (var1, var2, var3)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Testing if an object is a function

2006-10-05 Thread Claus Tondering
Fredrik Lundh wrote:
> if callable(x):

Perfect. Thank you.

--
Claus Tondering

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


Re: excepthook doesn't give exact line number

2006-10-05 Thread Hari Sekhon




Thanks for the pointer, I've now got this giving me the right line
number when an exception occurs, although I still get an empty stack
trace from 

print "Stack Trace:\n%s\n" % str(traceback.print_exc(2))

inside the excepthook.

Any ideas why this is?

Is there no traceback since the traceback was fed to the excepthook? Is
there another way of getting the traceback like you see when the
exception isn't caught?

Thanks for the help.

-h
Hari Sekhon


Peter Otten wrote:

  Hari Sekhon wrote:

  
  
The problem is that the excepthook gives the line of the topmost called
function rather that the actual line that generated the error the way
you get it with a normal traceback.

  
  
A look into the traceback module shows that tracebacks are stored as a
linked list. Here's a way to get hold of its tail:

def tbiter(tb):
while tb is not None:
yield tb
tb = tb.tb_next

def last(items):
for  item in items:
pass
return item

# example usage
def myexcepthook(type, value, tb):
tb_tail = last(tbiter(tb))
print tb_tail.tb_lineno
 
Peter
  



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

Re: Why do this?

2006-10-05 Thread Maric Michaud
Le jeudi 05 octobre 2006 13:16, Ivan Voras a écrit :
> print "'"+var1+"','"+var2'"+","+var3
>
> the above is much more readable as
>
> print "'%s', '%s', %s" % (var1, var2, var3)

It feels not IMO, one proof I see is that you forgot the spaces after periods 
in your first example, and it's even not easy to figure it out...

In fact this is a typical case I replace the first by the second, when the 
string comes a little complex.

-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Why do this?

2006-10-05 Thread Matthew Warren
 > Duncan Booth wrote:
> 
> > print "There are"+number+"ways to skin a"+furryanimal
> > 
> > or at least something equivalent to it. If I try to make 
> the same mistake 
> > with a format string it jumps out to me as wrong:
> > 
> > "There are%sways to skin a%s" % (number, furryanimal)
> 
> Related to this, formatting with sequences is also much more readable 
> when there are complex interpunction and quoting characters present, 
> like this:
> 
> print "'"+var1+"','"+var2'"+","+var3
> 
> the above is much more readable as
> 
> print "'%s', '%s', %s" % (var1, var2, var3)

Hmm, with my hastily written contrived example, I had forgotten about
sequences like that.

Oddly, in the case above I prefer reading the bottom example,

And shouldn't that top one be

print "'"+var1+"','"+var2+"',"+var3

;)

So to conclude, in future I will read it, and see how readable it is
before I decide. But now at least I do see a reason not to
pathalogically avoid such string formatting :)

Matt.


This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Subclassing built-in classes

2006-10-05 Thread MonkeeSage
I know that python doesn't allow extending built-in objects like the
str class; but you can subclass them using a class of the same name and
thus shadow them to get the same general effect (albeit you have to use
the explicit constructor rather than literals).

class str(str):
  def display(self):
print self
str('blah').display()

I was just playing around and realized that assigning to
__builtins__.str (or if you prefer sys.modules['__builtin__'].str) has
the same effect.

class mystr(str):
  def display(self):
print self
__builtins__.str = mystr
str('blah').display()

So that made me wonder...couldn't python (in theory) allow for literals
to use extended classes by using the object in __builtins__. as
the class for literals? By default it would be the standard base class,
but it could also be a custom subclass. Would that be possible / easy /
worthwhile to do?

Regards,
Jordan

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


RE: Why do this?

2006-10-05 Thread Tim Golden
[Matthew Warren]

| Blame outlook and AutoCaps. If number were a number I would write
| 
| print "There are",number,"ways to skin a "+furryanimal

You see now that strikes me as a bit mixed up. Why not simply use?

print "a", number, "c", string

| > altho' print is slated for replacement by a function in Python 3.0
| > at which point they'll be necessary.
| 
| ? Why do that, point me at a PEP if required and I'll read it :)

Oft-discussed, and personally I prefer it as a statement,
but the edict has gone out. Look at PEP 3100:

http://www.python.org/dev/peps/pep-3100/

| That's something I wasn't aware of, and I think I'll try if I find
| myself going
| 
| "something"+dict['thingummy']+" red ones and "+dict['colour']+" ones"
| 
| The dict substitution does feel a bit easier to read compared to the
| concatenation, because of the dict['']  noise.

Ultimately it's down to you, but I think you may be doing
your code a disservice by so assiduously avoiding the %s-style
of string building. Your last example suggests that you
see the dict-subtitution flavour simply as an alternative to doing
"a" + dict[key1] + "b" + dict[key2] etc. I doubt if I've *ever* 
started with the one and ended with the other; rather I've seen that
my code would be more readable if I put/had what I wanted into a
dict (or a dict-like object; just has to support __getitem__).

An easy example of this is where -- like many, I believe -- I prefer my
database rows to come in dict-like objects, rather than the tuples which
the dbapi stipulates. Again, like many, I've used or rolled my own
wrapper
which means I can do things like this, where my dbutils.fetch function
returns some kind of object which traps __getitem__ calls for column
names and returns the appropriate entry in the underlying tuple:


import dbutils
db = db_module.connect (...)
for row in dbutils.fetch (db, "SELECT * FROM blah"):
  print "Customer %(name)s (%(id)d) has %(n_orders)d outstanding orders
since %(last_order_date)s" % row



TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: A Universe Set

2006-10-05 Thread Jorgen Grahn
On Thu, 05 Oct 2006 00:02:51 +0200, Wildemar Wildenburger <[EMAIL PROTECTED]> 
wrote:
> Jorgen Grahn wrote:

> Any use cases for these?

>> - the wildcard object, which compares equal to everything else

Like someone else wrote, for quick-and-dirty comparisons or lists and
dictionaries where I don't care about one part. I think I wanted it for
unittest's assertEqual(foo, bar) at one point.

  self.assertEqual(['foo', 42, [], WILDCARD], my_result)

versus

  self.assertEqual('foo', my_result[0])
  self.assertEqual(42, my_result[1])
  self.assertEqual([], my_result[2])
  self.assertEqual(4, len(my_result))
  # possibly assert that 'my_result' is a list-like
  # object too

But I agree that the WILDCARD isn't the kind of object you want to spread
throughout your code; its behaviour is too odd.

>> - infinite xrange()s

Available in itertools, as someone pointed out.

>> - the black hole function 'def f(*args): pass'

I often find myself adding logging to functions by passing sys.stderr.write
as an argument to it.  Passing blackhole is an elegant and fast way of
disabling logging.

>> - the identity function 'def f(x): return x'

I don't think I've used it. Maybe if you do a lot of manipulation of
functions and functors -- in some sense it's to function application what 0
is to addition, or 1 to multiplication.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary of list from a file

2006-10-05 Thread [EMAIL PROTECTED]
Peter Otten wrote:
> [EMAIL PROTECTED] wrote:
>
> > for line in (l.rstrip("\n") for l in file("test.txt", "rU") if l[0] !=
> > "\n"):
> > \001\001\001k,\001v\001=\001line.split()
> > \001\001\001d.setdefault(k,\001[]).append(v)
>
> Note that this snippet will produce the same output with or without the
> rstrip() method call.

Wow. That's not at all what I expected.  I would've thought I'd see:
>>> " 1".split()
['', '1']

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


Re: Subclassing built-in classes

2006-10-05 Thread Steve Holden
MonkeeSage wrote:
> I know that python doesn't allow extending built-in objects like the
> str class; but you can subclass them using a class of the same name and
> thus shadow them to get the same general effect (albeit you have to use
> the explicit constructor rather than literals).
> 
> class str(str):
>   def display(self):
> print self
> str('blah').display()
> 
> I was just playing around and realized that assigning to
> __builtins__.str (or if you prefer sys.modules['__builtin__'].str) has
> the same effect.
> 
> class mystr(str):
>   def display(self):
> print self
> __builtins__.str = mystr
> str('blah').display()
> 
> So that made me wonder...couldn't python (in theory) allow for literals
> to use extended classes by using the object in __builtins__. as
> the class for literals? By default it would be the standard base class,
> but it could also be a custom subclass. Would that be possible / easy /
> worthwhile to do?
> 
Unfortunately the literals are interpreted during bytecode generation, 
before the compiled program is available, and your modifications to 
__builtns__ haven't been made, so the answer is "no", I'm afraid.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


RE: Why do this?

2006-10-05 Thread Matthew Warren
> [Matthew Warren]
> 
> | Blame outlook and AutoCaps. If number were a number I would write
> | 
> | print "There are",number,"ways to skin a "+furryanimal
> 
> You see now that strikes me as a bit mixed up. Why not simply use?
> 
> print "a", number, "c", string
> 

Habit (not always a good thing..), and it helps keep the distinction as
to what is a number and what is s a string.


> 
> Ultimately it's down to you, but I think you may be doing
> your code a disservice by so assiduously avoiding the %s-style
> of string building. Your last example suggests that you
> see the dict-subtitution flavour simply as an alternative to doing
> "a" + dict[key1] + "b" + dict[key2] etc. I doubt if I've *ever* 
> started with the one and ended with the other; rather I've seen that
> my code would be more readable if I put/had what I wanted into a
> dict (or a dict-like object; just has to support __getitem__).


Not quite. I was meaning that where I had things naturally in a dict and
found myself concatenating the string, I would now probably use the
substitution method.


> 
> An easy example of this is where -- like many, I believe -- I 
> prefer my
> database rows to come in dict-like objects, rather than the 
> tuples which
> the dbapi stipulates. Again, like many, I've used or rolled my own
> wrapper
> which means I can do things like this, where my dbutils.fetch function
> returns some kind of object which traps __getitem__ calls for column
> names and returns the appropriate entry in the underlying tuple:
> 
> 
> import dbutils
> db = db_module.connect (...)
> for row in dbutils.fetch (db, "SELECT * FROM blah"):
>   print "Customer %(name)s (%(id)d) has %(n_orders)d 
> outstanding orders
> since %(last_order_date)s" % row
> 
> 
> 
> TJG

I'm only just really looking into the effects of using things like
__getitem__ etc.., I imagine my approach will become more sophisticated
once I have looked into them.


This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Asychronous execution *with* return codes?

2006-10-05 Thread utabintarbo
I hope I have not overlooked a solution already posted, but I seem to
be unable to suss out a way to achieve both multiple console-less
executions of a given (console) application and gathering the return
code from the application.

What I have found:

import subprocess

# gives back return code, but does not run asynchronously
retcode = subprocess.call([app, lstArgs])
retcode = subprocess.Popen([app] + lstArgs).wait()
# runs the app async, but only returns the pid (no return code)
pid = subprocess.Popen([app] + lstArgs).pid


Is there some magic elixir which will get me both?

TIA

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


Re: Subclassing built-in classes

2006-10-05 Thread MonkeeSage
Steve Holden wrote:
> Unfortunately the literals are interpreted during bytecode generation,
> before the compiled program is available, and your modifications to
> __builtns__ haven't been made, so the answer is "no", I'm afraid.

Ah! That makes sense. I guess the only way to do it would be to add an
extra bit to every object to indicate whether it was constructed
literally and then re-initialize the object after compilation if that
bit is set. For some reason I just don't think that's gonna happen. ;)

Thanks for taking the time to explain.

Regards,
Jordan

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


Re: Subclassing built-in classes

2006-10-05 Thread Maric Michaud
Le jeudi 05 octobre 2006 14:20, Steve Holden a écrit :
> Unfortunately the literals are interpreted during bytecode generation,
> before the compiled program is available, and your modifications to
> __builtns__ haven't been made, so the answer is "no", I'm afraid.

But what prevents to interpret literals as a call to __builtins__ objects and 
functions ? optimization ? what else ?

-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asychronous execution *with* return codes?

2006-10-05 Thread MonkeeSage
utabintarbo wrote:
> pid = subprocess.Popen([app] + lstArgs).pid

Check out the poll() method and the returncode attribute:
http://docs.python.org/lib/node533.html

Regards,
Jordan

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


Re: embedding python -- windows specify problems

2006-10-05 Thread John Pye
Hi Fredrik,

Thanks very much for that reply. Your suggestion sounds feasible, I
guess. Taking what you said, and thinking about how I could avoid adding
an additional intepreter step, I thought that I could try the following:

pyfile = PyFile_FromString(name,"r");
if(pyfile==NULL){
return 1;
}   
f = PyFile_AsFile(pyfile);  
PyRun_AnyFileEx(f,name,1);

This seems to work on Linux at least (I'll test it tomorrow on my
Windows machine), and presumably it will work around the problem you
mentioned?

Cheers
JP

Fredrik Lundh wrote:
> John Pye wrote:
> 
> 
>>I have been working on some new code that embeds python in an C
>>application. The embedding is working fine under Linux but crashing
>>under Windows (XP) when I reach the following step.
>>
>>PyRun_AnyFile(f,name);
>>
>>If there's some python exception being thrown by the PyRun_AnyFile call,
>>how can I retrieve it from C?
>>
>>Even when the file (f) being run by Python contains only a 'print'
>>statement, the application still crashes on WinXP.
> 
> 
> the contents and the layout of the FILE structure isn't defined, so 
> PyRun_AnyFile()
> only works if you make sure to open the file using *exactly* the same run 
> time library
> as Python itself uses.
> 
> it's usually easier to hand the problem over to the interpreter:
> 
> PyRun_SimpleString("execfile('myscript.py')\n");
> 
> the same approach can be used to implement custom error handling, 
> stdout/stderr
> redirects, etc.
> 
>  
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: dictionary of list from a file

2006-10-05 Thread Matthew Warren
 

> -> > Python 2.5 introduced a dictionary type with automatic 
> > creation of values,
> > ala Perl:
> > 
> > ===
> > from collections import defaultdict
> > 
> > d = defaultdict(list)
> > for line in fl:
> >  k, v = line.strip().split()
> >  d[k].append(v)
> > 
> > for k,v in d.items():
> >  print k, v
> > ===
> > 
> > Notice that Python is always more strongly typed, so you have 
> > to specify a
> > factory function.
> 
> 
> Yay! Python2.5 fixed my approach to this, I tried
> 
> from collections import defaultdict
> f=file('c:\\test.txt')
> lines=f.readlines()
> f.close()
> d=defaultdict(list)
> [ d[l.split()[0]].append(l.split()[1]) for l in lines ]
> 
> But, if I try your (to see if I've actually got it right)
> 
> For k,v in d.items():
>   print k,v
> 
> I get
> 
> AttributeError: 'list' object has no attribute 'items'
> 


Okok, I'm silly.


This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: dictionary of list from a file

2006-10-05 Thread Matthew Warren
 

> -Original Message-
> From: 
> [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED]
> rg] On Behalf Of Giovanni Bajo
> Sent: 04 October 2006 15:17
> To: [email protected]
> Subject: Re: dictionary of list from a file
> 
> [EMAIL PROTECTED] wrote:
> 
> > while(){
> >   @info=split(/ +/,$_);
> >   push (@{$tmp{$info[0]}},$info[1]);
> > }
> >
> > and then
> > foreach $key (keys %tmp){
> >print "$key -> @{$tmp{$key}}\n";
> > }
> 
> Python 2.5 introduced a dictionary type with automatic 
> creation of values,
> ala Perl:
> 
> ===
> from collections import defaultdict
> 
> d = defaultdict(list)
> for line in fl:
>  k, v = line.strip().split()
>  d[k].append(v)
> 
> for k,v in d.items():
>  print k, v
> ===
> 
> Notice that Python is always more strongly typed, so you have 
> to specify a
> factory function.


Yay! Python2.5 fixed my approach to this, I tried

from collections import defaultdict
f=file('c:\\test.txt')
lines=f.readlines()
f.close()
d=defaultdict(list)
[ d[l.split()[0]].append(l.split()[1]) for l in lines ]

But, if I try your (to see if I've actually got it right)

For k,v in d.items():
print k,v

I get

AttributeError: 'list' object has no attribute 'items'




This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't open chm files all of a sudden

2006-10-05 Thread John Salerno
Dennis Lee Bieber wrote:
> On Wed, 04 Oct 2006 22:36:10 -0400, John Salerno
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
>> John Machin wrote:
>>
>>> 4. Have you done a full virus and spy-ware scan? Do you regularly
>>> install Windows updates from Microsoft?
>> Well, this is certainly the last thing I expected to work, but it did! 
>> There was something called an IECache cookie (which I've actually had 
>> before) and after removing it my chm files open now! Thanks for 
>> suggesting this! I was desperate! :)
> 
>   Probably some stray left behind by HTML KIt ... Remember, the
> rendering engine is NOT Internet Explorer only, it is shared by the
> desktop file Explorer, the help viewer, etc

LOL. I was also asking for help in the HTML Kit newsgroup, and of course 
they assured me that HTML Kit does not change chm settings or replace 
dlls, nor is it related to this piece of spyware. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subclassing built-in classes

2006-10-05 Thread Steve Holden
Maric Michaud wrote:
> Le jeudi 05 octobre 2006 14:20, Steve Holden a écrit :
> 
>>Unfortunately the literals are interpreted during bytecode generation,
>>before the compiled program is available, and your modifications to
>>__builtns__ haven't been made, so the answer is "no", I'm afraid.
> 
> 
> But what prevents to interpret literals as a call to __builtins__ objects and 
> functions ? optimization ? what else ?
> 
How can you modify __builtins__ before your program starts running? You 
can't.

What does the interpreter have to do before the program runs? Translate 
it into bytecode.

When are literals interpreted? During translation into bytecode.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: socket client server... simple example... not working...

2006-10-05 Thread SpreadTooThin

Jean-Paul Calderone wrote:
> On 4 Oct 2006 19:31:38 -0700, SpreadTooThin <[EMAIL PROTECTED]> wrote:
> >client:
> >
> >import socket
> >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >s.connect(("192.168.1.101", 8080))
> >print 'Connected'
> >s.send('ABCD')
>
> Here you didn't check the return value of send to determine if all of the 
> string was copied to the kernel buffer to be sent, so you may have only 
> succeeded in sending part of 'ABCD'.
>
> >buffer = s.recv(4)
>
> in the above call, 4 is the maximum number of bytes recv will return.  It 
> looks as though you are expecting it to return exactly 4 bytes, but in order 
> to get that, you will need to check the length of the return value and call 
> recv again with a lower limit until the combination of the return values of 
> each call gives a total length of 4.
>
> >print buffer
> >s.send('exit')
>
> Again, you didn't check the return value of send.
>
> >
> >
> >server:
> >
> >serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >serversocket.bind(("192.168.1.101", 8080))
> >serversocket.listen(5)
> >print 'Listen'
> >(clientsocket, address) = serversocket.accept()
> >print 'Accepted'
> >flag = True
> >while flag:
> > chunk = serversocket.recv(4)
>
> You're calling recv on serversocket instead of on clientsocket.  You're also 
> relying on recv to return exactly 4 bytes, which it may not do.
>
> > if chunk == '':
> > raise RuntimeError, "socket connection broken"
> > elif chunk == 'exit':
> > flag = False
> > else:
> > serversocket.send(chunk)
>
> Another missing check of the return value of send.
>
> >print 'Done'
> >
> >Server says!
> >
> >Listen
> >Accepted
> >Traceback (most recent call last):
> >  File "server.py", line 11, in ?
> >chunk = serversocket.recv(4)
> >socket.error: (57, 'Socket is not connected')
> >
> >
> >Client says:
> >Connected
> >
> >What have I done wrong now!
>
> I recommend switching to Twisted.  The Twisted equivalent (I guess - the 
> protocol defined above is strange and complex (probably unintentionally, due 
> to the things you left out, like any form of delimiter) and I doubt I really 
> understand the end goal you are working towards), minus bugs (untested):
>
> # client.py
> from twisted.internet import reactor, protocol
>
> class Client(protocol.Protocol):
> buf = ''
> def connectionMade(self):
> self.transport.write('ABCD')
> def dataReceived(self, data):
> self.buf += data
> if len(self.buf) >= 4:
> reactor.stop()
>
> protocol.ClientCreator(reactor, Client).connectTCP('192.168.1.101', 8080)
> reactor.run()
>
> # server.py
> from twisted.internet import reactor, protocol
>
> class Server(protocol.Protocol):
> buf = ''
> def dataReceived(self, bytes):
> self.buf += bytes
> exit = self.buf.find('exit')
> if exit != -1:
> self.transport.write(self.buf[:exit])
> self.buf = self.buf[exit + 4:]
> reactor.stop()
> else:
> self.transport.write(self.buf)
> self.buf = ''
>
> f = protocol.ServerFactory()
> f.protocol = Server
> reactor.listenTCP('192.168.1.101', 8080, f)
> reactor.run()
>
> Hope this helps,
>
> Jean-Paul

Jean-Paul many thanks for this and your effort.
but why is it every time I try to do something with 'stock' python I
need another package?
By the time I've finished my project there are like 5 3rd party add-ons
to be installed.
I know I'm a python newbie... but I'm far from a developer newbie and
that can be a recipe for
disaster.  The stock socket should work and I think I've missed an
obvious bug in the code other
than checking the return status.

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


Re: Python to use a non open source bug tracker?

2006-10-05 Thread skip

Ben> This thread was started on the shock of realising that a non-free
Ben> tool was even being *considered* for the new Python bug
Ben> tracker. Those are the terms on which I've been arguing.

Of course, the candidate trackers have been known for months.  Messages have
been posted to both this list and python-dev asking for inputs.

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


How do I read Excel file in Python?

2006-10-05 Thread kath
How do I read an Excel file in Python?

I have found a package to read excel file, which can be used on any
platform.

http://www.lexicon.net/sjmachin/xlrd.htm
I installed and working on the examples, I found its printing of cell's
contents in a different manner.

>>> import xlrd
>>> book=xlrd.open_workbook("Calculation_file.xls")
>>> book=xlrd.open_workbook("testbook.xls")
>>> sh=book.sheet_by_index(0)
>>> for row in range(sh.nrows):
print sh.row(rx)
[text:u'name', text:u'address', text:u'ph']
[text:u'sudhir', text:u'bangalore', number:1234.0]
[text:u'vinay', text:u'bangalore', number:3264.0]

I am bit confused with slicing. help me


Thank you,
Regards,
Sudhir.

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


Getting a ValueError with comtypes

2006-10-05 Thread winkatl1213
Hello,

I am working with comtypes to interface Microsoft's DirectShow library.

First, I found a Type Library on the internet that was created for
accessing DirectShow from .NET.  It seems that DirectShow only comes
with IDL files and no type library.

This got me started.

The following line imports the typelibrary and automatically generates
a wrapper module for DirectShow.

ds = comtypes.client.GetModule('DirectShow.tlb')

Next, I can basically start with something like this:

graph = comtypes.CoCreateInstance(CLSID_FilterGraph, ds.IGraphBuilder,
comtypes.CLSCTX_INPROC_SERVER)

I had to create the CLSID_FilterGraph parameter myself by doing the
following:

CLSID_FilterGraph =
comtypes.GUID('{e436ebb3-524f-11ce-9f53-0020af0ba770}')

One of the first issues I ran into was that the type library I found on
the web didn't expose the IMediaControl interface.  So, using the
generated wrapper as a template, I created my own wrapper:

class IMediaControl(comtypes.IUnknown):
_case_insensitive_ = True
_iid_ = comtypes.GUID('{56A868B1-0AD4-11CE-B03A-0020AF0BA770}')
_idlflags_ = []
IMediaControl._methods_ = [
COMMETHOD([], HRESULT, 'Run'),
COMMETHOD([], HRESULT, 'Pause'),
COMMETHOD([], HRESULT, 'Stop'),
COMMETHOD([], HRESULT, 'StopWhenReady'),
COMMETHOD([], HRESULT, 'GetState',
  (['in'], c_long, 'msTimeout'),
  (['out'], POINTER(c_int), 'pfs' ))
]

This got me further.  Once I defined the interface, I get access to the
interface by calling:

control = graph.QueryInterface(IMediaControl)

This seemed to work.  Once I got everything setup, I tried to use this
interface.  For example:

control.Run()

This generates an exception:

Traceback (most recent call last):
  File "", line 1, in ?
  File "ds.py", line 462, in play
control.Run()
ValueError: Procedure probably called with not enough arguments (4
bytes missing)

You can get errors like this when using ctypes if you use the wrong
calling convention (CDLL versus WINDLL).

The method "Run" on the IMediaControl interface doesn't take any
arguments.

I did notice that some wrapper code uses STDMETHOD versus COMMETHOD,
but changing this didn't make any difference.

Can anyone explain what might be happening here, or offer some
suggestions?

Thanks in advance,

Jeff

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


Re: Asychronous execution *with* return codes?

2006-10-05 Thread utabintarbo

MonkeeSage wrote:
> utabintarbo wrote:
> > pid = subprocess.Popen([app] + lstArgs).pid
>
> Check out the poll() method and the returncode attribute:
> http://docs.python.org/lib/node533.html
>

Thanks for the reply.

If I understand your meaning, I should do something like this (given I
wish to run an app against several arguments [my use case]):

for lstArgs in pileOflstArgs:
uniqueProcessID = subprocess.Popen([app] + lstArgs)
pid = uniqueProcessID.pid
retcode = uniqueProcessID.poll()
# increment uniqueProcessID


If so, how do I handle the poll() on long-running processes? Run a
bunch and then start a check loop? Am I asking too many questions?

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


Re: What value should be passed to make a function use the default argument value?

2006-10-05 Thread Antoon Pardon
On 2006-10-04, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Georg Brandl wrote:
>
>> This is an issue in most Python documentation: you're not told
>> if the described function is implemented in C, and if it is
>> keyword arg-enabled. The arguments must be given names though,
>> to be able to document them.
>
> the general rule is that if the documentation doesn't explicitly say 
> that something is a keyword argument, it isn't, and shouldn't be treated 
> as such.

The first module I looked in to check this, it wasn't true. In the Queue
Module is isn't explicitly written that maxsize is a keyword argument yet
Queue.Queue(maxsize=9) works just fine.

I then took a look in the Threading module and found that the semaphore
documentation didn't mention anything about keyword arguments but
again they worked fine.

It wouldn't surprise me if this was true for the complete threading
documentation.

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


Re: socket client server... simple example... not working...

2006-10-05 Thread Jean-Paul Calderone
On 5 Oct 2006 07:01:50 -0700, SpreadTooThin <[EMAIL PROTECTED]> wrote:
> [snip]
>
>Jean-Paul many thanks for this and your effort.
>but why is it every time I try to do something with 'stock' python I
>need another package?

Maybe you are trying to do things that are too complex :)

>By the time I've finished my project there are like 5 3rd party add-ons
>to be installed.

I don't generally find this to be problematic.

>I know I'm a python newbie... but I'm far from a developer newbie and
>that can be a recipe for
>disaster.

Not every library can be part of the standard library, neither can the
standard library satisfy every possible use-case.  Relying on 3rd party
modules isn't a bad thing.

>The stock socket should work and I think I've missed an
>obvious bug in the code other
>than checking the return status.
>

Well, I did mention one bug other than failure to check return values.
Maybe you missed it, since it was in the middle.  Go back and re-read
my response.

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


Re: Subclassing built-in classes

2006-10-05 Thread Maric Michaud
Le jeudi 05 octobre 2006 15:52, Steve Holden a écrit :
> > But what prevents to interpret literals as a call to __builtins__ objects
> > and functions ? optimization ? what else ?
>
>
> When are literals interpreted? During translation into bytecode.

agreed, but what's the problem with this ?

We can actually monkey patch all buitins like in this example :

In [1]: oldstr=str

In [2]: class mystr(str) :
   ...: def __new__(*a, **kw) :
   ...: print 'called : ', a, kw
   ...: return oldstr.__new__(*a, **kw)
   ...:
   ...:

In [3]: import __builtin__

In [4]: __builtin__.str = mystr
called :  (, ) {}
called :  (, 5) {}
...


If the generated bytecode of {k:v} is more or less the same as the one 
gernerated by dict(((k,v))), monkey patching dict will work for dict literals 
too.

Also, this should work with scalars,  'a string' be translated in what 
actually is produced by str('a string') (of course the internal code for 
building scalars should still be there).

If that is feasible without big refactoring and do not introduce noticeable 
performance loss is what I don't know, but it could be a nice feature of 
__builtin__ module IMO (at less I expected it to work like this when I first 
tried it).

-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


building strings from variables

2006-10-05 Thread Gal Diskin
Following a discussion with an associate at work about various ways to
build strings from variables in python, I'd like to hear your opinions
and preferred methods. The methods we discussed are:
1.  some_string = "cd %s ; %s  %d %s %s" % ( working_dir, ssh_cmd,
some_count, some_param1, some_param2)

2. import string
template = string.Template("cd $dir ; $cmd $count $param1
$param2")
some_string = template.substitute(dict(dir=working_dir,

cmd=ssh_cmd,

count=some_count,

pararm1=some_param1,

param2=some_param2))
here you can use a couple of nice tricks by using class.__dict__ and
globals() \ locals() dictionaries.

3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ "
"+str(some_count)+" "+some_param1+" "+some_param2
(all these are supposed to produce the same strings)

Which methods do you know of \ prefer \ think is better because...?
I will appreciate any opinions about the matter.

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


Oracle database export

2006-10-05 Thread Tor Erik Soenvisen
Hi,

I need to export an Oracle database to a DDL-formated file. On the Web, I 
found a Python script that did exactly this for a MS Access database, but
not one for Oracle databases.

Does anyone know of such a tool or Python script.

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


Restoring override of urllib.URLopener.open_https

2006-10-05 Thread Bakker A
Hi,

the M2Crypto library overrides the urllib.URLopener.open_https method,
causing a urllib.urlopen to a https: server to fail in my
case. My python is not that strong, so is there a way to set
urllib.URLopener.open_https back to the original code? I prefer not to
modify M2Crypto.

Thanks,
Arno Bakker

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


Re: Access to static members from inside a method decorator?

2006-10-05 Thread glen . coates . bigworld
Bruno Desthuilliers wrote:
> [EMAIL PROTECTED] wrote:
> > I'm developing a library at the moment that involves many classes, some
> > of which have "exposed" capabilities.  I'm trying to design a nice
> > interface for both exposing those capabilities, and inspecting
> > instances to find out what capabilities they have.
> >
> > At the moment, I'm leaning towards a superclass (Exposed) that defines
> > a static method which is a decorator (expose) such that any derived
> > class can mark a method with @Exposed.expose and it will then be later
> > returned by getExposedMethods(), a la:
> >
> > class Exposed:
> >   @staticmethod
> >   def expose( f ):
> > ...
> >
> >   def getExposedMethods( self ):
> > ...
> >
> > class Person( Exposed ):
> >   @Exposed.expose
> >   def talk( self, ... ):
> > ...
> >
> > I'm trying to implement the decorator by having it populate a static
> > member list of whatever class it's in with a reference to the method.
> > getExposedMethods() would then return the contents of each of those
> > lists from itself back to Exposed in the class hierarchy.  The first
> > problem was that having a reference to the method (i.e. talk()) does
> > not allow you to get a reference to the enclosing class (I had hoped
> > im_class would lead me there).
>
> Not yet. When your decorator is called, the class object is not yet
> created, and what you are decorating is a plain function.
>
> > The real hiccup was that explicitly
> > passing the class as an argument to the decorator generates a undefined
> > global name error, presumably because at that point of execution the
> > class object hasn't been fully created/initialised.
>
> Exactly.
>
> > So how can this be done?
>
> The simplest thing is to use a two-stages scheme : mark the functions as
> exposed, then collect them:
>
> def expose(func):
>   func._exposed = True
>   return func
>
> def exposed(obj):
>   return callable(obj) and getattr(obj, '_exposed', False)
>
> class Exposing(object):
>   @classmethod
>   def get_exposed_methods(cls):
> try:
>   exposeds = cls._exposed_methods
> except AttributeError:
>   exposeds = []
>   for name in dir(cls):
> obj = getattr(cls, name)
> if exposed(obj):
>   exposeds.append(obj)
>   cls._exposed_methods = exposeds
> return exposeds
>
> class Parrot(Exposing):
>   @expose
>   def parrot(self, what):
> return "%s says %s" % (self, str(what))
>
>
>
> HTH
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"

Thanks Bruno.  I came up with a similar solution today at work, which
involves an 'init' method which is called at the bottom of each module
that defines subclasses of Exposed and sets up static mappings for the
exposed methods.  I guess my solution is slightly less elegant because
it requires this ugly explicit init call outside the classes that it
actually deals with, however it is more efficient because the dir()
pass happens once on module load, instead of every time I want the list
of exposed methods.

Thanks for the help though,
Glen

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


Re: MySQLdb for Python 2.5

2006-10-05 Thread FatherAntox

Martin v. Löwis wrote:
> Harold Trammel schrieb:
> > Does anyone know the status of a version of MySQLdb that will work with
> > Python 2.5?
>
> AFAICT, MySQLdb 1.2.1 builds and works just fine.
>
> Regards,
> Martin

Hi Martin,

What is your setup as I am receiving a number of "Cannot open ..."
errors related to various msysql libraries and includes?  I am running
in a Windows XP environment with MySQL 5.1.  Thanks in advance.

Harold

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


Re: How do I read Excel file in Python?

2006-10-05 Thread John Machin

kath wrote:
> How do I read an Excel file in Python?
>
> I have found a package to read excel file, which can be used on any
> platform.

Hi Sudhir,
So far, so good :-)

>
> http://www.lexicon.net/sjmachin/xlrd.htm
> I installed and working on the examples, I found its printing of cell's
> contents in a different manner.
>
> >>> import xlrd
> >>> book=xlrd.open_workbook("Calculation_file.xls")
> >>> book=xlrd.open_workbook("testbook.xls")
> >>> sh=book.sheet_by_index(0)
> >>> for row in range(sh.nrows):
>   print sh.row(rx)
> [text:u'name', text:u'address', text:u'ph']
> [text:u'sudhir', text:u'bangalore', number:1234.0]
> [text:u'vinay', text:u'bangalore', number:3264.0]

It helps when asking questions if you copy/paste exactly what is on
your screen;
in this case
print sh.row(rx)
would have given an error; you must have typed
for rx in range.

A row is returned as a sequence of Cell objects. What you are seeing is
Python automatically doing repr(cell) on each cell in the row. The
Cell.__repr__ method formats it that way for debugging. Here are some
examples from a little test file of mine:

>>> import xlrd
>>> bk = xlrd.open_workbook('sjm1.xls')
>>> sh = bk.sheet_by_index(0)
>>> row0 = sh.row(0)
>>> row0
[text:u'fubar', number:1.0, number:2.0]
>>> firstcell = row0[0]
>>> type(firstcell)

>>> firstcell.ctype
1
>>> # cell type 1 is text
>>> firstcell.value
u'fubar'
>>> repr(firstcell)
"text:u'fubar'"

>
> I am bit confused with slicing. help me
>
None of the above is anything to do with slicing; is this a 2nd
problem?

Perhaps you are having trouble with this:
>>> help(sh.row_slice)
Help on method row_slice in module xlrd.sheet:

row_slice(self, rowx, start_colx=0, end_colx=None) method of
xlrd.sheet.Sheet instance
##
# Returns a slice of the Cell objects in the given row.
>>>

sh.row_slice(rowx, lo, hi) gives the same result as sh.row(rowx)[lo:hi]
-- it is provided because the latter would be inefficient for getting a
small slice from a long row.

If you are having trouble with the general concept of slicing, perhaps
you might like to try the Python tutorial. Otherwise, please try to be
a bit more specific about what the confusion is.

HTH, and e-mail me if you prefer ...

Cheers,
John

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


Re: Getting a ValueError with comtypes

2006-10-05 Thread Thomas Heller
[EMAIL PROTECTED] schrieb:
> Hello,
> 
> I am working with comtypes to interface Microsoft's DirectShow library.

Cool, another one using comtypes!
 
> First, I found a Type Library on the internet that was created for
> accessing DirectShow from .NET.  It seems that DirectShow only comes
> with IDL files and no type library.

What I sometimes do is to compile the IDL files into a typelib just
for creating the comtypes interface wrappers.  This may be somewhat
dangerous because these typelibs should *not* be registered by accident,
so that they do not conflict with other typelibs.

Then, I found out with oleview that on my system the IMediaControl interface
is described in the 'ActiveMovie control type library (Ver 1.0)',
in c:\windows\system32\quartz.dll.  So I was able to create the wrapper
by calling comtypes.client.GetModule("quartz.dll") - it seems that windows
searches the $PATH to find type libraries.

> This got me started.
> 
> The following line imports the typelibrary and automatically generates
> a wrapper module for DirectShow.
> 
> ds = comtypes.client.GetModule('DirectShow.tlb')
> 
> Next, I can basically start with something like this:
> 
> graph = comtypes.CoCreateInstance(CLSID_FilterGraph, ds.IGraphBuilder,
> comtypes.CLSCTX_INPROC_SERVER)
> 
> I had to create the CLSID_FilterGraph parameter myself by doing the
> following:
> 
> CLSID_FilterGraph =
> comtypes.GUID('{e436ebb3-524f-11ce-9f53-0020af0ba770}')
> 
> One of the first issues I ran into was that the type library I found on
> the web didn't expose the IMediaControl interface.  So, using the
> generated wrapper as a template, I created my own wrapper:
> 
> class IMediaControl(comtypes.IUnknown):
> _case_insensitive_ = True
> _iid_ = comtypes.GUID('{56A868B1-0AD4-11CE-B03A-0020AF0BA770}')
> _idlflags_ = []
> IMediaControl._methods_ = [
> COMMETHOD([], HRESULT, 'Run'),
> COMMETHOD([], HRESULT, 'Pause'),
> COMMETHOD([], HRESULT, 'Stop'),
> COMMETHOD([], HRESULT, 'StopWhenReady'),
> COMMETHOD([], HRESULT, 'GetState',
>   (['in'], c_long, 'msTimeout'),
>   (['out'], POINTER(c_int), 'pfs' ))
> ]
> 
> This got me further.  Once I defined the interface, I get access to the
> interface by calling:
> 
> control = graph.QueryInterface(IMediaControl)
> 
> This seemed to work.  Once I got everything setup, I tried to use this
> interface.  For example:
> 
> control.Run()
> 
> This generates an exception:
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "ds.py", line 462, in play
> control.Run()
> ValueError: Procedure probably called with not enough arguments (4
> bytes missing)
> 
> You can get errors like this when using ctypes if you use the wrong
> calling convention (CDLL versus WINDLL).
> 
> The method "Run" on the IMediaControl interface doesn't take any
> arguments.
> 
> I did notice that some wrapper code uses STDMETHOD versus COMMETHOD,
> but changing this didn't make any difference.
> 
> Can anyone explain what might be happening here, or offer some
> suggestions?

Your mistake here is that IMediaControl derives from IDispatch, not IUnknown.
So, control.Run() really calls the first IDispatch method, which is
GetTypeInfoCount(), which takes one argument ;-).

I'm not 100% sure the following code will work for you because I'm using
a comtypes version that's not yet committed to the repository, but it works
for me:

from comtypes.client import GetModule, CreateObject

# create and import the interface wrapper
ds = GetModule("quartz.dll")

# FilgraphManager is what the wrapper shows as coclass,
# you can pass that to CreateObject instead of a CLSID or ProgID.
# CreateObject calls QueryInterface for the 'most useful' interface,
# so usually there's no need to specify the interface you want:
fg = CreateObject(ds.FilgraphManager)

# this prints '0'
print fg.Run()

Thomas

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


Re: Access to static members from inside a method decorator?

2006-10-05 Thread Maric Michaud
Le jeudi 05 octobre 2006 17:18, [EMAIL PROTECTED] a écrit :
> I guess my solution is slightly less elegant because
> it requires this ugly explicit init call outside the classes that it
> actually deals with, however it is more efficient because the dir()
> pass happens once on module load, instead of every time I want the list
> of exposed methods.

You can always replace the need of the init method on classes using a 
metaclass.

This demonstrates it with Bruno's expose decorator, but it can be done with 
your actual init func too.

In [6]: class m(type) :
   ...: def __init__(self, *a,**kw) :
   ...: for name, meth in self.__dict__.items() :
   ...: if getattr(meth, '_exposed', False) :
   ...: print 'exposed :', name
   ...:
   ...:

In [7]: class a(object):
   ...: __metaclass__ = m
   ...: def f(self) :pass
   ...: @expose
   ...: def g(self) :pass
   ...:
   ...:
exposed : g

In [8]: class b(a) :
   ...: @expose
   ...: def h(self) :pass
   ...:
   ...:
exposed : h




-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: building strings from variables

2006-10-05 Thread Matthew Warren

> -Original Message-
> From: 
> [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED]
> rg] On Behalf Of Gal Diskin
> Sent: 05 October 2006 16:01
> To: [email protected]
> Subject: building strings from variables
> 
> Following a discussion with an associate at work about various ways to
> build strings from variables in python, I'd like to hear your opinions
> and preferred methods. The methods we discussed are:
> 1.  some_string = "cd %s ; %s  %d %s %s" % ( working_dir, ssh_cmd,
> some_count, some_param1, some_param2)
> 
> 2. import string
> template = string.Template("cd $dir ; $cmd $count $param1
> $param2")
> some_string = template.substitute(dict(dir=working_dir,
> 
> cmd=ssh_cmd,
> 
> count=some_count,
> 
> pararm1=some_param1,
> 
> param2=some_param2))
> here you can use a couple of nice tricks by using class.__dict__ and
> globals() \ locals() dictionaries.
> 
> 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ "
> "+str(some_count)+" "+some_param1+" "+some_param2
> (all these are supposed to produce the same strings)
> 
> Which methods do you know of \ prefer \ think is better because...?
> I will appreciate any opinions about the matter.

:D

I think, it would depend really on what your aims are (readable code,
fast string generation...), and how the vars you want to build the
string from are respresented in your code (is it natural to use a dict
etc..)

I kicked off a conversation similar to this earlier today, and that was
my conclusion after helpful debate & advice.

Matt.


This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asychronous execution *with* return codes?

2006-10-05 Thread Justin
If you're on a POSIX system, you could use the usual fork/exec/wait:

import os
for lstArgs in pileOflstArgs:
pid = os.fork()
if not pid:
os.execv( app, lstArgs )

for i in range(len(pileOflstArgs)):
pid, status = os.wait()

Of couse, os.wait() will block until a child exits. Look at the docs
for the status code it returns, though, as it's not just the return
value of the process.

On Oct 5, 7:43 am, "utabintarbo" <[EMAIL PROTECTED]> wrote:
> MonkeeSage wrote:
> > utabintarbo wrote:
> > > pid = subprocess.Popen([app] + lstArgs).pid
>
> > Check out the poll() method and the returncode attribute:
> >http://docs.python.org/lib/node533.htmlThanks for the reply.
>
> If I understand your meaning, I should do something like this (given I
> wish to run an app against several arguments [my use case]):
>
> for lstArgs in pileOflstArgs:
> uniqueProcessID = subprocess.Popen([app] + lstArgs)
> pid = uniqueProcessID.pid
> retcode = uniqueProcessID.poll()
> # increment uniqueProcessID
> 
>
> If so, how do I handle the poll() on long-running processes? Run a
> bunch and then start a check loop? Am I asking too many questions?

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


Re: user modules

2006-10-05 Thread Tuomas
Cameron Walsh wrote:
> Hi,
> 
> I'm writing a python program to analyse and export volumetric data.  To 
> make development and extension easier, and to make it more useful to the 
> public when it is released (LGPL), I would like to enable users to place 
> their own python files in a "user_extensions" directory.  These files 
> would implement a common interface in order for the main program to be 
> able to read them and execute the necessary code.
> 
> My question is what is the best way of implementing this?
> 
> I have investigated importing them as modules, but unless the user 
> modifies the main program I cannot see how the main program can learn of 
> the existence of specific modules.
> 
> For example:
> 
> from user_modules import *
> # directory 'user_modules' contains __init__.py allowing this
> # From here I would need a list of the imported modules, in order to
> # execute a common command on each of them, such as
> 
> for module in imported_modules:
> module.initialise()
> module.get_tab_window()
> 
> 
> How do I get from the first bit to the second bit, or is there a better 
> way of obtaining the functionality I need?
> 
> 
> --Cameron.

import os

files=os.listdir('user_modules')
tabs=[]
for fle in files:
 if fle.endswith('.py'):
 module=__import__(fle[0:-3], 'user_modules', None,
['initialise', 'get_tab_window'])
 module.initialise()
 tabs.append(module.get_tab_window())

*not tested*

print __import__.__doc__
__import__(name, globals, locals, fromlist) -> module

Import a module.  The globals are only used to determine the context;
they are not modified.  The locals are currently unused.  The fromlist
should be a list of names to emulate ``from name import ...'', or an
empty list to emulate ``import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty.

Tuomas

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


Re: Why do this?

2006-10-05 Thread Terry Reedy

"Matthew Warren" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I learned over the years to do things like the following, and I like
> doing it like this because of readability, something Python seems to
> focus on :-
>
> Print "There are "+number+" ways to skin a "+furryanimal

In python:
IDLE 1.1.3
>>> number = 3
>>> furryanimal = 'rat'
>>> print 'There are', number, 'of ways to skin a', furryanimal
There are 3 of ways to skin a rat

You have to remember that spaces are added automatically.
Printing a comma list is quite common in informal and preliminary work
and sometimes in finished work when its output is good enough.

> But nowadays, I see things like this all over the place;
>
> print("There are %s ways to skin a %s" % (number, furryanimal))

This gives more control over exact format of output.
Some people may also prefer having variables grouped together at end,
especially if they 'grew up' on C (for instance) rather than Basic.

Terry Jan Reedy



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


Re: ANN: Tftpy 0.1 - Pure Python TFTP Library

2006-10-05 Thread msoulier
msoulier wrote:
> Announcing new project, Tftpy, a Pure Python TFTP implementation.
>
> About Release 0.1:
> ==
>
> This is an initial release in the spirit of "release early, release
> often". Currently the sample client works, supporting RFC 1350. The
> server is not yet implemented, and RFC 2347 and 2348 support (variable
> block sizes) is underway, planned for 0.2.

Update on that, RFC 2347 and 2348 support wasn't difficult, so I just
pushed out release 0.2.

Enjoy,
Mike

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


Re: Oracle database export

2006-10-05 Thread Diez B. Roggisch
Tor Erik Soenvisen wrote:

> Hi,
> 
> I need to export an Oracle database to a DDL-formated file. On the Web, I
> found a Python script that did exactly this for a MS Access database, but
> not one for Oracle databases.
> 
> Does anyone know of such a tool or Python script.

Oracle is equipped with tools to do that. For example the conveniently named
export tool "exp"

No python in the equation, though.


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


Re: Getting a ValueError with comtypes

2006-10-05 Thread winkatl1213
Thomas,

Thanks a ton for the quick response.

I called GetModule('quartz.dll'), and now I can at least call
IMediaControl::Run.  I get another error, but that's my problem (I
don't have the graph set correctly yet).

You mentioned that you sometimes create a type library for creating the
interface wrappers.

Would you mind sharing with me how you do this?

I seem to recall a thread on ctypes-users where you were looking for a
method to do this.  I can't seem to locate what you conclusion was.

By the way, I've been using ctypes and comtypes quite a bit lately, and
I just wanted to say that they are both excellent.

Now if only I had an equivalent way to access C++ dlls, I'd no longer
have to write typemaps in SWIG.

While I'm at it, I thought I would ask you a separate completely
unrelated question.

I have a C++ library wrapped with SWIG.  One member function takes a
void* to a buffer.

I want to allocate this buffer using ctypes and pass it to my SWIG
wrapper, but I've been struggling to get it to work.

I tried passing in the addressof, and then casting it back in my SWIG
wrapper, but this doesn't work.  Do you have any suggestions on this?

I've also thought about using a numpy array, since this is supported in
both SWIG and ctypes.

Thanks again for your help.,

Jeff

Thomas Heller wrote:
> [EMAIL PROTECTED] schrieb:
> > Hello,
> >
> > I am working with comtypes to interface Microsoft's DirectShow library.
>
> Cool, another one using comtypes!
>
> > First, I found a Type Library on the internet that was created for
> > accessing DirectShow from .NET.  It seems that DirectShow only comes
> > with IDL files and no type library.
>
> What I sometimes do is to compile the IDL files into a typelib just
> for creating the comtypes interface wrappers.  This may be somewhat
> dangerous because these typelibs should *not* be registered by accident,
> so that they do not conflict with other typelibs.
>
> Then, I found out with oleview that on my system the IMediaControl interface
> is described in the 'ActiveMovie control type library (Ver 1.0)',
> in c:\windows\system32\quartz.dll.  So I was able to create the wrapper
> by calling comtypes.client.GetModule("quartz.dll") - it seems that windows
> searches the $PATH to find type libraries.
>
> > This got me started.
> >
> > The following line imports the typelibrary and automatically generates
> > a wrapper module for DirectShow.
> >
> > ds = comtypes.client.GetModule('DirectShow.tlb')
> >
> > Next, I can basically start with something like this:
> >
> > graph = comtypes.CoCreateInstance(CLSID_FilterGraph, ds.IGraphBuilder,
> > comtypes.CLSCTX_INPROC_SERVER)
> >
> > I had to create the CLSID_FilterGraph parameter myself by doing the
> > following:
> >
> > CLSID_FilterGraph =
> > comtypes.GUID('{e436ebb3-524f-11ce-9f53-0020af0ba770}')
> >
> > One of the first issues I ran into was that the type library I found on
> > the web didn't expose the IMediaControl interface.  So, using the
> > generated wrapper as a template, I created my own wrapper:
> >
> > class IMediaControl(comtypes.IUnknown):
> > _case_insensitive_ = True
> > _iid_ = comtypes.GUID('{56A868B1-0AD4-11CE-B03A-0020AF0BA770}')
> > _idlflags_ = []
> > IMediaControl._methods_ = [
> > COMMETHOD([], HRESULT, 'Run'),
> > COMMETHOD([], HRESULT, 'Pause'),
> > COMMETHOD([], HRESULT, 'Stop'),
> > COMMETHOD([], HRESULT, 'StopWhenReady'),
> > COMMETHOD([], HRESULT, 'GetState',
> >   (['in'], c_long, 'msTimeout'),
> >   (['out'], POINTER(c_int), 'pfs' ))
> > ]
> >
> > This got me further.  Once I defined the interface, I get access to the
> > interface by calling:
> >
> > control = graph.QueryInterface(IMediaControl)
> >
> > This seemed to work.  Once I got everything setup, I tried to use this
> > interface.  For example:
> >
> > control.Run()
> >
> > This generates an exception:
> >
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "ds.py", line 462, in play
> > control.Run()
> > ValueError: Procedure probably called with not enough arguments (4
> > bytes missing)
> >
> > You can get errors like this when using ctypes if you use the wrong
> > calling convention (CDLL versus WINDLL).
> >
> > The method "Run" on the IMediaControl interface doesn't take any
> > arguments.
> >
> > I did notice that some wrapper code uses STDMETHOD versus COMMETHOD,
> > but changing this didn't make any difference.
> >
> > Can anyone explain what might be happening here, or offer some
> > suggestions?
>
> Your mistake here is that IMediaControl derives from IDispatch, not IUnknown.
> So, control.Run() really calls the first IDispatch method, which is
> GetTypeInfoCount(), which takes one argument ;-).
>
> I'm not 100% sure the following code will work for you because I'm using
> a comtypes version that's not yet committed to the repository, but it works
> for me:
>
> from comtypes.client import GetModule, CreateObject
>
> # create and import the in

Re: What value should be passed to make a function use the default argument value?

2006-10-05 Thread Fredrik Lundh
Antoon Pardon wrote:

> The first module I looked in to check this, it wasn't true. In the Queue
> Module is isn't explicitly written that maxsize is a keyword argument yet
> Queue.Queue(maxsize=9) works just fine.

it's not a matter whether it works fine in any given version of Python, 
it's a matter of whether it's *guaranteed* to work.



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


Re: building strings from variables

2006-10-05 Thread Rainy

Gal Diskin wrote:
> Following a discussion with an associate at work about various ways to
> build strings from variables in python, I'd like to hear your opinions
> and preferred methods. The methods we discussed are:
> 1.  some_string = "cd %s ; %s  %d %s %s" % ( working_dir, ssh_cmd,
> some_count, some_param1, some_param2)
>
> 2. import string
> template = string.Template("cd $dir ; $cmd $count $param1
> $param2")
> some_string = template.substitute(dict(dir=working_dir,
>
> cmd=ssh_cmd,
>
> count=some_count,
>
> pararm1=some_param1,
>
> param2=some_param2))
> here you can use a couple of nice tricks by using class.__dict__ and
> globals() \ locals() dictionaries.
>
> 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ "
> "+str(some_count)+" "+some_param1+" "+some_param2
> (all these are supposed to produce the same strings)
>
> Which methods do you know of \ prefer \ think is better because...?
> I will appreciate any opinions about the matter.

My opinion is that 1st method is the best. It's both very readable and
easy to write. 2nd way is too involved, and 3rd way is both hard to
read and difficult to compose. Another useful variant of method #1 is
to do this: %(varname)s ..." % globals()

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


weakSet

2006-10-05 Thread jean . philippe . mague
Hello,

Has anyone ever think about a set wich references its elements weakly ?
The *easy* solution would provide a WeakSet class with the following
behavior:
>>>s=set([a, b])
>>>ws=WeakSet([b,c])
>>>(ws&s).__class__() is WeakSet
True
>>>s&ws
TypeError: unsupported operand type(s) for &: 'set' and 'instance'

the hard olution would  add the following behavior:
>>>(s&ws).__class__() is WeakSet
True

Any hint for the easy solution ?
for the hard one ?

Jean-Philippe

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


RE: Where is Python in the scheme of things?

2006-10-05 Thread Sells, Fred
Every C++ and Java programmer that I know, who have done a moderate sized
project in Python (thus requiring learning it's strengths) states that they
hope to never go back to C++ or Java.

I cannot comment on VB programmers, since I don't speak to them ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: user modules

2006-10-05 Thread Juho Schultz
Cameron Walsh wrote:
> Hi,
>
> I'm writing a python program to analyse and export volumetric data.  To
> make development and extension easier, and to make it more useful to the
> public when it is released (LGPL), I would like to enable users to place
> their own python files in a "user_extensions" directory.  These files
> would implement a common interface in order for the main program to be
> able to read them and execute the necessary code.
>
> My question is what is the best way of implementing this?
>
> I have investigated importing them as modules, but unless the user
> modifies the main program I cannot see how the main program can learn of
> the existence of specific modules.
>

One simple solution would be a shell script that adds user_extensions
(or whatever) to $PYTHONPATH and then starts your main program.

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


Re: How do I read Excel file in Python?

2006-10-05 Thread kath

John Machin wrote:
> kath wrote:
> > How do I read an Excel file in Python?
> >
> > I have found a package to read excel file, which can be used on any
> > platform.
>
> Hi Sudhir,
> So far, so good :-)
>
> >
> > http://www.lexicon.net/sjmachin/xlrd.htm
> > I installed and working on the examples, I found its printing of cell's
> > contents in a different manner.
> >
> > >>> import xlrd
> > >>> book=xlrd.open_workbook("Calculation_file.xls")
> > >>> book=xlrd.open_workbook("testbook.xls")
> > >>> sh=book.sheet_by_index(0)
> > >>> for row in range(sh.nrows):
> > print sh.row(rx)
> > [text:u'name', text:u'address', text:u'ph']
> > [text:u'sudhir', text:u'bangalore', number:1234.0]
> > [text:u'vinay', text:u'bangalore', number:3264.0]
>
> It helps when asking questions if you copy/paste exactly what is on
> your screen;
> in this case
> print sh.row(rx)
> would have given an error; you must have typed
> for rx in range.
>
> A row is returned as a sequence of Cell objects. What you are seeing is
> Python automatically doing repr(cell) on each cell in the row. The
> Cell.__repr__ method formats it that way for debugging. Here are some
> examples from a little test file of mine:
>
> >>> import xlrd
> >>> bk = xlrd.open_workbook('sjm1.xls')
> >>> sh = bk.sheet_by_index(0)
> >>> row0 = sh.row(0)
> >>> row0
> [text:u'fubar', number:1.0, number:2.0]
> >>> firstcell = row0[0]
> >>> type(firstcell)
> 
> >>> firstcell.ctype
> 1
> >>> # cell type 1 is text
> >>> firstcell.value
> u'fubar'
> >>> repr(firstcell)
> "text:u'fubar'"
>
> >
> > I am bit confused with slicing. help me
> >
> None of the above is anything to do with slicing; is this a 2nd
> problem?
>
> Perhaps you are having trouble with this:
> >>> help(sh.row_slice)
> Help on method row_slice in module xlrd.sheet:
>
> row_slice(self, rowx, start_colx=0, end_colx=None) method of
> xlrd.sheet.Sheet instance
> ##
> # Returns a slice of the Cell objects in the given row.
> >>>
>
> sh.row_slice(rowx, lo, hi) gives the same result as sh.row(rowx)[lo:hi]
> -- it is provided because the latter would be inefficient for getting a
> small slice from a long row.
>
> If you are having trouble with the general concept of slicing, perhaps
> you might like to try the Python tutorial. Otherwise, please try to be
> a bit more specific about what the confusion is.
>
> HTH, and e-mail me if you prefer ...
>
> Cheers,
> John


Hi, thanks for the reply. I just took some time reading help file and
came to know to there is nothing do with slicing. But I do have a
problem with date field in the excel file.

the date( 8/9/2006 ) in Excel file, i am getting the value as 38938.0,
which I get when I convert date values to general format in Excel. I
want the actual date value. How do get that?


Thank you.
regards,
Sudhir.

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


Re: Python to use a non open source bug tracker?

2006-10-05 Thread Michael Ströder
Giovanni Bajo wrote:
> Martin, I am by no means understimating Daniel's work. I am just noting that
> the spare-time work he did is, by definition, much much lower than the "6-10
> people" that the PSF infrastructure committee is calling for. I would like 
> this
> statement to be officially reduced to "2-3 people", since it is *really* not
> required much more than that to setup a bug tracker installation, and no more
> than 1 person to maintain it afterwards.

Glancing over this thread I wonder what these people are supposed to do.
Any list of requirements available?

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weakSet

2006-10-05 Thread Tim Peters
[EMAIL PROTECTED]
> Has anyone ever think about a set wich references its elements weakly ?

Yes, and there are excruciating subtleties.  I only implemented as
much of one as ZODB needed at the time:

# A simple implementation of weak sets, supplying just enough of Python's
# sets.Set interface for our needs.

class WeakSet(object):
"""A set of objects that doesn't keep its elements alive.

The objects in the set must be weakly referencable.
The objects need not be hashable, and need not support comparison.
Two objects are considered to be the same iff their id()s are equal.

When the only references to an object are weak references (including
those from WeakSets), the object can be garbage-collected, and
will vanish from any WeakSets it may be a member of at that time.
"""

For the rest ;-), including discussion of excruciating subtleties that
arise even implementing this little, see:

http://svn.zope.org/ZODB/trunk/src/ZODB/utils.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I read Excel file in Python?

2006-10-05 Thread Matimus
> the date( 8/9/2006 ) in Excel file, i am getting the value as 38938.0,
> which I get when I convert date values to general format in Excel. I
> want the actual date value. How do get that?

38938 appears to be the date in days since 1/1/1900. I'm sure someone
can help you figure out how to convert that to a more useful value.

-Matt

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


Re: Access to static members from inside a method decorator?

2006-10-05 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Bruno Desthuilliers wrote:
(snip)
>> class Exposing(object):
>>   @classmethod
>>   def get_exposed_methods(cls):
>> try:
>>   exposeds = cls._exposed_methods
>> except AttributeError:
>>   exposeds = []
>>   for name in dir(cls):
>> obj = getattr(cls, name)
>> if exposed(obj):
>>   exposeds.append(obj)
>>   cls._exposed_methods = exposeds
>> return exposeds
>>
>> class Parrot(Exposing):
>>   @expose
>>   def parrot(self, what):
>> return "%s says %s" % (self, str(what))
> 
> Thanks Bruno.  I came up with a similar solution today at work, which
> involves an 'init' method which is called at the bottom of each module
> that defines subclasses of Exposed and sets up static mappings for the
> exposed methods.  I guess my solution is slightly less elegant because
> it requires this ugly explicit init call outside the classes that it
> actually deals with, 

This is only a problem in a framework-style use.

> however it is more efficient because the dir()
> pass happens once on module load, instead of every time I want the list
> of exposed methods.

I think you have missed a point in my solution : the 'collect' pass
happens only once for each class - the first time the
get_exposed_methods is called on the class (or any instance of). It's
then memoized for latter calls.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to static members from inside a method decorator?

2006-10-05 Thread Bruno Desthuilliers
Maric Michaud wrote:
> Le jeudi 05 octobre 2006 17:18, [EMAIL PROTECTED] a écrit :
>> I guess my solution is slightly less elegant because
>> it requires this ugly explicit init call outside the classes that it
>> actually deals with, however it is more efficient because the dir()
>> pass happens once on module load, instead of every time I want the list
>> of exposed methods.
> 
> You can always replace the need of the init method on classes using a 
> metaclass.
> 
> This demonstrates it with Bruno's expose decorator, but it can be done with 
> your actual init func too.
> 
> In [6]: class m(type) :
>...: def __init__(self, *a,**kw) :
>...: for name, meth in self.__dict__.items() :

NB : This will only get methods exposeds in this class - not the one
exposeds in the parent classes...

>...: if getattr(meth, '_exposed', False) :
>...: print 'exposed :', name
>...:
>...:
> 

(snip)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to use a non open source bug tracker?

2006-10-05 Thread Fredrik Lundh
Michael Ströder wrote:

> Glancing over this thread I wonder what these people are supposed to do.
> Any list of requirements available?

from the original announcement (linked from the first post in this thread):

   "In order for Roundup to be considered equivalent in terms of an
   overall tracker package there needs to be a sufficient number of
   volunteer admins (roughly 6 - 10 people) who can help set up and
   maintain the Roundup installation. /.../

   If people want Roundup to be considered the tracker we go with by
   volunteering to be an admin, please email infrastructure at python.org
   and state your time commitment, the timezone you would be working
   from, and your level of Roundup knowledge.  Please email the committee
   by October 16."



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


  1   2   3   >