GTK for windows and Linux

2005-11-16 Thread Ask
Hi All,

Can someone please tell me what I need to use GTK with python for windows 
and Linux?

Any links to the appropriate installations would be greatly appreciated as I 
don't know what I need... GIMP... GTK+ etc

Thanks for any advice

Pauly




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


Re: newbie - How do I import automatically?

2005-11-16 Thread Mikael Olofsson
[EMAIL PROTECTED] wrote:
> I tried to put the line
> from btools import *
> in several places in PyShell.py
> but to now avail. It does not work, IDLE does not execute it???

IDLE definitely executes PyShell.py upon startup, since IDLE does not 
even appear on the screen if there is an error in that file. The 
following seems to work for me, in PyShell.py. After importing both sys 
and os,

sys.modules['__main__'].__dict__['os'] = os

Then, if I start IDLE, the module os is directly available.

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


Re: is parameter an iterable?

2005-11-16 Thread Steven D'Aprano
Fredrik Lundh wrote:

> Steven D'Aprano wrote:
> 
> 
>>This means we're no longer assuming what the error message will be,
>>which makes our code a lot more future-proof and implementation-proof: if
>>some version of Python changes the error string from "iteration over
>>non-sequence" to something else, the code should continue to work
>>correctly.
> 
> 
> Alex has already posted the right way to do this.  

Has he? Where and when? Is my crystal ball broken 
again? I hate it when I miss the one Usenet post all 
the cool kids are talking about.


> can you please stop

Can I please stop what? Using punctuation and 
capitalization correctly? Learning? Thinking for 
myself? Posting to Usenet? Programming in Python? Your 
post is unclear.



-- 
Steven.

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


Controlling Excel with win32com

2005-11-16 Thread Al Christians
I'm starting to test a python application that creates an Excel 
workbook, then fills in values for some cells and formulas for other 
cells.  The formulas involve circular references, which will cause Excel 
to take a little time to update and iterate through the successive 
approximations of finding a solution to the formulas.  (The system 
should converge pretty well -- no bad behavior expected.)

Since Excel runs as a com server in another window, is there anything 
that the python side of the win32com connection has to do to make sure 
that it is not calling Excel while Excel is busy recalculating or 
otherwise processing a previous request?  Are the assignments to the 
cell Value  and Formula properties synchronized for me somewhere?

I think that I've noticed a run-sometimes/crash-sometimes behavior in 
this program, but I'm so clueless about what's going on behind the 
scenes with com that I haven't really tied it down.  It seemed to get 
better behaved when I turned off automatic recalculation,  but that does 
not seem to me to be a guarantee that there will be no timing problems 
if the messages are not queued somewhere and if there is not some other 
mechanism to keep things synchronized.

What works best?

TIA


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


Re: best way to discover this process's current memory usage, cross-platform?

2005-11-16 Thread [EMAIL PROTECTED]
Alex Martelli wrote:
>
> Considering that the main purpose is adding regression tests to confirm
> that a hopefully-fixed memory leak does not recur, I'm not sure why
> shared memory should be a problem.  What scenarios would "leak shared
> memory"?

Apache leaks SHM segments in some scenarios.  SysV SHM segments aren't
freed explicitly when the process exits.  They're easy enough to clean
up by hand, but it's nicer to avoid that.

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


Re: subprocess terminate help

2005-11-16 Thread Do Re Mi chel La Si Do
Hi!

Self-destruction of a script:

import os
os.popen('TASKKILL /PID '+str(os.getpid())+' /F')

(only in windows XP or 2K)


@-salutations

Michel Claveau



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


Re: Creating (rather) generic plugin framework?

2005-11-16 Thread Jean-Paul Calderone
On Wed, 16 Nov 2005 17:14:27 +0200, Edvard Majakari <[EMAIL PROTECTED]> wrote:
>Hi,
>
>My idea is to create a system working as follows: each module knows
>path to plugin directory, and that directory contains modules which
>may add hooks to some points in the code.
>
>Inspired by http://www.python.org/pycon/2005/papers/7/pyconHooking.html

You may want to look at a few existing Python plugin systems.  To get you 
started, here's a link to the Twisted plugin system documentation: 


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


Re: python-mysqldb__debian_to_freebsd

2005-11-16 Thread Mike Meyer
Damjan <[EMAIL PROTECTED]> writes:
>>   Is there any at all chance that this will work
>>   with the proper configs or should I go ahead
>>   and beg the host for an installation ?
> It seems to me very unlikely that a program compiled for FreeBSD would link
> to a library compiled for Debian Linux which in turn was linked to a Debian
> libmysql but now has to work with the FreeBSD libmysql... I just don't
> beleive you can make this work.

Arrgh. Damjan, you *really* should have left enough context for those
reading what you have to say to figure out what that "this" was. I
have as yet to see the original on my news server, so I chased it down
on Google groups.

For the interested, the OP (Stanley Kitching), wants to use a
python-mysqldb module on his web host running FreeBSD. They don't have
the that installed, so he tried getting the Debian binary distrubtion
of the library to work, and failed. He's wondering if this is at all
possible.

Answer: yes, it might (key word - might) be made to work. Linux shared
libraries have been made to work with native applications on FreeBSD
before. I don't have the details, but would expect you'd have to
install large chunks of a Debian system to make this work. If you
really want to do this, let me know and I'll chase the details down
for you.

However, that's the wrong way to do this. First step - ask your
hosting service to install databases/py-MySQLdb. That's the Python
MySQLdb port in the FreeBSD ports tree. Installing it should be
trivial. If they won't, I'd seriously consider changing services. I
can recommend a FreeBSD-based hosting service that will install pretty
much anything in the ports tree.

The next thing to try is getting the MySQLdb pkg for FreeBSD. A pkg is
the format that FreeBSD uses for binary distributions. Look in
ftp://ftp.freebsd.org/pub/FreeBSD/ports//packages-/databases.
Supported architectures are alpha, amd64, i386, ia64 and
sparc64. Supported releases (for i386, anyway) include the last
release version of FreeBSD 4, 5 and 6, the stable branch of 4 and 6,
the development and stable branches of 5, and 7-current. Most of those
should be for Python 2.4. The one I checked had MySQLdb 1.2.0 and
1.2.1c3 (a development branch).

If that fails (because they don't have a binary for the right
combination of OS and Python), get the version of the os (use the
command "uname -pr") and the version of Python, and ask here and on
[EMAIL PROTECTED] to see if someone with an appropriate
installation will build you a binary. I'll do it if I have the
appropriate version of FreeBSD installed. Or install FreeBSD on a
spare system and build it yourself - once you get FreeBSD installed,
the rest is trivial, and I'll be glad to provide pointers for that.

If all that fails, *then* it's time to look into getting the debian
version of the library to work.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running functions

2005-11-16 Thread Gorlon the Impossible
On Thu, 17 Nov 2005 00:08:02 GMT, [EMAIL PROTECTED] (Cameron Laird)
wrote:

>In article <[EMAIL PROTECTED]>,
>Grant Edwards  <[EMAIL PROTECTED]> wrote:
>>On 2005-11-16, Gorlon the Impossible <[EMAIL PROTECTED]> wrote:
>>
>>> I'm not sure how to phrase this question. I have a Python function
>>> that sends MIDI messages to a synth. When I run it, I of course have
>>> to wait until it is finished before I can do anything else with
>>> Python. Is it possible to run this function and still be able to do
>>> other things with Python while it is running?
>>
>>Yes.
>>
>>> Is that what threading is about?
>>
>>Exactly.  Take a look at the "treading" module:
>>
>>http://www.python.org/doc/current/lib/module-threading.html
>   .
>   .
>   .
>I don't agree, Grant (although I salute the brevity
>of your follow-up), and a couple of other correspon-
>dents have already posted follow-ups that begin to
>explore the alternatives.
>
>If I were pursuing this, the first question I'd have
>for Gorlon is whether he's OK with a "fire and for-
>get" model.  By that, I mean to ask if it's OK to
>send the MIDI message, and then return immediately
>to other Python work, OR whether Gorlon also needs
>to stay in contact with the MIDI handler, and
>perhaps react especially when the MIDI handler
>finishes with the specific message.  That choice is
>crucial in a good concurrency design.

'good concurrency design'  LOL... I'm not that proficient at
programming in general or Python... 
You bring up some interesting points, though. I am just learning and
experimenting with programming MIDI events at this level. My function
sends a series of MIDI note-on and note-off messages and that's it so
far. But, I am trying to learn more and working towards a sort of
'live-coding' set-up for musical performance. So, eventually I will
want  to be able to control other synth parameters with MIDI messages
and be able to start and stop different kinds of control functions 'on
the fly' so to speak. I checked out the threading module and its
working for what I am trying to do at the moment, but I am open to
suggestions and eager to learn all I can about other options. Thanks
for taking the time to respond.
I would be interested in hearing more about the subprocess approach...

>
>So, Gorlon, yes, threading is a prominent member of
>the family of facilities that address situations like
>yours.  It's not the only one, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Auto Install Linux Rpm's

2005-11-16 Thread Lars Kellogg-Stedman
> We would like to use Python to automatically deploy new rpm's (assuming we
> first edit a file to require a new version).  I've just starting looking a
> the rpm module.  I can build this from scratch, but was wondering if anyone
> is/has solved some or all of this problem or could point me to some
> "goodies" that would help.  

"Yum" (the Fedora package manager) is written in Python, so it provides
both a good example of how to work with the Python rpm module and how to
do things like handle dependencies -- which you'll have to do if you
roll your own.

If I were you, I would probably just use Yum to do all the heavy
lifting, rather than trying to re-implement it.  Then your work boils
down to:

  IF (installed version of package) != (version of package in config
  file) THEN
yum -y install 
  END IF

-- Lars

-- 
Lars Kellogg-Stedman <[EMAIL PROTECTED]>
This email address will expire on 2005-11-23.

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


Re: Quitting a Tkinter application with confirmation

2005-11-16 Thread jepler
Sure, there's a difference.  Consider how this program behaves.
Quit only quits the mainloop, Destroy destroys the root widget.
When you Quit, you can enter the mainloop again.

from Tkinter import *
t = Tk()
Button(t, command=t.quit, text="Quit").pack()
Button(t, command=t.destroy, text="Destroy").pack()
t.mainloop()
t.mainloop()

Jeff


pgpY0B9ITm2VC.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python, Linux, Desktop Environment

2005-11-16 Thread jeremyvoros
Thanks everyone.

Making a shortcut was just too obvious for me...

I just made a KDE shortcut that runs the python command for me.

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


Re: Quitting a Tkinter application with confirmation

2005-11-16 Thread Peter Kleiweg
Fredrik Lundh schreef op de 16e dag van de slachtmaand van het jaar 2005:

> Peter Kleiweg wrote:
> 
> > I want the program to behave identical if the 'close' button of
> > the application window is clicked. I tried the code below,
> > using a class derived from Tk that redefines the destroy
> > method. That seems to work. At least on Linux.
> >
> > My questions:
> >
> > Is this the correct and save way to do this? Will it work on any
> > operating system? Shouldn't I do some event capturing instead?
> 
> the right way to do this is to implement a WM_DELETE_WINDOW
> protocol handler:
> 
> http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols
> 
> in your case, adding
> 
> root.protocol("WM_DELETE_WINDOW", root.destroy)
> 
> to the right place should be enough.

Yes, that works.

By the way, this example ends the program with root.destroy().
I used root.quit(). Is there a reason for using one or the other, 
or does it not matter? 


-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/~kleiweg/ls.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-mysqldb__debian_to_freebsd

2005-11-16 Thread Damjan
>   Is there any at all chance that this will work
>   with the proper configs or should I go ahead
>   and beg the host for an installation ?

It seems to me very unlikely that a program compiled for FreeBSD would link
to a library compiled for Debian Linux which in turn was linked to a Debian
libmysql but now has to work with the FreeBSD libmysql... I just don't
beleive you can make this work.

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


Re: Newbie wxPython ListCtrl Question

2005-11-16 Thread Todd7
Thank you very much.  That is exactly what I needed.

limodou <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> 2005/11/17, Todd7 <[EMAIL PROTECTED]>:
>> I am new to python and to wxWindows.  I have tried searching google,
>> reading the documentation and trying to figure out some of the
>> examples, but I am stumped as to how to get information out of a
>> listctrl at a certain row and column.  I tried to write a simple
>> example to learn to work with the listctrl as follows:
> 
> I'v made some helper function as that:
> 
> def getRowText(self, index, col):
> if index >= 0:
> return self.list_ctrl_1.GetItem(index, col).GetText()
> else:
> return ''
> 
> def getSelRowText(self, col):
> return self.getRowText(self.getSelection(), col)
> 
> def getSelection(self):
> return self.list_ctrl_1.GetNextItem(-1, wx.LIST_NEXT_ALL,
> wx.LIST_STATE_SELECTED)
> 
> You can just use self.getSelRowText(1) to gain the second column text
> of selection row.
> --
> I like python!
> My Blog: http://www.donews.net/limodou
> NewEdit Maillist: http://groups.google.com/group/NewEdit
> 

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


Re: Python obfuscation

2005-11-16 Thread Mike Meyer
[EMAIL PROTECTED] (Alex Martelli) writes:
> Mike Meyer <[EMAIL PROTECTED]> wrote:
>> Alex's solution doesn't require special treatment for disaster
>> recovery and/or planning, and as such is a valid answer to the
> I'm not sure I understand this.  I would assume that any software (or,
> for that matter, data) of any substantial importance, worthy of being
> deployed on a server, does include disaster planning (and recovery
> plans, in particular) as a routine part of server-side deployment
> (regular backups with copies off-site, etc etc).

To recap, I asked the question "how do provide software that is
protected but doesn't require special treatment in disaster recovery
and preparedness planning?"  I didn't raise the issue of server
deployment in light of this, but had earlier pointed it out as a good
solution to the general issue of copy protection. This resulted in my
beinng asked if I prefered your solution to an alternative that
involved local storage.

Anything on your server doesn't require any special treatment in my
planning. I might want to check what you promise to provide and how
well you live up to those promises as part of evaluating your service,
but that's a different issue. So "Put the software on a server and let
them run it there" is a valid answer to my question.

> So, I may perhaps be misunderstanding what you're saying about "my
> solution"...?

I hope I clarified what I meant.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie wxPython ListCtrl Question

2005-11-16 Thread limodou
2005/11/17, Todd7 <[EMAIL PROTECTED]>:
> I am new to python and to wxWindows.  I have tried searching google,
> reading the documentation and trying to figure out some of the examples,
> but I am stumped as to how to get information out of a listctrl at a
> certain row and column.  I tried to write a simple example to learn to
> work with the listctrl as follows:

I'v made some helper function as that:

def getRowText(self, index, col):
if index >= 0:
return self.list_ctrl_1.GetItem(index, col).GetText()
else:
return ''

def getSelRowText(self, col):
return self.getRowText(self.getSelection(), col)

def getSelection(self):
return self.list_ctrl_1.GetNextItem(-1, wx.LIST_NEXT_ALL,
wx.LIST_STATE_SELECTED)

You can just use self.getSelRowText(1) to gain the second column text
of selection row.
--
I like python!
My Blog: http://www.donews.net/limodou
NewEdit Maillist: http://groups.google.com/group/NewEdit
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-16 Thread The Eternal Squire
Standard libraries are usually paid for by the implementor of the
language, so this is not an issue.

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


Re: Proposal for adding symbols within Python

2005-11-16 Thread Steven Bethard
Pierre Barbier de Reuille wrote:
> Proposal
> 
> 
> First, I think it would be best to have a syntax to represent symbols.
> Adding some special char before the name is probably a good way to
> achieve that : $open, $close, ... are $ymbols.

How about using the prefix "symbol." instead of "$"?

 >>> symbol.x
symbol.x
 >>> symbol.y
symbol.y
 >>> x = symbol.x
 >>> x == symbol.x
True
 >>> x == symbol.y
False
 >>> symbol.file.opened
symbol.file.opened
 >>> symbol.file.closed
symbol.file.closed
 >>> symbol.spam(symbol.eggs)
symbol.spam(symbol.eggs)

And the definition of symbol that I used:

 >>> class symbol(object):
... class __metaclass__(type):
... def __getattr__(cls, name):
... return symbol(name)
... def __getattr__(self, name):
... return symbol('%s.%s' % (self.name, name))
... def __init__(self, name):
... self.name = name
... def __eq__(self, other):
... return self.name == other.name
... def __repr__(self):
... return '%s.%s' % (type(self).__name__, self.name)
... def __call__(self, *args):
... arg_str = ', '.join(str(arg) for arg in args)
... return symbol('%s(%s)' % (self.name, arg_str))
...

It doesn't work with "is", but otherwise I think it's pretty close to 
your proposal, syntax-wise.  Is there something obvious this won't 
address for you?

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


Re: Python obfuscation

2005-11-16 Thread Alex Martelli
Mike Meyer <[EMAIL PROTECTED]> wrote:

> Alex's solution doesn't require special treatment for disaster
> recovery and/or planning, and as such is a valid answer to the

I'm not sure I understand this.  I would assume that any software (or,
for that matter, data) of any substantial importance, worthy of being
deployed on a server, does include disaster planning (and recovery
plans, in particular) as a routine part of server-side deployment
(regular backups with copies off-site, etc etc).

Of course, server side deployment DOES make it considerably easier to
enjoy such crucial services, compared with client side deployment; but I
had not addressed such issues at all in my original posts on this thread
(in terms of "IP protection", a "fat client" with data kept client-side
might be just as suitable as a "thin client" for server-side
deployment... but it would be just as vulnerable as a wholly client-side
deployment to issues of [lack of] disaster planning etc).

So, I may perhaps be misunderstanding what you're saying about "my
solution"...?


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


Re: Python obfuscation

2005-11-16 Thread Alex Martelli
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> On Wed, 16 Nov 2005 13:51:35 +, Ed Jensen wrote:
> 
> > Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> >> I'm not sure if that is meant to be a rhetorical 
> >> question or not, but something of the order of 95% of 
> >> all software written is never distributed to others, 
> >> and so copyright or the lack of copyright is not an issue.
> > 
> > Can you cite your source(s) for this information?
> 
> Not easily, but I will try.
> 
> If it helps, I will clarify what I was talking about -- in hindsight it is
> a little unclear. Most software written (I think about 95%) is by
> companies for in-house use only. Since it never gets distributed outside
> of the company using it, copyright is of little additional value.

Hmmm, I thought the original "95%" (which I think I remember from
something ESR wrote, but can't pin down what) applied to a wider
category matching your former description: 95% of all software written
is never distributed to others, _either_ because it was never meant to
be, _or_ because the development project failed disastrously (after some
code got written but before it got deployed, i.e., distributed), as so
many projects in the SW industry do (at various stages of the
development process).


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


Re: best way to discover this process's current memory usage, cross-platform?

2005-11-16 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
   ...
> Neal  Norwitz wrote:
> > Here's a really screwy thought that I think should be portable to all
> > Unixes which have dynamic linking.  LD_PRELOAD.
> >
> > You can create your own version of malloc (and friends) and free.  You
> > intercept each call to malloc and free (by making use of LD_PRELOAD),
> > keep track of the info (pointers and size) and pass the call along to
> > the real malloc/free.  You then have all information you should need.
> 
> That'll only get you memory usage from malloc/free calls, which could
> be vastly less than the process' memory usage in plausible scenarios
> (e.g. a media player that uses mmap() to read the file, or anything
> that uses large shared memory segments generated with mmap() or SysV
> IPC, etc).

True.  But hopefully a cross-platform program's memory leaks will mostly
be based on malloc (it couldn't use SysV's IPC and still be
cross-platform, for example; and while mmap might be a possibility,
perhaps it might be tracked by a similar trick as malloc might).


> In the real world, malloc() and mmap() are probably sufficient to get a
> good picture of process usage for most processes.  But I guess defining
> exactly what counts as the process' current memory would be a starting
> place (specifically how to deal with shared memory).

Considering that the main purpose is adding regression tests to confirm
that a hopefully-fixed memory leak does not recur, I'm not sure why
shared memory should be a problem.  What scenarios would "leak shared
memory"?  If some shared library gets loaded once and stays in memory
that doesn't appear to me as something that would normally be called "a
memory leak" -- unless I'm failing to see some cross-platform scenario
that would erroneously re-load the same library over and over again,
taking up growing amounts of shared memory with time?


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


Re: Python obfuscation

2005-11-16 Thread The Eternal Squire
Plenty of case law exists behind judgements made to repair loss of
sales opportunites... these are called infringement upon sales
territories..

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


python-dev Summary for 2005-09-01 to 2005-09-15

2005-11-16 Thread Tony Meyer
[Note: yes, this is *September*!  All my (Tony's) bad, Steve has been  
chugging away at the summaries like he should have.  Extra apologies  
for this one - it was approved by python-dev a while back, and I  
didn't realise that I hadn't done the python-list post.]

python-dev Summary for 2005-09-01 through 2005-09-15


.. contents::

[The HTML version of this Summary is available at
http://www.python.org/dev/summary/2005-09-01_2005-09-15.html]



=
Announcements
=

-
QOTF: Quotes of the Fortnight
-

In the thread on the print statement, Charles Cazabon provided some  
nice imagery for Guido's Python 3.0 strategy.  Our first QOTF is his  
comment about the print statement:

 It's an anomaly.  It stands out in the language as a sore thumb  
waiting for Guido's hammer.

We also learned something important about the evolution of Python  
thanks to Paul Moore.  In the thread on the Python 3.0 executable  
name, Greg Ewing worried that if the Python 3.0 executable is named  
"py":

 Python 4.0 is going to just be called "p", and by the time we  
get to Python 5.0, the name will have vanished altogether!

Fortunately, as Paul Moore explains in our second QOTF, these naming  
conventions are exactly as we should expect them:

 That's OK, by the time Python 5.0 comes out, it will have taken  
over the world and be the default language for everything. So  
omitting the name is exactly right :-)

[SJB]

Contributing threads:

- `Replacement for print in Python 3.0 `__
- `Python 3 executable name `__

--
The "Swiss Army Knife (...Not)" API design pattern
--

This fortnight saw a number of different discussions on what Guido's  
guiding principles are in making design decisions about Python. Guido  
introduced the "Swiss Army Knife (...Not)" API design pattern, which  
has been lauded by some as `the long-lost 20th principle from the Zen  
of Python`_. A direct quote from Guido:

 [I]nstead of a single "swiss-army-knife" function with various  
options that choose different behavior variants, it's better to have  
different dedicated functions for each of the major functionality types.

This principle is the basis for pairs like str.split() and str.rsplit 
() or str.find() and str.rfind().  The goal is to keep cognitive  
overhead down by associating with each use case a single function  
with a minimal number of parameters.

[SJB]

.. _the long-lost 20th principle from the Zen of Python: http:// 
mail.python.org/pipermail/python-dev/2005-September/056228.html

Contributing threads:

- `Replacement for print in Python 3.0 `__
- `Replacement for print in Python 3.0 `__


A Python-to-C++ compiler


Mark Dufour announced `Shed Skin`_, an experimental Python-to-C++  
compiler, which can convert many Python programs into optimized C++  
code, using static type inference techniques.  It works best for  
Python programs written in a relatively static C++-style; much work  
remains to be done, and Mark would like anyone interested in getting  
involved to contact him.  Shed Skin was one of the recent `Google`_  
`Summer of Code`_ projects.
.. _Shed Skin: http://shedskin.sourceforge.net
.. _Google: http://www.google.com
.. _Summer of Code: http://code.google.com/summerofcode.html

[TAM]

Contributing thread:

- `First release of Shed Skin, a Python-to-C++ compiler. `__

--
python-checkins followups now stay on the python-checkins list
--

In a follow-up to a `thread in early July`_, the python-checkins  
mailing list Reply-To header munging has been turned off.   
Previously, follow-ups to python-checkins would be addressed to  
python-dev; now, follow-ups will stay on the python-checkins list by  
default.

.. _thread in early July: http://www.python.org/dev/summary/ 
2005-07-01_2005-07-15.html#behavior-of-sourceforge-when-replying-to- 
python-checkins

[TAM]

Contributing thread:

- `python-checkins reply-to `__


=
Summaries
=


Converting print to a function in Python 3.0


In Python 3.0, Guido wants to change print from a statement to a  
function.  Some of his motivation for this change:

* Converting code that uses the print statement to instead use 

Re: newbie - How do I import automatically?

2005-11-16 Thread Steve M
The file C:\Python24\Lib\sitecustomize.py (which I think doesn't exist
by default) executes every time Python starts. (This means not just
your IDLE session but every time you run any Python script.)

One use for this file is to invoke sys.setdefaultencoding because that
name gets deleted during initialization and so is unavailable by the
time your main script starts executing.

You can also put in any other code, such as "from btools import *".

You can also put your btools.py file in C:\Python24\Lib\site-packages
folder and it will be available from any program (as opposed to
requiring it in the current directory).

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


Re: running functions

2005-11-16 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Grant Edwards  <[EMAIL PROTECTED]> wrote:
>On 2005-11-16, Gorlon the Impossible <[EMAIL PROTECTED]> wrote:
>
>> I'm not sure how to phrase this question. I have a Python function
>> that sends MIDI messages to a synth. When I run it, I of course have
>> to wait until it is finished before I can do anything else with
>> Python. Is it possible to run this function and still be able to do
>> other things with Python while it is running?
>
>Yes.
>
>> Is that what threading is about?
>
>Exactly.  Take a look at the "treading" module:
>
>http://www.python.org/doc/current/lib/module-threading.html
.
.
.
I don't agree, Grant (although I salute the brevity
of your follow-up), and a couple of other correspon-
dents have already posted follow-ups that begin to
explore the alternatives.

If I were pursuing this, the first question I'd have
for Gorlon is whether he's OK with a "fire and for-
get" model.  By that, I mean to ask if it's OK to
send the MIDI message, and then return immediately
to other Python work, OR whether Gorlon also needs
to stay in contact with the MIDI handler, and
perhaps react especially when the MIDI handler
finishes with the specific message.  That choice is
crucial in a good concurrency design.

So, Gorlon, yes, threading is a prominent member of
the family of facilities that address situations like
yours.  It's not the only one, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs Ruby

2005-11-16 Thread bellarchitects

bruno modulix wrote:
>
> It's been a long time since I last saw a Java applet on a website.
>

That can only mean you are ignorant.
Applets are a huge deal for Intranets. And Java Web Start is even more
useful. I really wish Python had such wonderful means of deployment.

bruno modulix wrote
>  Err... I wouldn't start another HolyWar, but Java is not that Object
> Oriented. 'Class-based' would be more appropriate. Python, while not
> being class-based (ie: it doesn't impose that all code goes into a
> 'class' statement), is much more an OO language than Java, since in
> Python *everything* is an object - even functions, classes and modules.
> This makes a *big* difference.

I think you are confusing terms. Class-based means that the language
uses classes and class inheritance and not object prototyping (as in
javascript):
http://en.wikipedia.org/wiki/Object_oriented#Prototype-based_models

And why should functions be objects ? Actually, this makes it less OOP
if we consider Smaltalk as being true OOP ;)
Python is here more pragmatic but less OOP, please try to remember it.

And haven't you heard of java.lang.Class or java.lang.reflect.Method ?
Classes in Java *ARE* objects. Or do you think all those static methods
and properties just pop out of the ground ? Voodoo maybe ? :)

The reason classes don't behave as objects is because that's only
usefull for reflection and meta-programming and that can be achieved by
using the java.lang.reflect package which IMHO it really makes sense
the way it was implemented.

bruno modulix wrote
> Err... Python is more like what Java would have been if Java was a smart
> dynamic hi-level object oriented language !-)

You see, I rarely see this kind of rubish on comp.lang.ruby. Shame on
you.
Do you realy think you are doing the Python community a favor by
bashing Java ?


And yeah, LOC count is stupid. Productivity in general measured in LOC
is stupid. For that Java has a simple syntax which anyone can learn in
only a few hours (simpler than Python's ... a lot imho) and tools like
Eclipse, Netbeans, Studio Creator, JBuilder, etc ...


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


Re: strange file.write() behavior on windows: $ConvertToNonresident, $ReplaceAttribute2

2005-11-16 Thread jepler
This is really just a snide joke at the expense of Microsoft, but have you
checked the MSDN documentation about ConvertToNonresident or ReplaceAttribute2?

Your search - site:msdn.microsoft.com ConvertToNonresident OR
ReplaceAttribute2 - did not match any documents. 
-- google.com

Internally, Python also simply calls fwrite().  Are you using the same C
runtime for both sets of tests?

Jeff


pgpbAHQzcNQfx.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: JMS yet again

2005-11-16 Thread Mike Meyer
Ben Finney <[EMAIL PROTECTED]> writes:

> Aahz <[EMAIL PROTECTED]> wrote:
>> Am I the only person who immediately thought of Babylon 5 and
>> wondered if I was in the wrong newsgroup?
>
> I plead guilty.

Well, I thought of Crusade. But I'd just finished watching those.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


strange file.write() behavior on windows: $ConvertToNonresident, $ReplaceAttribute2

2005-11-16 Thread welch
while taking some rough disk performance measures on windows machines,
and snooping with FileMon, i've noticed some odd behavior

here's the little nul-writer i'm running:
def writeTest(nBlocks, blockSize):
"""write nBlocks*blockSize nuls to a file"""
f = open("writeTest.out", "wb")
nulBlock = '\0'*blockSize
while nBlocks:
f.write(nulBlock)
nBlocks -= 1
f.close()

when i invoke this with a blockSize of 64K or less, no surprises.
here's a row of FileMon output for the 64K block size:
2:44:48 PM python.exe:3064 WRITE C:\writeTest.out SUCCESS Offset:
214106112 Length: 65536

when i invoke this with larger blocksizes (say, 655360), FileMon output
looks like this:
2:37:46 PM python.exe:3064 WRITE  C:\writeTest.out  Offset: 140902400
Length: 655360
2:37:46 PM python.exe:3064 WRITE  C:\$ReplaceAttribute2 SUCCESS Offset:
140902400 Length: 65536
...(the $ReplaceAttribute2 line repeats several times, writing 65536
and advancing the offset by 65536 each time)

sometimes, depending on the phase of the moon, instead of
$ReplaceAttribute2 the write goes to $ConvertToNonresident. within a
single run of writeTest the write always goes to the same one,
whichever one that is. these runs are always slower (sometimes greatly)
than writing the same with 64K blocks, even though many fewer
file.write()'s are being issued because of the larger block size.

finally, where you'd expect an even 10 of the WRITE
C:\$ReplaceAttribute2 lines per WRITE C:\writeTest.out lines in the
example above, instead FileMon reports 8 lines for the first, 6 for the
second, 8 for the third, 6 for the fourth, etc... i've no idea if this
means FileMon is missing messages, but this pattern is absolutely
consistent across every run i've made, on both xp and win2k3 server
machines.

a look at the python fileobject.c source shed no light for me, anyone
know what could be going on? the "equivalent" c version of writeTest
using fwrite() shows a succession of 1K blocks writing to the named
file (even when fwrite is given 64K blocks), and no mysterious
$ReplaceAttribute2 lines

-- w

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


Re: subprocess terminate help

2005-11-16 Thread Fredrik Lundh
Ernesto wrote

> program.exe ?  I was looking at the Windows task manager after I used a
> Cntrl + C to manually terminate the running python program.  The
> program.exe is apparently ending when I end the python program.

I have to admit that I have no idea what you're doing, really.  The code
you used *explicitly* waits for the "program.exe" program to finish.  If
you don't want that, why are you telling the subprocess module to wait?
If you do want it to wait, why are you killing the python process ?

 



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


Auto Install Linux Rpm's

2005-11-16 Thread Sells, Fred
We would like to use Python to automatically deploy new rpm's (assuming we
first edit a file to require a new version).  I've just starting looking a
the rpm module.  I can build this from scratch, but was wondering if anyone
is/has solved some or all of this problem or could point me to some
"goodies" that would help.  

tia

Fred

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: HTML generation vs PSP vs Templating Engines

2005-11-16 Thread Sells, Fred
If this is your first try, use cgi, cgitb and html % dictionary as suggested
in this thread.  If your db is mysql, you can actually use os.popen() (or
equivalent) to run a  'mysql -html -e "select * from yaddayadda" to return
html.  you can make that look prettier with css.
here's a quick and dirty I just did.
===snip=
===
#!/usr/bin/python
import os, string, sys, time, cgi, cgitb
cgitb.enable(display=1)
import ezcgi
HTML = """

   table {cell-padding:2; cell-spacing:2; font-family:Arial;}
   th { background-color: lightblue; cell-padding:5; cell-spacing:5;}
   td { background-color: lightgray; padding:5; spacing:5;
font-size:mediumm;}

Snapshot of Administrative Bed Holds



Current Administrative Bed Holds at all
Facilities
%s

%s

Copyright (C) 1996-2005, Adventist Care Centers, Inc.  For Internal Use
Only
http://acc.sunbelt.org";>Home|
http://acc.sunbelt.org/rwb?P001=logout";>Logout
"""

COMMAND = ['mysql --host=acaredb --user=acare --password=acare -D census -H
-e ', 
   '"SELECT facility,wrb Room,description Reason,startdate, note
Explanation',
   'FROM admin_bed_holds h, abhreasons r '
   'WHERE h.reason=r.id   ',
   ' ORDER BY facility;"']
COMMAND = ' '.join(COMMAND)

def select_holds():
x = os.popen(COMMAND)
table = x.read(6000)
return HTML % ('', table)

def execute():
if ezcgi.is_authenticated():
print ezcgi.HTML_CONTENT_TYPE
print select_holds()
else: 
ezcgi.authenticate_user()

if __name__=='__main__':
#print ezcgi.PLAIN_CONTENT_TYPE
#print COMMAND
execute()
===snip=
=
-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]
Sent: Wednesday, November 16, 2005 11:32 AM
To: python-list@python.org
Subject: HTML generation vs PSP vs Templating Engines


Hello everybody,

I am in the process of writing my very first web application in Python,
and I need a way to
generate dynamic HTML pages with data from a database.  I have to say I
am overwhelmed
by the plethora of different frameworks, templating engines, HTML
generation tools etc that
exist. After some thought I decided to leave the various frameworks
aside for the
time being and use mod_python.publisher along with some means of
generating HTML on
the fly.
Could someone that has used all the different ways mentioned above for
dynamic HTML
content, suggest what the pros and cons of the different methods are?

  Thank you very much in advance

  Panos

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

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTML generation vs PSP vs Templating Engines

2005-11-16 Thread thakadu
I just do the following:

I store the form data as a pickeled dictionary. Then I create my
HTML form with something like this:

HTMLout="""..
..


'''

where the field1, field2 etc era the fields on my form.

Then finally:

print HTMLout % dict

where dict has all the values that I previously pickled.
You have to do some additional trickery for  type fields
and checkboxes and so on but its really not difficult.

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


Re: Python, Linux, Desktop Environment

2005-11-16 Thread Lee Harr
On 2005-11-16, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> So, I've written my first GUI app in python.  I've turned it into a
> binary .exe and .app that runs on Windows and Mac respectively, but on
> my Linux box, where I wrote the thing, I still have to drop to the
> command line and ./myscript.py.  What can I do to make it a "click and
> run" sort of application in KDE or Gnome on Linux?
>


Have you heard of a "shebang line"?

That is when the first line of a file starts with #!

You probably want ...

#!/usr/bin/env python


That will run the commandline from that first line.
Remember, it must be the very first thing (no spaces).


You may also need to be in a particular directory in
order to access program resources. I usually end up
making a little .sh script like ...

#!/bin/sh

cd /my/python/prog/dir && python myprog.py



Most of the recent window managers are using the
so called .desktop files. You could copy one of
those from another program (try creating a "link
to application" or an "application launcher" on
your desktop).

I think most wms will also just run your shell
script if the permissions are set correctly.

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


Re: Python obfuscation

2005-11-16 Thread Mike Meyer
"The Eternal Squire" <[EMAIL PROTECTED]> writes:
> A fair request.   The teaching of legality and ethics of incorporating
> other peoples' works into one's own should begin at 6th grade and be
> repeated every year until the message is driven home.

Right. You want to teach potential programmers that they should make a
checking the standard libraries and network library repositories for
libraries that can, if incorporated into their work, would make
finishing the product at hand that much easire. You wannt to teadh
them that this is not long legal and ethical, but smart.

I assume that other professions have similar tools/etc. available.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess terminate help

2005-11-16 Thread Ernesto
program.exe ?  I was looking at the Windows task manager after I used a
Cntrl + C to manually terminate the running python program.  The
program.exe is apparently ending when I end the python program.

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


Re: JMS yet again

2005-11-16 Thread Ben Finney
Aahz <[EMAIL PROTECTED]> wrote:
> Am I the only person who immediately thought of Babylon 5 and
> wondered if I was in the wrong newsgroup?

I plead guilty.

-- 
 \  "I like to reminisce with people I don't know. Granted, it |
  `\  takes longer."  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTML generation vs PSP vs Templating Engines

2005-11-16 Thread Damjan
> After some thought I decided to leave the various frameworks
> aside for the time being and use mod_python.publisher along with some
> means of generating HTML on the fly.

I kind of like KID templates the most, you can easyly work with them in any
HTML authoring software, they are easy to use (prety much pythonic).


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


Re: Python obfuscation

2005-11-16 Thread Ben Finney
The Eternal Squire <[EMAIL PROTECTED]> wrote:
> Ben Finney wrote:
> >Ethics such as sharing, and helping one's neighbour?
> 
> Giving away an illegal copy of software it not helping one's
> neighbor, it is making that neighbor an accessory to copyright
> infringement, a federal offense punishable not in excess of 10 years
> of $10K.

So the law is the guide to ethical behaviour? Sure you don't have that
reversed?

-- 
 \ "Unix is an operating system, OS/2 is half an operating system, |
  `\   Windows is a shell, and DOS is a boot partition virus."  -- |
_o__)  Peter H. Coffin |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: path module / class

2005-11-16 Thread Neil Hodgson
Chris:

> What is the status of the path module/class PEP?  Did somebody start
> writing one, or did it die?  I would really like to see something like
> Jason Orendorff's path class make its way into the python standard
> library.

There is no PEP yet but there is a wiki page.
http://wiki.python.org/moin/PathClass
Guido was unenthusiastic so a good step would be to produce some 
compelling examples.

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


Python driver for lpsolve

2005-11-16 Thread Peter Notebaert
 lp_solve is a Mixed Integer Linear Programming (MILP) solver (see 
http://lpsolve.sourceforge.net/5.5/).

There is now a Python driver to lpsolve. See 
http://lpsolve.sourceforge.net/5.5/Python.htm for more information about 
this driver.

Peter 


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


Re: Python obfuscation

2005-11-16 Thread Ben Finney
The Eternal Squire <[EMAIL PROTECTED]> wrote:
> >The legality of copying, modifying and redistributing works should be
> >reformed until it matches a 6th grader's intuitions about sharing.
> 
> A 6th grader also has intuitions regarding the ownership of an idea.
> "It was MY idea!!!"  "No, it's NOT!!!"  "Is TOO!!!"

And what should we teach those children?

"Now children, it can be an idea you *both* have, and you both get the
benefit. Learn to share."

Or, do we instead teach them:

"Excellent children! Keep on fighting over who owns ideas, and never
share them. That's the sort of society we want you to live in."

The more you try to teach them to stop sharing, the more we'll teach
them to share. Keep your propaganda about "sharing == evil" away from
children.

-- 
 \ "Those are my principles. If you don't like them I have |
  `\ others."  -- Groucho Marx |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is parameter an iterable?

2005-11-16 Thread Roy Smith
Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
># Create an instance of the exception you expect:
>try:
>for i in 0:
>pass
>except TypeError, ITER_OVER_NON_SEQ:
>pass
># Now run your code...
>try:
>...blah blah blah...
>except TypeError, msg
>if str(msg) == str(ITER_OVER_NON_SEQ):
>...blah blah blah... 
>
>This means we're no longer assuming what the error message will be,
>which makes our code a lot more future-proof and implementation-proof: if
>some version of Python changes the error string from "iteration over
>non-sequence" to something else, the code should continue to work
>correctly.

Now you're assuming that the message is a constant for all TypeErrors
caused by attempting to iterate over a non-iterable object.  I don't
see anything in the docs which prevents

try:
  for i in 0:
pass
except TypeError, ex:
  print ex

from printing "Cannot iterate over integer with value 0", or even
"Cannot iteratate over object at address <0x456778>".  Let's not even
talk about some future implementor who decides that the strings should
contain timestamps.  None of these things are forbidden by the spec,
therefore you should assume they will all happen.

The best solution I've seen suggested so far is to coerce the
passed-in object to an iter and see what happens:

try:
  thingieIterator = iter (thingie)
except TypeError:
  raise NonIterableThingieError

Once you've done that, I think you can either do:

for item in thingie:

or

for item in thingieIterator:

with equal effect.  And I'm reasonably sure this will work fine with
non-idempotent thingies.
-- 
http://mail.python.org/mailman/listinfo/python-list


python-mysqldb__debian_to_freebsd

2005-11-16 Thread Cousin Stanley

Greetings 

  I'm using a commercial web host running FreeBSD
  that fortunately has Python and MySQL,
  but no  python-mysqldb  module  

  Before begging the host to install it
  I thought I would try the Debian version
  that I have on the outside chance 
  that it  might  fly directly under FreeBSD 
  on the server  

  import MySQLdb  leads to the ImportError message 

  Shared object "libpthread.so.0" not found, 
 required by "_mysql.so"

  On my local Debian installation the reference
  to that particular library file is actually 
  a symbolic link 

 libpthread.so.0 -> libpthread-0.10.so 

  I copied  libpthread-0.10.so  over to the server
  in a directory that is in the Python search path
  and renamed it to libpthread.so.0  

  I tried to make the symbolic link as above
  from Python since I don't have a shell account,
  but it failed for some reason that I don't recall
  at the moment 

  After a bit of google-izing and a quick scan
  of the MySQL install docs, I also set
  the  LD_LIBRARY_PATH  enviroment variable
  to point to the dir where the supposed missing 
  file lives  

  Is there any at all chance that this will work 
  with the proper configs or should I go ahead 
  and beg the host for an installation ?

  Any clues would be greatly appreciated 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JMS yet again

2005-11-16 Thread Aahz
In article <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> [...]

Am I the only person who immediately thought of Babylon 5 and wondered if
I was in the wrong newsgroup?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is parameter an iterable?

2005-11-16 Thread Bengt Richter
On Wed, 16 Nov 2005 17:39:57 +0100, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:

>Rick Wotnaz wrote.
>
>> ... which leads me to belive that 'msg' is not type(str). It can be
>> coerced (str(msg).find works as expected). But what exactly is msg?
>> It appears to be of , and does not test equal to a
>> string.
>
>it's an instance of the exception type, of course.
>
>:::
>
>if you do
>
>raise SomeError, value
>
>Python will actually do
>
>raise SomeError(value)

Depending on what you mean by "actually" I guess ...
(I'm sure you know this and more ;-)

 >>> dis.dis(compile('raise SomeError, value','','exec'))
   1   0 LOAD_NAME0 (SomeError)
   3 LOAD_NAME1 (value)
   6 RAISE_VARARGS2
   9 LOAD_CONST   0 (None)
  12 RETURN_VALUE
 >>> dis.dis(compile('raise SomeError(value)','','exec'))
   1   0 LOAD_NAME0 (SomeError)
   3 LOAD_NAME1 (value)
   6 CALL_FUNCTION1
   9 RAISE_VARARGS1
  12 LOAD_CONST   0 (None)
  15 RETURN_VALUE

I guess that comes from the grammar of the raise statement, i.e.,

raise_stmt: 'raise' [test [',' test [',' test]]]

which allows up to three arguments for raise, apparently all general
expressions, but  with some specific run-time requirements for what
combinations of argument expression values are allowable.

I.e., it seems (I haven't looked in ceval.c(?)) that RAISE_VARARGS must
look at the first item in its count of args on the stack, and in the
SomeError, value case find an exception class, and decide to instantiate it
and throw the instance, but if it finds the instance ready made, as in
SomeError(value), it must skip the instantiation (and disallow further args 
BTW).

 >>> raise Exception, 'arg'
 Traceback (most recent call last):
   File "", line 1, in ?
 Exception: arg
 >>> raise Exception('arg')
 Traceback (most recent call last):
   File "", line 1, in ?
 Exception: arg

Those looks the same, but sensitivity to the type of the first arg is revealed 
by

 >>> raise Exception('arg'), 'what now?'
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: instance exception may not have a separate value

 >>> raise Exception('arg', 'what now?')
 Traceback (most recent call last):
   File "", line 1, in ?
 Exception: ('arg', 'what now?')


>
>(that is, create a SomeError exception and pass the value as its
>first argument).
>
>you can use either form in your code (I prefer the latter myself).
>
Just to drive home the general expression allowability in raise,
and instance vs class as the first arg:

 >>> extab = [StopIteration('stop stop ;-)'), ValueError('wrong value')]

 >>> raise extab[1]
 Traceback (most recent call last):
   File "", line 1, in ?
 ValueError: wrong value

 >>> raise extab[0]
 Traceback (most recent call last):
   File "", line 1, in ?
 StopIteration: stop stop ;-)

 >>> extab = [StopIteration, 'stop stop ;-)', ValueError, 'wrong value']

 >>> raise extab[2], extab[3]
 Traceback (most recent call last):
   File "", line 1, in ?
 ValueError: wrong value

 >>> raise extab[0], extab[1]
 Traceback (most recent call last):
   File "", line 1, in ?
 StopIteration: stop stop ;-)

Ok, I'll stop ;-)

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


Re: is parameter an iterable?

2005-11-16 Thread Fredrik Lundh
> Alex has already posted the right way to do this.  can you please stop

posting crappy non-solutions to a problem that has a very simple solution (split
things up), that should be obvious to anyone who didn't sleep through exceptions
101.

 



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


Re: Newb ?

2005-11-16 Thread Chad Everett
Hey guys,

Thanks for the hint.
I found that info last night but I could never get it to print more than 
just the last letter.
or it would only print partially.
I was using just a single colon,  the double colon did it.

Thanks

"Chad Everett" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello all,
>
> Have a problem here with a challenge from a book I am reading.
> Any help is much appreciated.
>
> I am trying to run a program that asks the user for a statement and then 
> prints it out backwards.
> this is what I have.
> It does not print anything out.  I assume that I have something out of 
> whack with my high and low statements.
>
> Thanks for you help.
>
>
> print "\n\nWelcome to the Backwards Message Display."
> print
> message = raw_input("\nPlease Enter a Message.")
>
> high = len(message)
> low = -len(message)
> print
> print message[high:low]
> print
> print raw_input("Please Press Enter to Exit")
> 


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


Re: subprocess terminate help

2005-11-16 Thread Ernesto
A... I figured out a way around this.  I'll use program.exe to shut
down itself.  That way I won't have to use any extension modules.

Thanks!

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


Re: Python obfuscation

2005-11-16 Thread Steven D'Aprano
On Wed, 16 Nov 2005 14:00:16 -0800, The Eternal Squire wrote:

>>The legality of copying, modifying and redistributing works should be
>>reformed until it matches a 6th grader's intuitions about sharing.
> 
> A 6th grader also has intuitions regarding the ownership of an idea.
> "It was MY idea!!!"  "No, it's NOT!!!"  "Is TOO!!!"


That's what happens when you try to teach 6th graders about intellectual
property: they revert back to two year old mentality.


-- 
Steven.

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


Re: running functions

2005-11-16 Thread [EMAIL PROTECTED]
Gorlon the Impossible wrote:
> Hello
> I'm not sure how to phrase this question. I have a Python function
> that sends MIDI messages to a synth. When I run it, I of course have
> to wait until it is finished before I can do anything else with
> Python. Is it possible to run this function and still be able to do
> other things with Python while it is running? Is that what threading
> is about?

Threading's a good answer if you really need to share all your memory.
A multiprocess solution is probably preferrable, though it depends on
the architecture.

It may be possible to do it in a single process (if, say, the MIDI
synth supports waitForMultipleObjects, select, async I/O, or an
equivalent thereof) without blocking.

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


Re: Python obfuscation

2005-11-16 Thread Steven D'Aprano
On Wed, 16 Nov 2005 13:25:50 -0800, The Eternal Squire wrote:

> The teaching of legality and ethics of incorporating
> other peoples' works into one's own should begin at 6th grade and be
> repeated every year until the message is driven home.

I think you have that completely backwards.

Sixth graders have an intuitive understanding of the economics and
morality of using "things" that adults these days rarely have.

Material things, objects, are scarce resources and cannot be taken with
impunity. If I take your black crayon, then you have one less black crayon.

Non-material things, ideas, are not scarce resources. If I take your idea
of writing programs in a high-level language like Python instead of using
machine code, you still have the idea and we are both better off.



> The concept of intellectual property (patent, copyright, trade secret)
> is an extension into the business world of issues regarding the proper
> usage of ideas (e.g. scientific principles) as treated in high school
> and college.

Nonsense. Patents, copyrights and trade secrets are completely and utterly
opposed to proper scientific principles. Alchemists and magicians tried to
monopolise their knowledge. Scientists share. The proliferation of patents
in the medical industry is *hurting*, not helping, medical research:
scientists are reluctant to publish knowledge, or are prohibited by their
employer, and the cost of doing basic research is sky-rocketing due to the
need to pay licence fees.

This is especially obscene when one realises that in the US 80% of the
scientific research that gets patented by private companies is paid for by
tax payer dollars. Your taxes pay for the science which then gets given on
a silver platter to some private company who collects monopoly rents on
that knowledge for 20 years. It is a nice scam if you can get away with
it, and the pharmaceutical companies have got away with it.


>>Do developers, when writing code consider how protected their
>>code will be when considering what language they will write it in
>>i.e ease of use, speed of language, maintainability and
>>'obfuscatability' ?
> 
> Typically not due to a few well-known principles:  1) Essentially an
> optimized (not debug!) compilation from source code to machine language
> is nearly as good as encryption for hindering reverse engineering of
> the distributed code,  

That is utterly wrong. Reverse engineering of even optimized code is
relatively easy. That is one of the big myths that plague the IT industry:
"if I don't release the source code, nobody will be able to work out how
my code works". 

It just doesn't work that way. Just ask the people working on the WINE
project, who have a working, almost complete, bug-for-bug compatible
reverse-engineered Windows emulator, and they've done it in their spare
time.

Or ask the virus writers, who often find bugs and buffer over-flows and
other security holes in software before the guys with the source code find
them.

Reverse engineering object code is harder than reading source, but it is
still not a barrier to anyone serious about working out how your code
works.



[snip]
> The greatest theft of sales opportunities 

Listen to yourself. "The greatest theft of SALES OPPORTUNITIES". What is
that supposed to mean? Not theft of goods, not even theft of ideas, but
the theft of an opportunity to make a sale?

"I might have been able to sell to that person, but now I can't, it's YOUR
FAULT... I'm going to sue!!!"

The greatest "theft" of sales opportunities is COMPETITION, not copying.
If every food store and restaurant in the country shut down except
McDonalds, then they would have all the sales opportunities anyone would
ever want. Every store that competes with them is "stealing" the
opportunity to make a sale.

We've already seen this way of thinking. Listen to Jamie Kellner, chairman
and CEO of Turner Broadcasting System:

"Any time you skip a commercial you're actually stealing the programming."

Listen to the arrogance: "I guess there's a certain amount of tolerance
for going to the bathroom." We need a permission slip from the television
stations to go to the toilet? Heaven forbid we turn the machine off,
that's theft of sales opportunities.

Perhaps somebody should remind these folks, we're not the customer. We're
the product they are selling: they sell our eyeballs to advertisers, who
give them money for the opportunity to be seen by us. If we choose to
skip the commercials, that's just too bad for Jamie Kellner's business
model.



> Ourselves
> and our children are lost generations with respect to ethics, manners,
> and respect for authority, perhaps we can train our grandchildren to
> behave more proprely.

There is too much respect for so-called "authority", not too little.
Respect for authority is just another way of saying "Don't think for
yourself, do as you're told."


-- 
Steven.

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


Re: Shutdown hook

2005-11-16 Thread Steve Juranich
On 15 Nov 2005 14:45:27 -0800, Steve <[EMAIL PROTECTED]> wrote:
> Does any one know if python has the ability to run a shutdown hook.

Look at the "atexit" module.

barbet (~)$ pydoc atexit.register
Help on function register in atexit:

atexit.register = register(func, *targs, **kargs)
register a function to be executed upon normal program termination

func - function to be called at exit
targs - optional arguments to pass to func
kargs - optional keyword arguments to pass to func
--
Steve Juranich
Tucson, AZ
USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: path module / class

2005-11-16 Thread Dennis Benzinger
[EMAIL PROTECTED] schrieb:
> [...]
> What is the status of the path module/class PEP?  Did somebody start
> writing one, or did it die?  

I didn't find one at the PEP index , so I 
assume that nobody wrote or submitted one.

> I would really like to see something like
> Jason Orendorff's path class make its way into the python standard
> library.
> [...]

If you think having such a class in the standard library is that 
important then you should write a PEP by yourself...


Bye,
Dennis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is parameter an iterable?

2005-11-16 Thread Fredrik Lundh
Steven D'Aprano wrote:

> This means we're no longer assuming what the error message will be,
> which makes our code a lot more future-proof and implementation-proof: if
> some version of Python changes the error string from "iteration over
> non-sequence" to something else, the code should continue to work
> correctly.

Alex has already posted the right way to do this.  can you please stop

 



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


Re: Python obfuscation

2005-11-16 Thread The Eternal Squire
>Utter poppycock. Who is to say that a particular entity holds an
>exclusive "sales opportunity" to a particular individual? Are we to
>protect the expectations of profit for some, at the expense of sharing
>things with each other?

Utter horse manure.  Anyone can profit from something so long as it
is thier own idea.

>> Ourselves and our children are lost generations with respect to
>> ethics, manners,

>Ethics such as sharing, and helping one's neighbour?

Giving away an illegal copy of software it not helping one's neighbor,
it is making that neighbor an accessory to copyright infringement,
a federal offense punishable not in excess of 10 years of $10K.
Such a nieghbor should ask: "with friends like that, who needs
enemies?"

>I certainly hope our grandchildren will live in an environment that
>encourages helping each other, yes.

Helping each other cheat on a test is not helping, it is hurting.
There
is no difference ethically between plagiarism, cheating, or
unauthorized
copying.

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


Re: subprocess terminate help

2005-11-16 Thread Fredrik Lundh
Ernesto wrote:

> Yeah I know.  I posted it b/c I was having the same problems and I'm
> investigating ways to do this.  None of those methods gave me desired
> results for my program.  All I want to do is end my python program and
> return to the DOS prompt.

what about the other program?  do you want to terminate that as well ?

 



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


Re: Python obfuscation

2005-11-16 Thread The Eternal Squire
>The legality of copying, modifying and redistributing works should be
>reformed until it matches a 6th grader's intuitions about sharing.

A 6th grader also has intuitions regarding the ownership of an idea.
"It was MY idea!!!"  "No, it's NOT!!!"  "Is TOO!!!"

The Eternal Squire

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


Re: running functions

2005-11-16 Thread Ben Finney
Gorlon the Impossible <[EMAIL PROTECTED]> wrote:
> I'm not sure how to phrase this question. I have a Python function
> that sends MIDI messages to a synth. When I run it, I of course have
> to wait until it is finished before I can do anything else with
> Python. Is it possible to run this function and still be able to do
> other things with Python while it is running? Is that what threading
> is about? 

Threads are a complex answer. Subprocesses are a less complex answer.

(good sigmonster, have a biscuit)

-- 
 \ "I have yet to see any problem, however complicated, which, |
  `\  when you looked at it in the right way, did not become still |
_o__) more complicated."  -- Paul Anderson |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running functions

2005-11-16 Thread Grant Edwards
On 2005-11-16, Gorlon the Impossible <[EMAIL PROTECTED]> wrote:

> I'm not sure how to phrase this question. I have a Python function
> that sends MIDI messages to a synth. When I run it, I of course have
> to wait until it is finished before I can do anything else with
> Python. Is it possible to run this function and still be able to do
> other things with Python while it is running?

Yes.

> Is that what threading is about?

Exactly.  Take a look at the "treading" module:

http://www.python.org/doc/current/lib/module-threading.html

-- 
Grant Edwards   grante Yow!  BRILL CREAM is
  at   CREAM O' WHEAT in another
   visi.comDIMENSION...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: scrollbar in grid-managed frame

2005-11-16 Thread jepler
Tkinter "frame"s don't scroll.  Instead, you need to use something like
bwidget's "ScrollableFrame" widget.  You may want to combine this with
bwidget's "ScrolledWindow".

Below is an example which uses my "pybwidget" package, available at
http://tkinter.unpy.net/bwidget/
# --
import Tkinter, bwidget
 
t = Tkinter.Tk()
s = bwidget.ScrolledWindow(t, auto="vertical", scrollbar="vertical")
f = bwidget.ScrollableFrame(s, constrainedwidth=True)
g = f.getframe()

for i in range(20):
Tkinter.Label(g, text="Field %d:  " % i).grid(row=i, column=0, sticky="w")
Tkinter.Entry(g, width=25).grid(row=i, column=1, sticky="ew") 
g.grid_columnconfigure(1, weight=1)

s.setwidget(f)
s.pack(fill="both", expand=1)
t.mainloop()
# --

Jeff



pgplDevMyZAn5.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: subprocess terminate help

2005-11-16 Thread Ernesto
Yeah I know.  I posted it b/c I was having the same problems and I'm
investigating ways to do this.  None of those methods gave me desired
results for my program.  All I want to do is end my python program and
return to the DOS prompt.

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


Re: Python obfuscation

2005-11-16 Thread Ben Finney
The Eternal Squire <[EMAIL PROTECTED]> wrote:
> The greatest theft of sales opportunities

Utter poppycock. Who is to say that a particular entity holds an
exclusive "sales opportunity" to a particular individual? Are we to
protect the expectations of profit for some, at the expense of sharing
things with each other?

> Little can be done to stop it except through repeated education at
> every grade level that copying without paying is as bad as
> plagiarism and just as dangerous to one's career in school.

Wonderful double-think. 

> Ourselves and our children are lost generations with respect to
> ethics, manners,

Ethics such as sharing, and helping one's neighbour?

> and respect for authority

When such "authority" demands that we enter unsigned contracts to
protect their profits, they lose our respect, yes.

> perhaps we can train our grandchildren to behave more proprely.

I certainly hope our grandchildren will live in an environment that
encourages helping each other, yes.

-- 
 \   "We spend the first twelve months of our children's lives |
  `\  teaching them to walk and talk and the next twelve years |
_o__)telling them to sit down and shut up."  -- Phyllis Diller |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is parameter an iterable?

2005-11-16 Thread Steven D'Aprano
On Wed, 16 Nov 2005 09:06:01 -0500, Rick Wotnaz wrote:

[cutting to the important bit]
>> except TypeError, msg:
>> if msg == "iteration over non-sequence":
>> # handle non-iterable case

> Does this in fact work on your system? On mine (2.4.1 (#65, Mar 30 
> 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]), it doesn't seem to.

Dammit, that will teach me not to test my code before posting.

No it doesn't: msg is an object of type exceptions.TypeError.

The easy fix is to just coerce it to a string:

if str(msg) == "iteration over non-sequence":

which *does* work on my system. But perhaps a better way is to do this:


# Create an instance of the exception you expect:
try:
for i in 0:
pass
except TypeError, ITER_OVER_NON_SEQ:
pass
# Now run your code...
try:
...blah blah blah...
except TypeError, msg
if str(msg) == str(ITER_OVER_NON_SEQ):
...blah blah blah... 

This means we're no longer assuming what the error message will be,
which makes our code a lot more future-proof and implementation-proof: if
some version of Python changes the error string from "iteration over
non-sequence" to something else, the code should continue to work
correctly.


-- 
Steven.

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


running functions

2005-11-16 Thread Gorlon the Impossible
 Hello
I'm not sure how to phrase this question. I have a Python function
that sends MIDI messages to a synth. When I run it, I of course have
to wait until it is finished before I can do anything else with
Python. Is it possible to run this function and still be able to do
other things with Python while it is running? Is that what threading
is about? 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-16 Thread Ben Finney
The Eternal Squire <[EMAIL PROTECTED]> wrote:
> The teaching of legality and ethics of incorporating other peoples'
> works into one's own should begin at 6th grade and be repeated every
> year until the message is driven home.

I disagree strongly.

The legality of copying, modifying and redistributing works should be
reformed until it matches a 6th grader's intuitions about sharing.

-- 
 \  "I bought some powdered water, but I don't know what to add."  |
  `\  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating package question

2005-11-16 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> I think I have an answer to my own question.  In the
> WindowsComponents/__init__.py file, I have the following, that feels
> like a better answer for the problem.  Is there a better answer than
> this?
> 
> import os, sys
> sys.path.append(os.path.join(os.getcwd(), 'Common'))
> 

Err... if the script is called from somewhere else, this won't work. 
replace os.getcwd() with os.path.dirname(os.path.realpath(__file__))

Or better, use a .pth or add the needed path in your PYTHONPATH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess terminate help

2005-11-16 Thread Fredrik Lundh
Ernesto wrote

> I've been searching for ways to terminate this process so I can exit my
> program.  program.exe is a text based interface which I'm running with
> python subprocess in a DOS command window.  I tried using 'sys.exit()'
> to end my program, but nothing works.  I think I have to somehow
> terminate the subprocesses I create.  Any suggestions?

someone calling himself "Ernesto" posted this link yesterday:

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

 



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


Re: Python obfuscation

2005-11-16 Thread The Eternal Squire
Change from

3) User support and service is not an increasingly large component of
the
service provided by a software product, which can only be obtained

to

3) User support and service is an increasingly large component of the
service provided by a software product, which can only be obtained

Oops,

The Eternal Squire

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


Re: Python obfuscation

2005-11-16 Thread The Eternal Squire
>I'm asking coz i don't have any real world/industrial basis to better
>understand the problem and factors involved when selling software - i'm
>just a student

A fair request.   The teaching of legality and ethics of incorporating
other peoples' works into one's own should begin at 6th grade and be
repeated every year until the message is driven home.

The concept of intellectual property (patent, copyright, trade secret)
is an extension into the business world of issues regarding the proper
usage of ideas (e.g. scientific principles) as treated in high school
and college.

>Do developers, when writing code consider how protected their
>code will be when considering what language they will write it in
>i.e ease of use, speed of language, maintainability and
>'obfuscatability' ?

Typically not due to a few well-known principles:  1) Essentially an
optimized (not debug!) compilation from source code to machine language
is nearly as good as encryption for hindering reverse engineering of
the distributed code,  2) Network license servers residing on a
seperate machine in the network apart from the executing software have
become the method of choice for securing more valuable software, 3)
User support and service is not an increasingly large component of the
service provided by a software product, which can only be obtained
through possession of a legal copy, 4) The time-to-market and
obsolescense windows of software are continuing to decrease to the
point where the time required to get around security is more expensive
than the utility that software provides.

Of course, all generally sweeping rules are false including this one,
but those are the trends.

All that being said:

The greatest theft of sales opportunities resides in entertainment or
gaming software.   Little can be done to stop it except through
repeated education at every grade level that copying without paying is
as bad as plagiarism and just as dangerous to one's career in school.
Ourselves and our children are lost generations with respect to ethics,
manners, and respect for authority, perhaps we can train our
grandchildren to behave more proprely.

Productivity software is less so, the market is usually flooded with
reverse engineered or lookalike competitors but brand name loyality
usually wins out.  Electronic Design Automation (EDA) software is
rarely so, due to the huge need for customer support that is denied to
an unregistered user.

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


Re: Python obfuscation

2005-11-16 Thread Steven D'Aprano
On Wed, 16 Nov 2005 13:51:35 +, Ed Jensen wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>> I'm not sure if that is meant to be a rhetorical 
>> question or not, but something of the order of 95% of 
>> all software written is never distributed to others, 
>> and so copyright or the lack of copyright is not an issue.
> 
> Can you cite your source(s) for this information?

Not easily, but I will try.

If it helps, I will clarify what I was talking about -- in hindsight it is
a little unclear. Most software written (I think about 95%) is by
companies for in-house use only. Since it never gets distributed outside
of the company using it, copyright is of little additional value.


-- 
Steven.

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


Re: can modules be dynamically reloaded

2005-11-16 Thread Benjamin Niemann
Steve wrote:

> Can python modules be reloaded.

Yes:

import mymod
...
reload(mymod)

But this will not always work as expected (what someone would expect who
does not really understand how it works...). Read the documentation on


> For example you import a module, programatically edit it, then have the
> file reload the module?
> 
> Does anyone have any ideas about this?
> Steve

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: initialising a list of lists

2005-11-16 Thread Steven D'Aprano
On Wed, 16 Nov 2005 13:58:45 +0100, Peter Kleiweg wrote:

> 
> This does not what I want it to do:
> 
> >>> a = [[]] * 6
> >>> a[3].append('X')
> >>> a
> [['X'], ['X'], ['X'], ['X'], ['X'], ['X']]
> 
> This does what I want:
> 
> >>> b = [[] for _ in range(6)]
> >>> b[3].append('X')
> >>> b
> [[], [], [], ['X'], [], []]
> 
> The first is clear and wrong. 

That is correct. It is wrong because you make six references to the same
empty list instead of six different empty lists.

> The second is hairy and right.

I disagree. I think the second method is just as clear as the first.

> Is there a way to do it clear and right?

There are lots of ways to do it right. Clarity is in the eye of the
beholder. But perhaps the clearest way is the most explicit:

>>> c = []
>>> for i in range(6):
...c.append([])
>>> c[3].append('X')
>>> c
[[], [], [], ['X'], [], []]


I can't help feeling though that this is such a common task, and so often
trips up newbies, that it deserves a built in list method. I base my
reasoning on the existence of methods like extend:

Instead of writing:

for item in seq:
L.append(item)

the Powers That Be created L.extend(seq). This isn't the only case of very
simple idioms being made even shorter in Python.

So perhaps there should be a list method that takes an integer argument
and appends that many empty lists:

d = []
d.append_empties(5)

Or even a function that does this:

def nested(numcopies, base=None, *args):
if base is None:
base = []
for i in range(numcopies):
base.append(args[:])
return base





-- 
Steven.

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


can modules be dynamically reloaded

2005-11-16 Thread Steve
Can python modules be reloaded.

For example you import a module, programatically edit it, then have the
file reload the module?

Does anyone have any ideas about this?
Steve

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


subprocess terminate help

2005-11-16 Thread Ernesto
def launchWithoutConsole(command, args):
"""Launches 'command' windowless and waits until finished"""
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen([command] + args,
startupinfo=startupinfo).wait()


handle = launchWithoutConsole("program.exe",["disconnect"])
--

I've been searching for ways to terminate this process so I can exit my
program.  program.exe is a text based interface which I'm running with
python subprocess in a DOS command window.  I tried using 'sys.exit()'
to end my program, but nothing works.  I think I have to somehow
terminate the subprocesses I create.  Any suggestions?

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


Re: How to write an API for a Python application?

2005-11-16 Thread Mike Meyer
"Eric Brunel" <[EMAIL PROTECTED]> writes:
> On 16 Nov 2005 06:18:05 -0800, Paul Boddie <[EMAIL PROTECTED]> wrote:
>> One technology that I used many years ago with Python, and which should
>> still do the job is CORBA - at that time ILU, but I suppose the various
>> other ORBs should also be as capable; certainly, ILU permitted
>> callbacks from the server into the client. These days, you might want
>> to look at omniORB, Fnorb and ORBit.
> I never saw any way to create callbacks from server to client with CORBA. How 
> would you describe such a callback in the IDL file?

It's OO, not functional. You pass an object to the server, and the
server invokes methods on that object. In the IDL, you use the
interface name as a type. I.e.:

  interface Window {
  ...
  }
  
  and in another interface:
  WindowListFindWindows(in Window name) ;

And, FWIW, Fnorb hasn't been maintained for a while. It requires
patching to run on recent versions of Python.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more
information. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: readline vi mode in python interactive shell

2005-11-16 Thread [EMAIL PROTECTED]
Well, I subsequently found this:

http://groups.google.com/group/gnu.bash.bug/browse_thread/thread/ab3d3d5ff3e1ea89/f50f81b86161b271?lnk=st&q=readline+vi+mode&rnum=25#f50f81b86161b271

to explain it.

Bummer ...

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


Re: readline vi mode in python interactive shell

2005-11-16 Thread Micah Elliott
On Nov 16, [EMAIL PROTECTED] wrote:
> Hi comp.lang.python:
> New to the group and new to python, so don't tear me up too much ...
> I installed the GNU readline support in python2.4, and it is working,
> but there is one annoying behaviour that I am hoping to squash ...
> 
> Namely, when I hit  to go to edit mode, then hit 'k' to go up
> in the command history, the prompt is put at the start of the line.

Amazing that you brought this up right now; I was just thinking about
whether or not to bother posting my own annoyance (invisible last
history command) with readline 4.3-5 (default with Fedora Core 3) and
Python 2.4.2.  Since you brought it up, here's my test case:

My ~/.inputrc simply contains "set editing-mode vi".  When I start
python I type "print 'a'".  Then "k" to recall the last
command -- but the line is invisible!  If I start editing the
blank/invisible line the text magically appears.  Or if I press
"k" twice I have visible history again.  So now I have in muscle
memory "kkj" to get my last command :-(

This is not a problem on the same machine with older versions of python
that are installed.  Is this worth filing a bug against python?  I
didn't find anything reported on sf.net/projects/python.

> Other places I use vi mode command line editing (e.g., zsh),  the
> cursor is at the end of the previous command. More often than not, I
> am wanting to edit the latter part of the previous command, not the
> start.

In bash "k" puts me at the *beginning* of the line.  Of course $
puts you where you want to be then, but I'm not sure how to affect the
behavior you're asking for; "help bind" might be useful, and "bind -P"
shows some mappings.

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-16 Thread Mike Meyer
"Ben Sizer" <[EMAIL PROTECTED]> writes:
> Mike Meyer wrote:
>> "Ben Sizer" <[EMAIL PROTECTED]> writes:
>> > In my
>> > case, providing a free download of any lost executables or data upon
>> > presentation of a legitimate license key should be adequate.
>> My special handling for such
>> things - and *especially* for entertainment software, where the media
>> gets handled by children - is "Return that POS."
> That's funny, I could have sworn that a few messages above you
> suggested I "Try Alex's solution, and put the data on a network server
> that goes through whatever authentication you want it to."
> Are you claiming therefore that it's more acceptable to you to have to
> access the data remotely every time you use the software than once per
> install?

Alex's solution doesn't require special treatment for disaster
recovery and/or planning, and as such is a valid answer to the
question. It may be unacceptable for *other* reasons, but it beats
dictating a disaster recovery plan for your software to the end user
hands down on that basis.

>> Worse yet, you play
>> semantic games so you can claim not to be violating fair use rights in
>> the process.
> No, I am just pointing out that you are mixing up the concept of an
> actual 'right' such as one embodied in a state's constitution, with an
> implied 'right' that is just an exemption from committing an offence.
> The term 'right' does not even appear in the relevant part of US
> copyright law, except to state that it is a limitation on the copyright
> holder's rights.

You're still just playing semantic games. The common usage is "fair
use rights." If you mean "... without infringing on the end users
rights, except for fair use rights", then you should say that.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: repeating regular expressions in one string

2005-11-16 Thread Fredrik Lundh
"Shane" wrote

> I have a bunch of strings that looks like this:
>
> 'blahblah_sf1234-sf1238_blahblah'
>
> and I would like to use the re module to parse all the 'sf' parts
> of the string. Each 'sf' needs to be its own string when I am
> through. How do I compile a regular expression that looks for more
> than one instance? Currently my expression looks like this:
>
> myString = re.compile('sf[0-9][0-9][0-9][0-9]')
>
> This works great for finding the first instance of 'sf'.

if you want to extract all matches, you can either call the search method
again (with a start offset), or use a method that returns all matches:

>>> s = 'blahblah_sf1234-sf1238_blahblah'

>>> import re
>>> p = re.compile('sf[0-9][0-9][0-9][0-9]')

footnote: you can use \d instead of [0-9]:

p = re.compile('sf\d\d\d\d')

and you can use {n} to specify a repeat count:

p = re.compile('sf\d{4}')

no matter what form you prefer, you can use findall and finditer to locate all
matching substrings:

>>> print p.findall(s)
['sf1234', 'sf1238']

>>> for m in p.finditer(s):
... print m, m.group()
...
<_sre.SRE_Match object at 0x00A29058> sf1234
<_sre.SRE_Match object at 0x00A29918> sf1238

 



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


Re: repeating regular expressions in one string

2005-11-16 Thread Inyeol Lee
On Wed, Nov 16, 2005 at 03:09:56PM -0500, Shane wrote:
> Hi folks,
> 
> I'm new to regular expressions (and a novice at Python) but it seems to be 
> the tool I need for a particular problem. I have a bunch of strings that 
> looks like this:
> 
> 'blahblah_sf1234-sf1238_blahblah'
> 
> and I would like to use the re module to parse all the 'sf' parts of the 
> string. Each 'sf' needs to be its own string when I am through. How do I 
> compile a regular expression that looks for more than one instance? Currently 
> my expression looks like this:
> 
> myString = re.compile('sf[0-9][0-9][0-9][0-9]')
> 
> This works great for finding the first instance of 'sf'. I hope that was 
> clear :)
> 
> Thanks,
> 
> Shane
> -- 
> http://mail.python.org/mailman/listinfo/python-list

You can simplify your pattern

myString = re.compile('sf[0-9][0-9][0-9][0-9]')

to

myString = re.compile(r"sf\d{4}")

>>> import re
>>> s = 'blahblah_sf1234-sf1238_blahblah'
>>> pat = re.compile(r"sf\d{4}")
>>> re.findall(pat, s)   
['sf1234', 'sf1238']
>>> for m in re.finditer(pat, s):
... print m.group()
... 
sf1234
sf1238
>>> 

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


Re: using openurl to log into Yahoo services

2005-11-16 Thread Mike Meyer
"joe_public34" <[EMAIL PROTECTED]> writes:

> Hello all,
>
> I'm trying to write a script to log into Yahoo! (mail, groups, etc),

I don't have an answer to your problem but I *do* have a script that
logs into yahoo. It's ugly, but it works. I'm refactoring it - if I
ever get back to it.

I've appended the crucial code, but haven't tried running this
excerpt. If you have problems or questions, feel free to ask.

 http://groups.yahoo.com').read())
passage.done()
i = 0
while passage and i < 5:
page = passage
passage = handle_login(passage, password)
i = i + 1

if i >= 5:
handle_bogus(page, 'To many login attempts')# Never returns

while 1:
metas = page.fetch('meta', {'http-equiv': 'Refresh'})
if not metas:
return page
# Sigh. It's redirect page that didn't get handled by the library.
page = meta_redirect(metas[0]['content'])

return page


def handle_login(soup, password):
"""Parse a page for login information, and hand back the result of logging 
in.

Returns None if there is no login form."""

# Get the login page, scrape the form, and log in!
forms = soup.fetch('form', {'name': 'login_form'})
if not forms:
return None
form = forms[0]

postdata = []
for intag in form.fetchNext('input'):
if intag['type'] == 'hidden':
postdata.append((intag['name'], intag['value']))
elif intag['type'] == 'password':
postdata.append((intag['name'], password))
elif intag['type'] == 'checkbox':
postdata.append((intag['name'], 'n'))
elif intag['type'] == 'text' and intag['name'] == 'login':
postdata.append(('login', myYahooID))
elif intag['type'] == 'submit':
if intag.has_key(['name']):
postdata.append((intag['name'], intag['value']))
else:
postdata.append(('submit', intag['value']))
else:
print "Login form had unrecognized input tag:", str(intag)

out = BeautifulSoup(urlopen(form['action'], urlencode(postdata)).read())
out.done()
return out

def meta_redirect(value):
"""Handle a http-equiv redirect, since the library isn't reliable."""

for spam in value.split(';'):
stuff = spam.strip().split('=')
if stuff and stuff[0] == 'url':
out = BeautifulSoup(urlopen(stuff[1]).read())
out.done()
return out


-- 
Mike Meyer <[EMAIL PROTECTED]>  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: repeating regular expressions in one string

2005-11-16 Thread Carl J. Van Arsdall
Shane wrote:
> Hi folks,
>
> I'm new to regular expressions (and a novice at Python) but it seems to be 
> the tool I need for a particular problem. I have a bunch of strings that 
> looks like this:
>
> 'blahblah_sf1234-sf1238_blahblah'
>
> and I would like to use the re module to parse all the 'sf' parts of the 
> string. Each 'sf' needs to be its own string when I am through. How do I 
> compile a regular expression that looks for more than one instance? Currently 
> my expression looks like this:
>
> myString = re.compile('sf[0-9][0-9][0-9][0-9]')
>
>   
Well, since all your strings come in the same format you might try 
something like

myString = re.compile(r'\w+_(sf\d\d\d\d)-(sf\d\d\d\d)_\w+')

then when you do your matching:

extracted = myString.match(originalStrnig)

your two extracted strings would be accessible via:

extracted.group(1)
extracted.group(2)


> This works great for finding the first instance of 'sf'. I hope that was 
> clear :)
>
> Thanks,
>
> Shane
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can anyone tell me if pygame and Tkinter can work together?

2005-11-16 Thread Fredrik Lundh
Nathan Pinno wrote:

> It's a warning that says:
>
> Can only use * in top level or something like that.
>
> It's kind of annoying

why?  importing tons of unknown stuff into a local namespace is
rather silly, and makes it impossible for the compiler to properly
analyze your code -- which means that you cannot use nested
scoping.  the language reference says:

The from form with "*" may only occur in a module scope.
If the wild card form of import -- "import *" -- is used in a
function and the function contains or is a nested block with
free variables, the compiler will raise a SyntaxError.

future versions of Python will most likely issue a SyntaxError also
for "import *" in non-nested functions.

> but the program still ran after I made the import * lines top level,
> and removed the def's.

moving the "import *" line to the module scope would have been
enough; functions can refer to module-level variables just fine.

you might wish to read up on Python scoping rules:

http://docs.python.org/ref/naming.html

 



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


repeating regular expressions in one string

2005-11-16 Thread Shane
Hi folks,

I'm new to regular expressions (and a novice at Python) but it seems to be the 
tool I need for a particular problem. I have a bunch of strings that looks like 
this:

'blahblah_sf1234-sf1238_blahblah'

and I would like to use the re module to parse all the 'sf' parts of the 
string. Each 'sf' needs to be its own string when I am through. How do I 
compile a regular expression that looks for more than one instance? Currently 
my expression looks like this:

myString = re.compile('sf[0-9][0-9][0-9][0-9]')

This works great for finding the first instance of 'sf'. I hope that was 
clear :)

Thanks,

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


readline vi mode in python interactive shell

2005-11-16 Thread [EMAIL PROTECTED]
Hi comp.lang.python:
New to the group and new to python, so don't tear me up too much ...
I installed the GNU readline support in python2.4, and it is working,
but there is one annoying behaviour that I am hoping to squash ...

Namely, when I hit  to go to edit mode, then hit 'k' to go up in
the command history,
the prompt is put at the start of the line.

Other places I use vi mode command line editing (e.g., zsh),  the
cursor is at the end of the previous command.

More often than not, I am wanting to edit the latter part of the
previous command, not the start.

Is there any way to tell readline to put the cursor at the end of the
command line when browsing them?

Thx for any light you can shinte,
Tim

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


Re: creating package question

2005-11-16 Thread infidel

[EMAIL PROTECTED] wrote:
> I think I have an answer to my own question.  In the
> WindowsComponents/__init__.py file, I have the following, that feels
> like a better answer for the problem.  Is there a better answer than
> this?
>
> import os, sys
> sys.path.append(os.path.join(os.getcwd(), 'Common'))

My solution to this is to use a .pth file.  In my site-packages folder
under the python installation, I have a file named infidel.pth.  This
file contains the path to the folder where I put all my python source
code (C:\src\py).  In your case, you could have the path to your 'root'
folder.

One of my projects is structured like this:

C:\src\py
infidel\
__init__.py
models\
__init__.py
basemodel.py
views\
__init__.py
baseview.py
controllers\
__init__.py

Now the controllers package can do imports like this:

from infidel.models import basemodel
from infidel.views import baseview

The point is that the .pth file in site-packages adds custom paths to
your sys.path

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


Re: Quitting a Tkinter application with confirmation

2005-11-16 Thread Fredrik Lundh
Peter Kleiweg wrote:

> I want the program to behave identical if the 'close' button of
> the application window is clicked. I tried the code below,
> using a class derived from Tk that redefines the destroy
> method. That seems to work. At least on Linux.
>
> My questions:
>
> Is this the correct and save way to do this? Will it work on any
> operating system? Shouldn't I do some event capturing instead?

the right way to do this is to implement a WM_DELETE_WINDOW
protocol handler:

http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols

in your case, adding

root.protocol("WM_DELETE_WINDOW", root.destroy)

to the right place should be enough.

> (Capture the SIGTERM or SIGQUIT, sent by the Window manager to
> the application.)

that's signals, not events, and should not be needed.  (afaik, a properly 
written
X Window application should shut down by itself, in response to DestroyWindow
requests from the window manager.  if the window manager has to use explicit
kill signals to get rid of an application, something's wrong).

 



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


Re: creating package question

2005-11-16 Thread Micah Elliott
On Nov 16, [EMAIL PROTECTED] wrote:
> I have a package directory structure as follows
> 
> root-
> |
> Common (contains __init__.py file)
> WindowsComponents (contains __init__.py file)
> ...
> 
> I would like modules in the WindowsComponents directory to be able
> to import some modules from the Common directory.

So you now have a "Common" package.  And it might contain a "mustard"
module.

> In my first pass, I was able to append sys.path (
> sys.path.append('../Common') ) in each module that wants to import
> from Common, but this feels "clunky".

Agreed.  You probably want to avoid messing with sys.path whenever
possible.

> Is there a "standard"/"best" way to accomplish this?  

So "root" should already be on your sys.path/PYTHONPATH.

Then in say file "root/WindowsComponents/spam.py":

from Common import mustard
...
mustard.attr

More import info from Fredrik:
http://effbot.org/zone/import-confusion.htm

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie - How do I import automatically?

2005-11-16 Thread Claudio Grondi

Probably you have inbetween already found the 'def runsource(' line in the
PyShell.py , but maybe you still wait for a reply, so here it is:

yes, you put the two lines at the beginning of in PyShell.py existing
runsource() method of the class ModifiedInterpreter(InteractiveInterpreter)

If in my Windows IDLE version the things are different from yours, sorry,
I can't help in that case having no Linux installation available.

Claudio

<[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Where do I put
>
>  def runsource(self, source):
> if(source == ''):
>source = 'from btools import *'
> "Extend base class method: Stuff the source in the line cache
> first"
> filename = self.stuffsource(source)
>
> Do I put it in Pyshell.py or somewhere else?
>
> Bob
>



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


Re: creating package question

2005-11-16 Thread erick_bodine
I think I have an answer to my own question.  In the
WindowsComponents/__init__.py file, I have the following, that feels
like a better answer for the problem.  Is there a better answer than
this?

import os, sys
sys.path.append(os.path.join(os.getcwd(), 'Common'))


--ERick

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


Re: Creating (rather) generic plugin framework?

2005-11-16 Thread bruno at modulix
Edvard Majakari wrote:
> Hi,
> 
> My idea is to create a system working as follows: each module knows
> path to plugin directory, and that directory contains modules which
> may add hooks to some points in the code.
> 
> Inspired by http://www.python.org/pycon/2005/papers/7/pyconHooking.html
> 
> I would create a class like this:
> 
> class Printer:
> 
> def printit(self, msg):
> stuff = self.beforePrintHook(msg)
> if stuff:
> msg = stuff
> print msg
> self.afterPrintHook(msg)
> 
> def beforePrintHook(self, msg): pass
> def afterPrintHook(self, msg): pass
> 
> Now, in the spirit of py.test, I'd like API to be practically no API at all :)
> moreover, deploying a plugin must consist simply of adding appropriate file to
> plugins directory, nothing more, and removing it would uninstall it. The
> plugin should be able to somehow result in all future invocations to
> Printer.printit() call hooks specified in the plugin. Now, the plugin module
> for class above /might/ be along the following lines (I'm thinking of stuff
> here, so I don't know yet what would be the most appropriate way):
> 
> ### a very simple plugin which uppercases all data fed to it.
> 
> extensions = {'Printer': 'PrinterHook'}
> 
> class PrinterHook:
> 
> def beforePrintHook(self, msg):
> return msg.upper()
> def afterPrintHook(self, msg):
> print "Called afterPrintHook with msg %s" % msg
> 
> 
> Now, I have a very rude (I think) implementation which has two methods, first
> the one that loads plugin modules:
> 

(snip code)

> 
> But hey, this has many downsides. First off, mechanism doesn't support
> arbitrary namespaces. Here, class identifier in the plugin must be as it is
> seen from the module which calls the plugin (not a problem for me, but could
> be more elegant; probably a mapping between logical class identifiers and
> actual class names, hmm?). Second, if one wants to use many hooks (with
> priority for conflicts), it is not possible now; set_hooks always overrides
> potentially existing hooks. And probably many other problems that are not
> obvious to me, but for the simple purpose I have in mind, it seems to work.

Just a couple of ideas:
- using decorators for plugin hooks ? ie:

import hooks

class Whatever(anything):
  @hooks.hook(for='Printer.beforePrintHook',priority=42)
  def my_function_with_a_long_name(self, *args, **kw):
 pass

The decorator would take care of "registering" the hook where relevant,
  ie, storing it in a class attribute of the hooked class ?

which leads to:

- in the hooked class, use a dict class attribute for hooks:

from hooks import run_hooks

class Printer
  # will be filled (and could even be created)
  # by the @hook decorator
  _hooks = {}

  def print(self, msg):
 # run_hooks will take care of selecting appropriate
 # hooks (by looking up the class attribute _hooks)
 # and running'em in order
 msg = run_hooks(self, 'Printer.beforePrintHook', msg)
 print msg
 run_hooks(self, 'Printer.afterPrintHook', msg)



My 2 cents... I don't even know if this can be implemented (but I don't
see why it couldn't).

> This is the first plugin system in Python I'm writing, so I can be a way off
> the correct path..



-- 
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: Can anyone tell me if pygame and Tkinter can work together?

2005-11-16 Thread Nathan Pinno
It's a warning that says:

Can only use * in top level or something like that.

It's kind of annoying, but the program still ran after I made the import * 
lines top level, and removed the def's.

Nathan Pinno.

-- 
For great sites go to: http://www.the-web-surfers-store.com
MSN Messenger: [EMAIL PROTECTED],com
Yahoo! Messenger: spam_swatter31
ICQ: 199020705
AIM: f3mighty
"Simon Brunning" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On 16/11/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
> It worked, but unfornately I can't use this line as it brings up errors:
>
> from Tkinter (or pygame) import *
>
> Anyway around this little bug?

What's the error?

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



-- 

.
  >   Posted thru AtlantisNews - Explore EVERY Newsgroup  <
  >   http://www.AtlantisNews.com  --  Lightning Fast!!!  <
  >   Access the Most Content * No Limits * Best Service  <
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python, Linux, Desktop Environment

2005-11-16 Thread Jorgen Grahn
On Wed, 16 Nov 2005 19:56:51 +0100, bruno at modulix <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> So, I've written my first GUI app in python.  I've turned it into a
>> binary .exe and .app that runs on Windows and Mac respectively, but on
>> my Linux box, where I wrote the thing, I still have to drop to the
>> command line and ./myscript.py.  What can I do to make it a "click and
>> run" sort of application in KDE or Gnome on Linux?
>
> There are *no*  "click and run" on linux, since the GUI is an option,
> not a part of the OS.
>
> What you're looking for is WM/DesktopManager specific. You'll find the
> answers in the Gnome and KDE manuals.

Yeah, and please don't accidentally remove the option to type 'myscript.py'
on the command line -- that's how I almost always start GUI programs. If I
like them enough, I edit my window manager's config so that it appears in a
suitable place in the menus. Nine applications have made that list during
the past fifteen years ;-)

/Jorgen

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


Quitting a Tkinter application with confirmation

2005-11-16 Thread Peter Kleiweg

I have an application written in Tkinter. There is a menu item 
'quit' that calls the function 'quit'. If 'quit' is called, it 
first checks if there is unsaved data. If there is, it won't let 
the application exit unless you confirm to disregard the 
changes.

So far, so good.

I want the program to behave identical if the 'close' button of 
the application window is clicked. I tried the code below, 
using a class derived from Tk that redefines the destroy 
method. That seems to work. At least on Linux. 

My questions: 

Is this the correct and save way to do this? Will it work on any 
operating system? Shouldn't I do some event capturing instead? 
(Capture the SIGTERM or SIGQUIT, sent by the Window manager to 
the application.)

from Tkinter import *
import tkMessageBox

def quit():
if not changes:
root.quit()
else:
if tkMessageBox.askyesno(_('Quit'), _('Project is not saved. Ignore 
changes and quit?')):
root.quit()

class myTk(Tk):
def destroy(self):
quit()

root = myTk()

-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/~kleiweg/ls.html
-- 
http://mail.python.org/mailman/listinfo/python-list


creating package question

2005-11-16 Thread erick_bodine
I have a package directory structure as follows

root-
|
Common (contains __init__.py file)
WindowsComponents (contains __init__.py file)
...

I would like modules in the WindowsComponents directory to be able to
import some modules from the Common directory.  In my first pass, I was
able to append sys.path ( sys.path.append('../Common') ) in each module
that wants to import from Common, but this feels "clunky".  Is there a
"standard"/"best" way to accomplish this?  

--ERick

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


Re: Python, Linux, Desktop Environment

2005-11-16 Thread Yves Glodt

> [EMAIL PROTECTED] wrote:
>   
>> So, I've written my first GUI app in python.  I've turned it into a
>> binary .exe and .app that runs on Windows and Mac respectively, but on
>> my Linux box, where I wrote the thing, I still have to drop to the
>> command line and ./myscript.py.  What can I do to make it a "click and
>> run" sort of application in KDE or Gnome on Linux?
>> 
I don't really understand what you mean... Have you tried simply 
creating a "shortcut"
that points to your script.py?
That should make it run with a click...


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


Re: Addressing the last element of a list

2005-11-16 Thread Mike Meyer
Antoon Pardon <[EMAIL PROTECTED]> writes:
> Op 2005-11-15, Mike Meyer schreef <[EMAIL PROTECTED]>:
>> Antoon Pardon <[EMAIL PROTECTED]> writes:
> Like having an assignment operator (let use @= for it) next to a
> (re)bind operator.
> We could then have something like the following.
> a = 5
> b = a
> a @= 7
> b ==> would result in 7.
 You've just overwritten the object referred to by the token "5" in the
 source code with the value 7, so you get:
 print 5
 7
>>> You have a valid point, but I think a different approach is possible.
>>> Don't make the distinction between mutable and immutable types but
>>> between mutable and immutable objects. So an int wouldn't be an
>>> immutable type, but 5 would be an immutable object.
>>> So the code above I gave would throw an exception, but the following
>>> might work.
>>> a @= 5
>>> b = a
>>> b @= 7
>>> a ==> would result in 7.
>>
>> Which solves that issue but brings up - well, more issues. What
>> happens if the third line is 'b @= "seven"'? Does this require an
>> extra level of indirection in the implementation? Avoiding that kind
>> of thing was the reason for suggesting this:
>
> It depends on how far you want to go.
>
> I think one can argue that in case of an inplace replacement, this
> only makes sense if the two objects belong to the same class. So
> no extra level of indirection is then required.

Now factor in inheritance. Do users of this facility have to worry
about static OO typing? That is, two objects that are otherwise
completely interchangeable will raise an exception if you try to
assign one to a variable holding the other, because they have the
wrong type. That seems unpythonic.

> Otherwise it really depends on how the builtin objects are implemented.
> For user classes, a somewhat simplistic implementation could be
> something like:
>
>   def '@=' (one, two):
> one.__dict__.clear()
> one.__dict__.update(two.__dict__)

Wouldn't one.__dict__ = dict(**two.__dict__) be a bit better?

Anyway, this won't' work if the class of one of the objects has
slots.

>> The critical thing is that this doesn't introduce any new facilities
>> into the language, just some new syntax, so there's no implementation
>> impact. In fact, if you're willing to put up with some notational
>> abuse, we can do this now:
>>
>> class Ref(object):
>> _unbound = object()
>> def __new__(cls, value = _unbound):
>> """We're an object, but need to ignore the optional argument."""
>>
>> return object.__new__(cls)
>>
>> def __init__(self, value = _unbound):
>> """Bind the  optional value, if provided."""
>> if value is not self._unbound:
>> self._value = value
>>
>> def __pos__(self):
>> """Return value, if bound."""
>> try:
>> return self._value
>> except AttributeError:
>> raise ValueError, "%s object does not have a value stored." % \
>>   self.__class__.__name__
>>
>> def __iadd__(self, value):
>> self._value = value
>> return self
>>
>> Usage:
>>
> x = Ref.Ref()
> x += 23
> +x
>> 23
> a = x
> x += 25
> +a
>> 25
> a += "this is a test"
> +x
>> 'this is a test'
>>
>> Since it doesn't have real lannguage support, things like +x += 25
>> don't work. That's the only obvious gotcha. Maybe ~ would be a better
>> prefix.
>
> I'm a bit puzzled on how you would implement this as real language
> support. As far as I understand this only works with Ref objects.

Correct. That's the point.

> You can't do something like the following.
>
> l = [3, 7]
> a = Ref(l[0])
>
> Instead you would have to do something like
> l = [Ref(3), Ref(7)]
> a = l[0]
>
> So it seems that if you want to use this idea for implementing langauge
> support you will have to wrap all objects in a Ref internally and this
> seems some kind of extra indirection too.

No, the idea is to expose this class to the user. They would have to
explicitly wrap objects that they want to be able to be get a
reference to. Other object types can be implemented without having to
worry about assigning to them. If you want to assign to an object, you
cdreate it as a Ref. You still have to have a special syntax so you
can distinguish assigning to a Ref from binding a name, and getting
the value of the Ref vs. getting the Ref.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie - How do I import automatically?

2005-11-16 Thread bobueland
Where do I put

 def runsource(self, source):
if(source == ''):
   source = 'from btools import *'
"Extend base class method: Stuff the source in the line cache
first"
filename = self.stuffsource(source)

Do I put it in Pyshell.py or somewhere else?

Bob

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


  1   2   >