Re: [Tutor] Python Editors (particualrly Vim)

2005-09-28 Thread Alan Gauld
> 3. scite (very simple)
>
>All are great and I use all of the three.

Just back from vacation or I would have had
a lot more to say! :-)

But I have to agree with scite as an option,
its very lightweight and fast and is basically
the editor portion opf Pythonwin(*). That means
you get all the editor features, but for many
languages.

But you lose the IDE Features - debugger integration,
some code completion, keyword suggestion etc.

Emacs can of course do all of the requested things
but you may have to invest a lot of configuration
time getting it just so.

THe other feature you may want to look for is
tags support (vim and emacs at least), ie the
ability to put the cursor on a fuinction name
and go to its definition with a single leap.
This is very good for exploring other peoples code!

(*)Scite was originally just a demostrator for
the Scintilla editor component for GUIs but it
has taken on a life of its own!

HTH,

-- 
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simultaneous Adobe Reader

2005-09-28 Thread Alan Gauld
>From windows, using a python script how can I open
> Adobe Reader without displaying a PDF document?

Just start the reader executable with no arguments.

os.system(r"C:\Program Files\Adobe\Acrobat 
7.0\Reader\AcroRd32.exe")

Does it for me.

If you need to send commands etcto it you propbably need
to to use popen()/commands/subprocess depending on your
preferences and Python version.

> to run two Adobe Reader sessions simulatneously.

Yes of course but to communicate with them you will need
to store the pipes in different variables.

An alternative approach is to use the WSH COM objects,
but thats a whole new topic!


-- 
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stupid newbie question

2005-09-28 Thread Alan Gauld
>>class startremail:
>>def __init__(self):
>> remailfile = open('U:\Bounce20.txt', 'r') 
>> #future
>> def getday(self):
>> def Read(self,line):

>>from startremail import *
>>x = startremail()
>>print x.getday()
>>I get the following return
>>
>>NameError: name 'getday' is not defined
>
> It appears that you're being bitten by my least-favorite 
> ``feature''
> of python, indentation errors.  The getday routine appears to 
> be a
> subroutine of __init__, not a method of the class.

Actually he is being bitten by *lack* of indentation.
Indentation would help here not hinder! Unless you mean
that Python should insist on a dertain minimum amouint
of indentation..

If you use >=3 chars for indentation this kind of error
rarely happens, its only when using absurdly low indentation
spaces that this occurs. Indentation is intended to prevent
this but if you try to avoid using it then you get bitten...

Admittedly if Python used block markers to close a block
(ala Ruby) then the parser would identify a missing block
marker or if the markers matched parse correctly. So I
suspect Bill is actually objecting to the lack of block
markers not the use of indentation! ;-)

Alan G. 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] find data in html file

2005-09-28 Thread Ed Singleton
On 27/09/05, lmac <[EMAIL PROTECTED]> wrote:
> Hi there,
> i have a base-question. If i want to read some kind of data out of a line
> which i know the start-tag and the end-tag in an html-file how do i
> recognize
> if it's more than one line ?
>
> Example:
>
> Some textlinktext . DATA  etc.
>
> I would use >text as the starting tag to localize the beginning of the DATA.
> And then  as the ending tag of the DATA. But if there is \n then
> there are more than
> one line.

Hopefully it's just a typo or something, but you appear to have your
ending  and  tags the wrong way round.

You should be closing the cell before you close the row.

How do you want to get the data out?  This case is simple enough that
you could do a lazy (non-greedy) regex statement for it.  Something
like "([\s|\S]+?)" would do it.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [tutor]web development

2005-09-28 Thread Ron Phillips


Well, I won't argue with anyone who chooses otherwise, but CherryPy http://www.cherrypy.org/ is easy to use, lightweight, quick, and pythonic. I write everything as plain old python, then webify it the very last thing. 
 
It's also the basis of a new, promising framework called TurboGears http://www.turbogears.org/, which Kevin Dangoor put together. He does a "Wiki in 20 minutes" tutorial that's pretty impressive.
 
 
 
Ron PhillipsProgrammer/AnalystCounty of Summit Engineer538 E. South St.Akron, OH 44311
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Prevent "Coder's Remorse"?

2005-09-28 Thread Ron Phillips
Maybe it's just me. I am always haunted by "coder's remorse" (the
certainty that there's a more compact, beautiful, fun, maintainable way
to code anything I finish.)
 
At any rate, I am currently working on a script to model an ordered
collection of geographic points, all of which must share the same
collection of attributes. So, a little collection might be:
 
pointList = [
{lat:40.123,lon:-81.456, 
'attributes':{'msg':'example','beavers':34, 'distance':18.132}
},
{lat:40.12345,lon:-81.45678, 
'attributes':{'msg':'','beavers':0, 'distance':0.0}
}
]
 
If I add an attribute of 'newAtt':'newVal' to
pointList[1]['attributes'], I want it to automatically add
'newAtt':'default' to
all the other member's 'attributes' dictionary. If I delete an
attribute, it should delete from all the member's dictionaries. The
attributes are limited to string, integer, and float values.
 
I can do this by brute force, but:

Is there an elegant approach that occurs to anyone? 
Is there a data structure that forces all members to have the same
keys? 
Is there an object structure that will let updates to one instance
affect all instances?
Am I even asking the right questions?

I suspect there's an elegant solution, but it's beyond me right now. If
not, fine; I'll happily go on with my ham-fisted approach.

Regards,




 
 

Ron Phillips
Programmer/Analyst
County of Summit Engineer
538 E. South St.
Akron, OH 44311
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web development

2005-09-28 Thread Kent Johnson
Don Jennings wrote:
> what I would really like to know are how people decided to use any 
> particular framework.

Well I stumbled into Jython / Velocity over many years. My first web 
application was written in Java + servlets using the Jetty servlet engine. At 
first I didn't use any template engine and discovered the pain of manual HTML 
generation. Eventually I found Velocity and came to love it. At some point I 
learned Python and Jython and figured out that using Jython to write the 
servlet and Velocity for the view made for very agile web site development.

More recently I have completed a small project using CherryPy. My selection 
process for this was based on requirements and personal preference. I was 
writing a tool that would be distributed in my company so setup had to be easy. 
For this reason I wanted a framework that included a standalone webserver 
rather than requiring Apache. The tool could conceivably be distributed as a 
proprietary product so I avoided frameworks that are GPL licensed. These two 
requirements narrowed the field considerably. I also wanted XML-RPC support 
which is included with CherryPy. I have wanted to try it out so I gave it a go.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] script question

2005-09-28 Thread Chris Hallman

Thanks for all the input!!! I really appreciate it. I need to post a
correction to my script. What I sent was an early version. I made a few
minor modifications:



import ConfigParser, string, sys, ossection = sys.argv[1]interface = sys.argv[3]INI=ConfigParser.ConfigParser()INI.read("c:\utils\interfaces.ini")interface_entries=[p for p in INI.options
(section)]interface_list=[INI.get(section, pw) for pw in interface_entries]for i in interface_list:	if i == interface:		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " + 
sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])



I've researched what you all have suggested and I may need to switch to
reading the ini file line by line or using a different file parser. The
ini file is only 100 lines long now, but will likely grow to 500 line
and maybe to 4000 lines. To give you a better background of what I'm
doing with this script, it's running on a network management system
that receives traps. After some processing of the raw trap, messages
get sent to this script for further processing. These messages are for
interface down traps from routers and switches in our network. I use
this script to mitigate the number of interface down messages on our
console. I need to do this because we do not need to know when every
port has gone down (i.e. user ports). This script searches the ini file
for a device name match. Once it has found a match and if the interface
matches as well, I need to message forwarded to the console (the
Windows command). If no matching device or interface is found, then the
script can just exit.
- Show quoted text -
On 9/26/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Kent Johnson wrote:> *TEST FIRST* Don't optimize until you know it is too slow and you> have a test case that you can time to see if your 'optimizations' are> making it faster.Pardon my shouting :-)
Kent___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prevent "Coder's Remorse"?

2005-09-28 Thread Kent Johnson
Ron Phillips wrote:
> At any rate, I am currently working on a script to model an ordered
> collection of geographic points, all of which must share the same
> collection of attributes. So, a little collection might be:
>  
> pointList = [
> {lat:40.123,lon:-81.456, 
> 'attributes':{'msg':'example','beavers':34, 'distance':18.132}
> },
> {lat:40.12345,lon:-81.45678, 
> 'attributes':{'msg':'','beavers':0, 'distance':0.0}
> }
> ]
>  
> If I add an attribute of 'newAtt':'newVal' to
> pointList[1]['attributes'], I want it to automatically add
> 'newAtt':'default' to
> all the other member's 'attributes' dictionary. If I delete an
> attribute, it should delete from all the member's dictionaries. The
> attributes are limited to string, integer, and float values.
>  
> I can do this by brute force, but:
> 
> Is there an elegant approach that occurs to anyone? 
> Is there a data structure that forces all members to have the same
> keys? 
> Is there an object structure that will let updates to one instance
> affect all instances?
> Am I even asking the right questions?

I'm curious about why you want to do this, it is kind of a strange requirement. 
But anyway, here is a class that subclasses dict and presents the interface you 
want to client code. It doesn't actually update all instances when you add or 
delete a key; it keeps a list of valid keys in a class attribute and updates 
this list when you add or delete. Then when you access a key it checks the list 
of valid keys. If the key you want is not in the list, you get a KeyError - the 
instance dict is never checked. If the key you want is in the list but not in 
the instance, you get the default value.

I don't see any need to actually add default values to all the dicts. 
Conceivably to save memory you might want to actually delete values from all 
the dicts; to do this you could keep a list of all the existing dicts as 
another class attribute. I'm not sure you will save much though as the dict 
itself probably doesn't resize downward. A side effect of not deleting keys is 
that if you delete and then restore a key, instances that had that key before 
will magically restore their old value. This could be a bug or a feature 
depending on your requirements.

Finally, the set of valid keys is shared by all instances, so if you want to 
use this for two different types of things you will have to make subclasses and 
give each subclass its own _key attribute.

Requires Python 2.3 or greater

Kent

# CommonKeysDict.py
# Make it work with Python 2.3
try:
set
except NameError:
from sets import Set as set

class CommonKeysDict(dict):
"""Dictionary where all instances must have the same set of keys
   and with a default value for unknown keys.
   
   >>> d = CommonKeysDict()
   >>> d[0]
   Traceback (most recent call last):
 ...
   KeyError: 0
   
   >>> d[0] = 1
   >>> d[0]
   1
   
   A second instance will get the default value for keys that are in use:
   >>> d2 = CommonKeysDict()
   >>> d2[0]
   'default'
   
   The second instance can have its own values
   >>> d2[0] = 2
   >>> d2[0]
   2
   >>> d[0]
   1
   
   Deleting a key from any instance removes that key from the allowed set.
   Note that this doesn't actually delete the key from all instances, it 
just
   makes it inaccessible.
   
   >>> del d[0]
   >>> d2[0]
   Traceback (most recent call last):
 ...
   KeyError: 0
   
"""

_keys = set()

def __init__(self, **items):
dict.__init__(self, **items)

def __getitem__(self, key):
if key not in self._keys:
raise KeyError, key
try: 
return dict.__getitem__(self, key)
except KeyError:
return 'default'


def __setitem__(self, key, value):
self._keys.add(key)
dict.__setitem__(self, key, value)


def __delitem__(self, key):
self._keys.remove(key)
dict.__delitem__(self, key)


def _test():
import doctest
doctest.testmod()

if __name__ == "__main__":
_test()


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web development

2005-09-28 Thread Andrew P
I've used CherryPy on a couple of projects now.  I use it with
HTMLTemplate
(http://freespace.virgin.net/hamish.sanderson/htmltemplate.html) and
SQLObject (http://sqlobject.org/). 

This has the advantage of being about as Pythonic as you can get, since
everything you manipulate is represented as an object. 
HTMLTemplate is especially nice since it completely separates the html
from your code.  I can, have, and do change the interface
frequently with impunity, and vice versa.  Contrast this with
something like inline PHP.  It's also editable in any old wsywig
HTML editor.  But you are free to choose whatever persistent
storage and templating system you like.

CherryPy is low level, and will force you to make decisions about what
templating you want to use, and what you want to use for a
backend.  But the upside is, it feels no different than writing
any other program.  Just do what you've always done, choose
supporting packages you like, and it's off to the races.  It's
even it's own webserver. So edit, run, edit run.  Same as always.

I can tell you why I didn't choose some others.  Zope is a chunky,
labyrinth-like framework.  My friend runs Plone, built with Zope,
and it's easily the most resource heavy thing running on my
server.  That just sent me running.  Webware uses some sort
of JSP/ASP/PHP alike, which makes me cringe in horror.  HTML and
code do not belong together in a big inline spaghetti lovefest. 
IMHO :)  

Twisted is an "asynchronous networking framework", and I haven't used
it, but actually looks fairly small, has it's own webserver, and a very
very nice looking templating system which has the same philosophy as
HTMLTemplate, but has some really cool feautures like livepage, which
seems to be the same thing as AJAX, a la google maps.  I just
haven't had a reason to check it out, but it would be first on my list
to check.  It's more of a kitchen sink approach, or general
purpose if you prefer, but does seem cool.  So if you are looking
for something like that, well.  Build websites, write chat
programs! 

OK.  Enough early morning rambling :)  Good luck choosing. 

On 9/27/05, Don Jennings <[EMAIL PROTECTED]> wrote:
Earlier this month, Kent posted that Jython and Velocity are a good wayto develop dynamic web sites. After a little searching, it seems thatthere are quite a few options for web development in Python (perhapstoo many?). So, rather than ask for recommendations of which one to
use, what I would really like to know are how people decided to use anyparticular framework.Thanks!DonP.S. As an aside, does anyone have any experience with django? (Ireally like the name since I am fond of django reinhardt, the jazz
guitarist.)___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Prevent "Coder's Remorse"?

2005-09-28 Thread Ron Phillips
 Kent Johnson wrote:
I'm curious about why you want to do this, it is kind of a
strange requirement. 

Yeah, that was bothering me, too. I was a little unsure if I'd even
defined the problem properly; that's what I meant by: "Am I even asking
the right questions?" 

I'll play around with the class a little and see if it helps me clarify
to myself what I am trying to do. I was kind of on the right path, but
I've never written much with __getitem__, __setitem__, etc. and it
wasn't going at all like I had in mind. I've found that when I patch and
patch and patch my code, it's usually because I am trying to do the
wrong thing altogether. And I wasn't using Class attributes properly,
either.

Thanks so much! Sorry for the vague question, but I really think the
class you made is close to what I needed.

Ron

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Reformatting a one (long) line xml file

2005-09-28 Thread Negroup -
Hi all, I have an xml file where the tags are all on the same line,
without any newline. This file is quite big and difficult to read. I'd
like to format it in a convenient way, using indentation and nesting.
How to pretty print my content?

I hope to have explained well enough my problem, differently let me know.

Thans a lot!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prevent "Coder's Remorse"?

2005-09-28 Thread Alan G
> pointList = [
> {lat:40.123,lon:-81.456, 
>'attributes':{'msg':'example','beavers':34, 'distance':18.132}
> },
> {lat:40.12345,lon:-81.45678, 
>'attributes':{'msg':'','beavers':0, 'distance':0.0}
> }
> ]

THis sopunds like its crying out for a class

class Point:
   def __init__(self, lat, long, msg, beavers, distance):
  self.lat = lat
  self.long = long
  etc...
  

Pointlist = [Point(40.123,-81.456,'example',34,18.132),
 Point(40.12345,-81.4567,'',0,0.0)]

> If I add an attribute of 'newAtt':'newVal' to
> pointList[1]['attributes'], I want it to automatically add
> 'newAtt':'default' to all the other member's 'attributes' 
> dictionary. 

You could do that by calling a class method that updates all 
of the instances.

> If I delete an attribute, it should delete from all the 
> member's dictionaries. 

Likewise a class method could do this.

> attributes are limited to string, integer, and float values.

Doesn't really matter! :-)

> Is there an elegant approach that occurs to anyone? 
> Is there a data structure that forces all members to have the same
> keys? 

A class. Although in Python its always possible to add 
instance variables but you have to do it deliberately!
But at least a class will ensure that all the values 
that should be there are indeed present.

> Is there an object structure that will let updates to one instance
> affect all instances?

A class method is the traditional way of doing that. 
Get the init method to update a global (or class based) 
list of instances and write a del() method that removes 
itself.

Then a class method can iterate that instance list 
doing whatever it needs to do...

HTH,

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Embedding

2005-09-28 Thread Joseph Quigley
Hi,
Ok, I'll try to convince them to try python... but still, would it be 
best to just:
Program in C with Python and Java scripts
Program in Python with a little bit of C?

The game we're trying to make is a Super Mario type game (or super tux 
for you like linux games).
I suppose pygame would make it a breeze for video, sound and graphics!  
My only problem is I haven't done any games withy pygame at all and 
can't find any pygame tutorials (when I google).
Thanks,
  Joe

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] script question

2005-09-28 Thread Andrew P
Have you benchmarked it yet?  4000 lines isn't very many, even for
an older machine.  Starting the Python interpreter usually takes
most of the time with simple scripts like this.  Honestly,
benchmark :)

You might find it easier to do::

interface_list = INI.items(section)for i in interface_list:
    if i[1] == interface:
    ...
the items method just returns the whole section in a list of tuples, so don't have to build it yourself.

One last you may also want to consider is lowercasing any input,
because last I checked ConfigParser lowercases what it parses whether
you want it to or not :)

So if somebody searches for NetworkDevice10, ConfigParser will return
it as networkdevice10, and you won't get a match.  That certainly
bit me a couple times.

Good luck.
On 9/28/05, Chris Hallman <[EMAIL PROTECTED]> wrote:

Thanks for all the input!!! I really appreciate it. I need to post a
correction to my script. What I sent was an early version. I made a few
minor modifications:



import ConfigParser, string, sys, ossection = sys.argv[1]interface = sys.argv[3]INI=ConfigParser.ConfigParser()INI.read("c:\utils\interfaces.ini")interface_entries=[p for p in INI.options
(section)]interface_list=[INI.get(section, pw) for pw in interface_entries]for i in interface_list:	if i == interface:		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " + 
sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])



I've researched what you all have suggested and I may need to switch to
reading the ini file line by line or using a different file parser. The
ini file is only 100 lines long now, but will likely grow to 500 line
and maybe to 4000 lines. To give you a better background of what I'm
doing with this script, it's running on a network management system
that receives traps. After some processing of the raw trap, messages
get sent to this script for further processing. These messages are for
interface down traps from routers and switches in our network. I use
this script to mitigate the number of interface down messages on our
console. I need to do this because we do not need to know when every
port has gone down (i.e. user ports). This script searches the ini file
for a device name match. Once it has found a match and if the interface
matches as well, I need to message forwarded to the console (the
Windows command). If no matching device or interface is found, then the
script can just exit.
- Show quoted text -
On 9/26/05, Kent Johnson <[EMAIL PROTECTED]
> wrote:
Kent Johnson wrote:> *TEST FIRST* Don't optimize until you know it is too slow and you> have a test case that you can time to see if your 'optimizations' are> making it faster.Pardon my shouting :-)
Kent___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Embedding

2005-09-28 Thread Kent Johnson
Joseph Quigley wrote:
> Hi,
> Ok, I'll try to convince them to try python... but still, would it be 
> best to just:
> Program in C with Python and Java scripts

This seems like a poor choice. Some commercial games have been written with the 
main game engine in C and Python used to script some game elements. My guess is 
that to have some game elements scripted in Python and some in C would be 
problematic. I guess you could program in C with Jython and Java scripts...

> Program in Python with a little bit of C?

That sounds more practical to me. Though I confess I haven't actually written 
any games this way, ISTM you could start with Python + Pygame and rewrite to C 
for performance as needed.

> 
> The game we're trying to make is a Super Mario type game (or super tux 
> for you like linux games).
> I suppose pygame would make it a breeze for video, sound and graphics!  
> My only problem is I haven't done any games withy pygame at all and 
> can't find any pygame tutorials (when I google).

Did you look on the pygame site?
http://pygame.org/tutorials.html

Also many of the sample games are open source:
http://pygame.org/projects/20

Search comp.lang.python for "game programming":
http://groups.google.com/group/comp.lang.python/search?hl=en&group=comp.lang.python&q=game+programming&qt_g=1&searchnow=Search+this+group

The rules page for the PyWeek Game Programming Challenge lists many other game 
programming resources. Also the submissions to this challenge are open source:
http://www.mechanicalcat.net/tech/PyWeek/1/rules.html/#entries-are-to-be-written-from-scratch

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web development

2005-09-28 Thread Mike Hansen
> Subject:
> [Tutor] web development
> From:
> Don Jennings <[EMAIL PROTECTED]>
> Date:
> Tue, 27 Sep 2005 22:13:30 -0400
> To:
> tutor@python.org
> 
> To:
> tutor@python.org
> 
> 
> Earlier this month, Kent posted that Jython and Velocity are a good way 
> to develop dynamic web sites. After a little searching, it seems that 
> there are quite a few options for web development in Python (perhaps too 
> many?). So, rather than ask for recommendations of which one to use, 
> what I would really like to know are how people decided to use any 
> particular framework.
> 
> Thanks!
> Don
> 
> P.S. As an aside, does anyone have any experience with django? (I really 
> like the name since I am fond of django reinhardt, the jazz guitarist.)
> 

I've looked at a few of the web development frameworks for Python. I'm thinking 
I'm going with CherryPy on my next project. Reading the docs, it seems to click 
with me. Mapping URLs directly to python functions seems pretty simple and 
flexible. The POST and GET parameters just show up as arguments to your 
functions. You can even decide weather or not you want to expose the function 
or 
not. You can use any HTML templating toolkit you want with it. I'm still 
deciding on the templating toolkit to use.

Here's my take on some of the other frameworks

Zope
It seems too big for my purposes. If your web apps are going to be high volume, 
Zope is probably the answer.

Quixote
It seems a little weird and complex to me. I may look at it again someday.

Django
Uses the MVC philosophy, and appears to build a directory structure to 
facilitate that philosophy. I'm not sure I want to go there yet in that you 
need 
to work its way and not your way. I've heard that it's very similar to Ruby on 
Rails.

Nevow
If I recall, it extracted woven from the Twisted Framework so that it could 
work 
on it's own. Kind of reminded me of Quixote.

There are many others that I passed on for various reasons.

For me, if it looked like a steep learning curve, then I thought I'd be better 
off with something else. I also wanted something that's been around for a 
while(stable) with a good size community to help if I got stuck. It had to be 
fairly easy to install and configure. I didn't want to spend all my time 
getting 
it up and running on a development server. Then having problems when it's time 
to install on a production server or other servers at different locations.

Mike
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reformatting a one (long) line xml file

2005-09-28 Thread Christopher Arndt
Negroup - schrieb:
> Hi all, I have an xml file where the tags are all on the same line,
> without any newline. This file is quite big and difficult to read. I'd
> like to format it in a convenient way, using indentation and nesting.
> How to pretty print my content?

Untested:

import sys
from xml.dom import minidom
file = sys.argv[1]

doc = minidom.parse(file)
print doc.toprettyxml(indent=2)


See http://www.python.org/doc/current/lib/module-xml.dom.minidom.html for more
info.

HTH, Chris
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prevent "Coder's Remorse"?

2005-09-28 Thread Danny Yoo


On Wed, 28 Sep 2005, Ron Phillips wrote:

> Maybe it's just me. I am always haunted by "coder's remorse" (the
> certainty that there's a more compact, beautiful, fun, maintainable way
> to code anything I finish.)
>
>  At any rate, I am currently working on a script to model an ordered
> collection of geographic points, all of which must share the same
> collection of attributes. So, a little collection might be:
>
> pointList = [
> {lat:40.123,lon:-81.456,
> 'attributes':{'msg':'example','beavers':34, 'distance':18.132}
> },
> {lat:40.12345,lon:-81.45678,
> 'attributes':{'msg':'','beavers':0, 'distance':0.0}
> }
> ]

Hi Ron,

You may want to change the data structure.

Rather than have points all be peers, reorganize them so that there's some
kind of hierarchy: that'll help you directly represent the "sharing" of
attributes.  Explicitly:

#
class Point:
def __init__(self, lat, lon, atts, parent=None):
(self.lat, self.lon, self.atts, self.parent) = (
  lat, long, atts, parent)
def lookup(self, name):
if name in self.atts:
return self.atts[name]
if self.parent:
return self.parent.lookup(name)
raise KeyError
#


The idea here is that we impose some structure among the points.  We can
keep a central Point that has a set of child points within its satellite.

##
>>> centralPoint = Point(40, -81, {})
>>> satellitePoint = Point(40, -81, {}, centralPoint)
##


Once we formalize this hierarchical relationship --- satellitePoint's
"parent" is centralPoint --- then we can test out how attribute lookup and
sharing might work:

##
>>> satellitePoint = Point(40, -81, {}, centralPoint)
>>> centralPoint.atts['color'] = 'purple'
>>> satellitePoint.lookup('color')
'purple'
##


Does this make sense?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prevent "Coder's Remorse"?

2005-09-28 Thread Ron Phillips
Ok, I have three diverse answers from three of the tutors that I respect
most. 
 
Kent Johnson's approach: subclass dict and overloads the __getitem__ ,
__setitem__, and __delitem__ methods.
 
Alan G's idea:
 ". . .
Get the init method to update a global (or class based) 
list of instances and write a del() method that removes 
itself.
 
Then a class method can iterate that instance list 
doing whatever it needs to do..."

And Danny Yoo's hierarchical structure:

". . .
The idea here is that we impose some structure among the points.  We
can
keep a central Point that has a set of child points within its
satellite.

##
>>> centralPoint = Point(40, -81, {})
>>> satellitePoint = Point(40, -81, {}, centralPoint)
##

. . ."

Very clever ideas, as far as I can tell. I need to play with all three
of them so that I understand them thoroughly.  I think that once I do,
I'll be able to say I really understand OOP in Python! I believe that
any one of these approaches will do what I need, though, so maybe it
comes down to style.

Maybe I should explain why I thought I wanted this object. I am trying
to read, edit, and write shapefiles (actually, a shapefile is a
collection of 3-6 files having the same filename, but different
extensions. It's a legacy format that still gets a lot of use in
geography.)

One of the constituent files in a shapefile is a variant of Xbase,
which knows nothing  about NULL, so I have to provide some value in
every column for every record when I write them. I thought that having a
data structure that enforces a common set of "fields", the application
would be more robust when it's being edited. (Prevent me from deleting
an item for one record and not others, or adding a field to a record
without adding at least some default value to all the others.)

I just thought about it, but a CSV file has kind of the same problem.

Thanks, everyone; this will be a real education, however I go!

Ron
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reformatting a one (long) line xml file

2005-09-28 Thread Adam
BeautifulSoup
is a brilliant module for this kind of thing. Just make an instance of
a parser feed() in the file with file.read() then .prettify()On 28/09/05, Negroup - <[EMAIL PROTECTED]> wrote:
Hi all, I have an xml file where the tags are all on the same line,without any newline. This file is quite big and difficult to read. I'd
like to format it in a convenient way, using indentation and nesting.How to pretty print my content?I hope to have explained well enough my problem, differently let me know.Thans a lot!___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prevent "Coder's Remorse"?

2005-09-28 Thread Poor Yorick
Danny Yoo wrote:

>You may want to change the data structure.
>
>Rather than have points all be peers, reorganize them so that there's some
>kind of hierarchy: that'll help you directly represent the "sharing" of
>attributes.  Explicitly:
>
>#
>class Point:
>def __init__(self, lat, lon, atts, parent=None):
>(self.lat, self.lon, self.atts, self.parent) = (
>  lat, long, atts, parent)
>def lookup(self, name):
>if name in self.atts:
>return self.atts[name]
>if self.parent:
>return self.parent.lookup(name)
>raise KeyError
>#
>
>  
>

Many thanks Danny.  This example was an moment of epiphany for me, one
that will probably drastically influence me in the future.  I owe you
big time!

--
Poor Yorick

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] hiding a notebook page

2005-09-28 Thread Jeff Peery
hello, I'm using wxpython to write a windows app. I want to be able to hide a page in a notebook and I'm not sure how to do it. functionally its the same as doing:
 
notebook.Show(False)
 
but I want that to work for just one notebook page and not the whole notebook. I tried the wxpython list but didn't have much luck. any help would be much appreciated. thanks!
 
Jeff___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Frustrated Beginner

2005-09-28 Thread Rosalee Dubberly
I am trying to learn Python to use in my lesson plans. I am using Windows XP 
and the textbooks I am using are Beginning Python by WROX and Learning 
Pyhton by O'Reilly.


I am definning a range of words 0 to 55, if the number is divisible by 
3,7,11 with no remainder print eggs, else print spam. This works.


def firstpart():
  for n in range(0, 55):
 if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
 print 'eggs,',
 else:
 print 'spam,',
# Now I am trying to modify the function to replace eggs with toast and spam 
with jelly. I have spent days and nothing works. Can you send me in the 
right direction??

Rosa Dubberly
[EMAIL PROTECTED]

_
Don’t just search. Find. Check out the new MSN Search! 
http://search.msn.click-url.com/go/onm00200636ave/direct/01/


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Frustrated Beginner

2005-09-28 Thread R. Alan Monroe
> I am trying to learn Python to use in my lesson plans. I am using Windows XP 
> and the textbooks I am using are Beginning Python by WROX and Learning 
> Pyhton by O'Reilly.

> I am definning a range of words 0 to 55, if the number is divisible by 
> 3,7,11 with no remainder print eggs, else print spam. This works.

> def firstpart():
>for n in range(0, 55):
>   if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>   print 'eggs,',
>   else:
>   print 'spam,',
> # Now I am trying to modify the function to replace eggs with toast and spam 
> with jelly. I have spent days and nothing works. Can you send me in the 
> right direction??

It seems like you could just backspace the old words and type the new
words in their place. Unless I misundertand the purpose of the
program.

Alan

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Frustrated Beginner

2005-09-28 Thread Brian van den Broek
Rosalee Dubberly said unto the world upon 2005-09-28 15:41:
> I am trying to learn Python to use in my lesson plans. I am using 
> Windows XP and the textbooks I am using are Beginning Python by WROX and 
> Learning Pyhton by O'Reilly.
> 
> I am definning a range of words 0 to 55, if the number is divisible by 
> 3,7,11 with no remainder print eggs, else print spam. This works.
> 
> def firstpart():
>   for n in range(0, 55):
>  if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>  print 'eggs,',
>  else:
>  print 'spam,',
> # Now I am trying to modify the function to replace eggs with toast and 
> spam with jelly. I have spent days and nothing works. Can you send me in 
> the right direction??
> Rosa Dubberly
> [EMAIL PROTECTED]


Hi Rosa,

does this do the sort of thing you want?

 >>> def conditional_print(test_data, first_msg, second_msg):
if test_data > 0:
print first_msg
else:
print second_msg


 >>> conditional_print(5, "Positive!", "Non-positive!")
Positive!
 >>> conditional_print(-4, "Positive!", "Non-positive!")
Non-positive!
 >>> conditional_print(5, "Spam!", "Ham!")
Spam!
 >>> conditional_print("all strings are ", "greater than 0.", "less 
than o.")
greater than 0.
 >>>

Best,

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] call a def/class by reference

2005-09-28 Thread DS
Is it possible to call a function or class by reference, aside from
using an eval approach?

What I would like to do is have a loop that processes functions by:

1.  gettting the input that consists of a function and its parameters,
2.  determining if the function is on an approved function list,
3.  executing the function
4.  rinse, repeat.

I don't actually mind eval, but I would want to make sure I inspect
everything pretty thorougly before executing.

Thanks for any help you can give me.

ds
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-28 Thread Adam
How about something like this

def foo(bar):
    print bar

d = {"foo":foo}
s = "foo"
params = "bar"
try: d[s](params)
except: KeyError

Then you can just put the allowed functions into the dictionary.On 29/09/05, DS <[EMAIL PROTECTED]
> wrote:Is it possible to call a function or class by reference, aside from
using an eval approach?What I would like to do is have a loop that processes functions by:1.  gettting the input that consists of a function and its parameters,2.  determining if the function is on an approved function list,
3.  executing the function4.  rinse, repeat.I don't actually mind eval, but I would want to make sure I inspecteverything pretty thorougly before executing.Thanks for any help you can give me.
ds___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-28 Thread DS
Thanks for answering my question.  What I'm hoping to avoid is an
explicit reference to any of the called functions within the program.  
By doing it that way, it would avoid a maintenance problem of having to
remember to put a reference for every new function in the calling program.

ds


Adam wrote:

> How about something like this
>
> def foo(bar):
> print bar
>
> d = {"foo":foo}
> s = "foo"
> params = "bar"
> try: d[s](params)
> except: KeyError
>
> Then you can just put the allowed functions into the dictionary.
>
> On 29/09/05, *DS* <[EMAIL PROTECTED]
> > wrote:
>
> Is it possible to call a function or class by reference, aside from
> using an eval approach?
>
> What I would like to do is have a loop that processes functions by:
>
> 1.  gettting the input that consists of a function and its
> parameters,
> 2.  determining if the function is on an approved function list,
> 3.  executing the function
> 4.  rinse, repeat.
>
> I don't actually mind eval, but I would want to make sure I inspect
> everything pretty thorougly before executing.
>
> Thanks for any help you can give me.
>
> ds
> ___
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tutor
> 
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help with running graphics program

2005-09-28 Thread Goofball223
Hello

I downloaded the graphics.py file and have it saved on my computer but everytime I run the following program I seem to keep getting an error.

from graphics import*

def main():
    win=GraphWin()
    shape = Circle(Point(50,50), 20)
    shape.setOutline("red")
    shape.setFill("red")
    shape.draw(win)
    for i in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY -c.getY()
    shape.move(dx,dy)
    win.close()
main()   


Traceback (most recent call last):
  File "C:/Python24/circle", line 1, in -toplevel-
    from graphics import*
ImportError: No module named graphics

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Alan's responce frustrated beginner

2005-09-28 Thread Rosalee Dubberly
I want to save this file, import it and make the changes, eggs = toast, spam 
= jelly and change the values if needed.

def firstpart():
   for n in range(0, 55):
  if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
  print 'eggs,',
  else:
  print 'spam,',
Rosa Dubberly

_
On the road to retirement? Check out MSN Life Events for advice on how to 
get there! http://lifeevents.msn.com/category.aspx?cid=Retirement

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] More than one thing at a time?

2005-09-28 Thread Joseph Quigley
Hi, I've got a problem:
I've got a semi working IRC client. There's a function that is for 
receiving and one for sending. How can I have a loop where I can receive 
messages, yet still have a send prompt?
Thanks,
Joe
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-28 Thread Danny Yoo


> Thanks for answering my question.  What I'm hoping to avoid is an
> explicit reference to any of the called functions within the program.
> By doing it that way, it would avoid a maintenance problem of having to
> remember to put a reference for every new function in the calling
> program.


In your list of requirements:

>1.  gettting the input that consists of a function and its
>parameters,
>2.  determining if the function is on an approved function list,
>3.  executing the function
>4.  rinse, repeat.

the second one is probably the one that needs clarifying.

How do you know which functions should be callable? Adam's approach to
expressing that knowledge is to use a dictionary:

d = {"foo" : foo}

And there are many other ways of doing this besides a hardcoded
dictionary.

Tell us more about what you mean for a function to be "approved", and we
should be able to suggest practical ways to do what you want.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with running graphics program

2005-09-28 Thread Danny Yoo


On Wed, 28 Sep 2005 [EMAIL PROTECTED] wrote:

> I downloaded the graphics.py file and have it saved on my computer but
> everytime I run the following program I seem to keep getting an error.

[some text cut]

> Traceback (most recent call last):
>   File "C:/Python24/circle", line 1, in -toplevel-
> from graphics import*
> ImportError: No module named graphics


What directory did you download 'graphics.py' into?  Make sure that it
does have a .py suffix, and that it's in the same directory as your
'circle' program.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] drawing squares

2005-09-28 Thread Goofball223
Hello

How would I get the following program to draw squares instead of circles?


from graphics import*

def main():
    win=GraphWin()
    shape = Circle(Point(50,50), 20)
    shape.setOutline("red")
    shape.setFill("blue")
    shape.draw(win)
    for i in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY -c.getY()
    shape.move(dx,dy)
    win.close()
main() 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Alan's responce frustrated beginner

2005-09-28 Thread Danny Yoo


On Wed, 28 Sep 2005, Rosalee Dubberly wrote:

> I want to save this file, import it and make the changes, eggs = toast, spam
> = jelly and change the values if needed.
>
> def firstpart():
>for n in range(0, 55):
>   if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>   print 'eggs,',
>   else:
>   print 'spam,',


Hi Rosalee,

It sounds like you're still stuck trying to input programs into Python.
Are you using a "programming text editor"?  If not, then you may want to
look at:

http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/

That guide should help you get started.  Some of the notes there are a
little outdated since IDLE has been changed a bit since Python 2.1.  In
particular, "Run Script" is now "Run Module" in the Run menu.  But other
than that, that IDLE guide should be relevant.

Please free free to ask questions.  Good luck!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] drawing squares

2005-09-28 Thread Danny Yoo


On Wed, 28 Sep 2005 [EMAIL PROTECTED] wrote:

> How would I get the following program to draw squares instead of circles?

What have you tried so far?  What part of your program is the part
responsible for drawing circles?  What happens if you change that part?


To tell the blunt truth, the questions you've been asking so far have been
contentless and, frankly, uninteresting.  Although we do encourage people
to ask questions on Tutor, there is a flip side of this: you have to show
some initiative.  Please do enough to show that you're actually trying
something and doing something to understand things.

Otherwise, it really looks like you don't care about anything other than
getting a "right answer", and nothing demotivates a volunteer more than
being asked to do someone else's homework.  We're interested in helping
people understand how to solve problems, but we're really not interested
in doing your homework exercises.

"How to Ask Questions the Smart Way" talks about this some more:

http://www.catb.org/~esr/faqs/smart-questions.html

Thanks.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference (fwd)

2005-09-28 Thread Danny Yoo


-- Forwarded message --
Date: Wed, 28 Sep 2005 17:11:07 -0700
From: DS <[EMAIL PROTECTED]>
To: Danny Yoo <[EMAIL PROTECTED]>
Subject: Re: [Tutor] call a def/class by reference

Danny Yoo wrote:

>
>
>>Thanks for answering my question.  What I'm hoping to avoid is an
>>explicit reference to any of the called functions within the program.
>>By doing it that way, it would avoid a maintenance problem of having to
>>remember to put a reference for every new function in the calling
>>program.
>>
>>
>
>
>In your list of requirements:
>
>
>
>>   1.  gettting the input that consists of a function and its
>>   parameters,
>>   2.  determining if the function is on an approved function list,
>>   3.  executing the function
>>   4.  rinse, repeat.
>>
>>
>
>the second one is probably the one that needs clarifying.
>
>How do you know which functions should be callable? Adam's approach to
>expressing that knowledge is to use a dictionary:
>
>d = {"foo" : foo}
>
>And there are many other ways of doing this besides a hardcoded
>dictionary.
>
>Tell us more about what you mean for a function to be "approved", and we
>should be able to suggest practical ways to do what you want.
>
>
>
>
As far as an "approved" function, what I was imagining was something along
the lines of importing modules where all functions are callable such as

approvedlist = dir(mymodule)

which would give a list of names and then going from there.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-28 Thread DS

Danny Yoo wrote:

>  
>
>>Thanks for answering my question.  What I'm hoping to avoid is an
>>explicit reference to any of the called functions within the program.
>>By doing it that way, it would avoid a maintenance problem of having to
>>remember to put a reference for every new function in the calling
>>program.
>>
>>
>
>
>In your list of requirements:
>
>  
>
>>   1.  gettting the input that consists of a function and its
>>   parameters,
>>   2.  determining if the function is on an approved function list,
>>   3.  executing the function
>>   4.  rinse, repeat.
>>
>>
>
>the second one is probably the one that needs clarifying.
>
>How do you know which functions should be callable? Adam's approach to
>expressing that knowledge is to use a dictionary:
>
>d = {"foo" : foo}
>
>And there are many other ways of doing this besides a hardcoded
>dictionary.
>
>Tell us more about what you mean for a function to be "approved", and we
>should be able to suggest practical ways to do what you want.
>
>
>  
>
As far as an "approved" function, what I was imagining was something along
the lines of importing modules where all functions are callable such as

approvedlist = dir(mymodule)

which would give a list of names and then going from there.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] drawing squares

2005-09-28 Thread Danny Yoo


> Otherwise, it really looks like you don't care about anything other than
> getting a "right answer", and nothing demotivates a volunteer more than
> being asked to do someone else's homework.  We're interested in helping
> people understand how to solve problems, but we're really not interested
> in doing your homework exercises.

And by homework exercise, I mean Discussion Exercise 3 of Python
Programming: An Introduction to Computer Science:

http://www.fbeedle.com/python/99-6ch05.pdf

So please, please, don't just copy homework questions and submit them to
this Tutor list: we won't help you much if you do only that.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] stopping threads?

2005-09-28 Thread Marcus Goldfish
I'm a little confused about threading in Python.  Here is a sample class I've written for monitoring for events.  Included in the comments are a couple of questions, specifically:
 
   (1) can I use super() in the constructor, or is direct call to base class preferred?
   (2) do I need to sleep in the run() method?  If so, why?  It seems to improve my programs responsiveness
   (3) what happens after run() finishes-- does the thread die, get suspended, go away?  Should I try to force the thread into one of these states, and if so how?
 
Any help is appreciated!
Thanks,
Marcus
 
 
class Monitor(threading.Thread):
   def __init__(self):
  threading.Thread.__init__(self) # would super() also work here?  which is preferred
  self.undetected = True        # presumably, when the event occurs it sets this attribute to False
 
   def run(self):
  print "looking for event"
  while self.undetected is True:
 time.sleep(0.1)    # another minor point: why do I need to sleep here?
  self.processEvent()
  # what happens here-- does the thread die?
 
   def processEvent(self):
  print "yeah-- event detected"
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Flattening multi-dimentional list

2005-09-28 Thread Bernard Lebel
Hello,

I have this list wich is made of tuples. I wish I could "flatten" this
list, that is, to extract each element in the tuples and build a new
flat list with it. Is there any shortcut to do that or do I have to go
through some list comprehension-like procedure?

(I have looked at sets but I have to keep things ordered).


Thanks
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flattening multi-dimentional list

2005-09-28 Thread Danny Yoo


On Wed, 28 Sep 2005, Bernard Lebel wrote:

> I have this list wich is made of tuples. I wish I could "flatten" this
> list, that is, to extract each element in the tuples and build a new
> flat list with it. Is there any shortcut to do that or do I have to go
> through some list comprehension-like procedure?

Here you go:

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

Hope this helps!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flattening multi-dimentional list

2005-09-28 Thread Bernard Lebel
Thanks a lot Danny.


Bernard



On 9/28/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
>
> On Wed, 28 Sep 2005, Bernard Lebel wrote:
>
> > I have this list wich is made of tuples. I wish I could "flatten" this
> > list, that is, to extract each element in the tuples and build a new
> > flat list with it. Is there any shortcut to do that or do I have to go
> > through some list comprehension-like procedure?
>
> Here you go:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363051
>
> Hope this helps!
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with BeautifulSoup

2005-09-28 Thread Bernard Lebel
Hi Kent,

Thanks a lot for that answer. I have had a look at the BS code, and I
have to admit I'm a bit at a loss: how would you add several nestable
tag names in that list?

I tried
NESTABLE_TAGS = BeautifulSoup.buildTagMap( [], 'parameter', 'parameters' )
for example, but I kept having these nesting issues. I fact I have a
whole bunch of tags that I need to make nestable


Thanks
Bernard


On 9/26/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Bernard Lebel wrote:
> > Hi grouchy,
> >
> > I seem to have found the problem. Somehow, it seems BeautifulSoup
> > doesn't like nested tags of the same name.
>
> This seems to be a feature of BS. It seems a bit of a misfeature when applied 
> to XML but anyway...you can configure BS with a set of tags which can be 
> nested, then it will properly parse your data. Here is a short program that 
> shows how:
>
> xml = '''
> 
>   1
> 
> '''
>
> import BeautifulSoup
>
> class NestingParser(BeautifulSoup.BeautifulStoneSoup):
> NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')
>
> soup = NestingParser(xml)
> print soup.prettify()
>
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call a def/class by reference

2005-09-28 Thread bob
At 04:29 PM 9/28/2005, DS wrote:
>What I'm hoping to avoid is an
>explicit reference to any of the called functions within the program.
>By doing it that way, it would avoid a maintenance problem of having to
>remember to put a reference for every new function in the calling program.

Try this - a class in which you define all the functions. The __init__ 
method builds the dictionary.

 >>> class X:
... funcs = {}
... def y(self):
... pass
... def __init__(self):
... for itemname in dir(self):
... if not itemname.startswith('__'):
... item = getattr(self, itemname)
... if callable(item):
... self.funcs[itemname] = item
...
 >>> y = X()
 >>> y.funcs
{'y': >}


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flattening multi-dimentional list

2005-09-28 Thread Kent Johnson
Bernard Lebel wrote:
> Hello,
> 
> I have this list wich is made of tuples. I wish I could "flatten" this
> list, that is, to extract each element in the tuples and build a new
> flat list with it. Is there any shortcut to do that or do I have to go
> through some list comprehension-like procedure?

If the list is just nested one deep and every element is a tuple then a single 
list comprehension will do it:

 >>> l=[(1,2), (3,4)]
 >>> [ x for t in l for x in t ]
[1, 2, 3, 4]

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] stopping threads?

2005-09-28 Thread John Fouhy
On 29/09/05, Marcus Goldfish <[EMAIL PROTECTED]> wrote:
> I'm a little confused about threading in Python.  Here is a sample class
> I've written for monitoring for events.  Included in the comments are a
> couple of questions, specifically:

Hi Marcus,

>(1) can I use super() in the constructor, or is direct call to base class
> preferred?

You can use super() --- in fact, there are some circumstances where it
is prefered: if you have complicated inheritance, super() will do a
better job. Check out this article for details:
http://python.org/2.2.3/descrintro.html

>(2) do I need to sleep in the run() method?  If so, why?  It seems to
> improve my programs responsiveness

Without a sleep(), you are doing what is called "busy waiting". 
Remember, you only have one processor which is only capable of doing
one thing at once.  Without a sleep() call, your program runs
something like this:

#
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
- context switch
do something else
run the user interface
- context switch
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
...etc.
#

But when a thread sleeps, python knows that it can do a context switch
immediately, because the thread isn't going to be using the processor.

#
check self.undetected
 True
sleep
- context switch
do something else
run the user interface
- context switch
check self.undetected
 True
sleep
- context switch
do something else
run the user interface
- context switch
...etc
#

Does that help explain?

>(3) what happens after run() finishes-- does the thread die, get
> suspended, go away?  Should I try to force the thread into one of these
> states, and if so how?

>From the docs:

#
isAlive()
Return whether the thread is alive.

Roughly, a thread is alive from the moment the start() method
returns until its run() method terminates.
#

If you keep a reference to the object, then it will die, but not go
away.  If you don't keep a reference, I imagine it will be garbage
collected once it dies. (I can't quote you docs for that, though)

There's no easy way to tell a thread to stop.  A common technique is
to make the thread check a boolean every time it goes through its
look.

eg:

#
def __init__(self, *etc):
 self.die = False

def run(self):
 while not self.die:
  # do stuff

def stop(self):
 self.die = True
#

HTH!

--
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] stopping threads?

2005-09-28 Thread Pierre Barbier de Reuille
Hello Marcus,

Marcus Goldfish a écrit :
> I'm a little confused about threading in Python. Here is a sample class I've
> written for monitoring for events. Included in the comments are a couple of
> questions, specifically:
>   (1) can I use super() in the constructor, or is direct call to base class
> preferred?

IMO, it is better to explicitely call the base class ... I think it is
more readable. But I don't know if there is any drawback for any solution...

>  (2) do I need to sleep in the run() method? If so, why? It seems to improve
> my programs responsiveness

Yes, you need to sleep ! What you're doing is called "polling", you have
an infinite loop watching some state. If you don't wait, you'll use your
processor 100% for ... nothing ! Global responsiveness will decrease as
your program will always ask the OS for run-time ! Now, if you sleep,
you will test the state once, let other threads/process run and watch
some other time... 0.1 sec is quite a long time for processes and so
short for us ;) So if you need human-time responsiveness, you definitely
need this sleep. However, you may consider other way of
blocking/watching like using events or semaphors. So that your thread
will be blocked until someone releases it by sending the event or
releasing the semaphor.

>  (3) what happens after run() finishes-- does the thread die, get suspended,
> go away? Should I try to force the thread into one of these states, and if
> so how?

Yop ! after run() finishes, the thread dies. This is the normal way to
finish a thread ... just end its main function :)

>  Any help is appreciated!
> Thanks,
> Marcus
>   class Monitor(threading.Thread):
>  def __init__(self):
>  threading.Thread.__init__(self) # would super() also work here? which is
> preferred
>  self.undetected = True # presumably, when the event occurs it sets this
> attribute to False
>   def run(self):
>  print "looking for event"
>  while self.undetected is True:
>  time.sleep(0.1) # another minor point: why do I need to sleep here?
>  self.processEvent()
>  # what happens here-- does the thread die?
>   def processEvent(self):
>  print "yeah-- event detected"
> 
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77fax   : (33) 4 67 61 56 68
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reformatting a one (long) line xml file

2005-09-28 Thread Negroup -
2005/9/28, Christopher Arndt <[EMAIL PROTECTED]>:
[cut]
>
> See http://www.python.org/doc/current/lib/module-xml.dom.minidom.html for more
> info.

Hi, this seems to be exactly what I was looking for!

import sys
from xml.dom import minidom

INDENT = ' ' * 4

file = sys.argv[1]

content = open(file).read()

pretty = minidom.parseString(content).toprettyxml(indent=INDENT).encode('utf-8')
beautiful = open('%s.pretty' % file, 'w')
beautiful.write(pretty)
beautiful.close()

I looked at BeautifulSoup, as Adam suggested. However it seems very
powerful and probably *too* powerful for my actual simple needings.
Anyway I will remember for the future.

> HTH, Chris

Thanks both of you!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor