Re: [Tutor] Grabbing Information from txt files

2010-11-12 Thread Michael
>Random thoughts:
>
>1.) Maybe you should be looking at something like Fuppes instead:
>http://fuppes.ulrich-voelkel.de/ ?
>2.) Even so, continuing with your current direction: there appears to
>be  a
>module/wrapper of MediaInfo for Python, thus removing the need to >scrape
>information from MediaInfo's output, which is what I presume you're >trying
>to do above.  Might be useful.  See here:
>http://forum.doom9.org/showthread.php?t=96516&page=11
>
>Walter

I didn't get Fruppes in any of my original searches, I will give that a
try, and I have tried the module/wrapper for MediaInfo but have to wait
for a bug fix as it does not work correctly with 64bit Linux. At least
not with Python 2.6, and I am reluctant to upgrade to Python 3 due to
compatibility issues.






  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] hitting a wall (not a collision detection question :P)

2009-07-19 Thread Michael
I have virtually no background in programming. I'm currently teaching myself 
python using the following books:

Beginning Python - From Novice to Professional by Magnus Lie Hetland
Beginning Python by Peter Norton et. al.
Making Use of Python by Rashi Gupta
Learning Python  by Mark Lutz

as well as a variety of tutorials I picked up off the web. I'm using v.2.5.2, 
and I'm trying to upgrade to 2.6.2, but I'm running Linux/Ubuntu so the upgrade 
is giving me problems. The main reason I'm not using 3.1 is because all my 
books talk about 2.x.

Ultimately, my goal is to delve into pygame and make some games and maybe some 
multimedia applications. I'd like my first project to be an old-school style 
RPG (e.g. Final Fantasy), as something with such simple graphics and interface 
would be a good benchmark of where I want to go from there.

I've been progressing steadily, until now. At this point, I have a pretty solid 
understanding of strings, integers, tuples, lists, dictionaries, etc. and 
everything up to functions vs. methods and the basics of classes and OOP. This 
is where I'm hitting a wall. It's at this point the all the books go off in 
different directions and I'm not sure a) what I'm learning, b) why I'm learning 
it, and c) how this is going to help me get to my goals. I'm not really even 
understanding much of what these books are talking about at this point anyway. 
It's like a few chapters after "Classes and OOP" were torn out of all of them.

So, I'm just wondering what I should be doing at this point. Sorry for the 
vague question, but I'm pretty lost right now and this is about as specific as 
I can be. Thanks in advance for any help.

Michae



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


[Tutor] German Totorial!?!

2005-01-05 Thread michael
Hello,
Im a German peaople whou would learn Python.

But I cant find a german tutorial.

So you know a German Tutorial?

Daer Michael

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


Re: [Tutor] Need Some Help

2007-08-27 Thread Michael
Hi

I have just taught myself some Python and among my resources were...
http://www.ibiblio.org/obp/thinkCSpy/   - I worked my way through over 
half of this online and downloadable manual
http://www.livewires.org.uk/python/index.html - This course is good, 
I am currently working through this but it is a good idea to have a bit 
of an idea about Python first, hence the previous site.
http://www.freenetpages.co.uk/hp/alan.gauld/   - This looks good, I had 
been meaning to get to it but there are only so many hours...

After that there are heaps of sites with tutorials and downloadable 
programmes for all sorts of specific uses of Python, just do a search.

Michael

chinni wrote:
> Hi All,
>
> I am new to python.i need some help about python.i want to learn 
> python so plz guide me from where can i start.so,that i can learn and 
> under stand quickly.
>
> -- 
> Best Regards,
> M.Srikanth Kumar,
>
> 
>
> ___
> 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] validation

2007-08-27 Thread Michael
Hi

I am fairly new to Python and I wish to validate input. Such as wanting 
to check and make sure that an integer is entered and the program not 
crashing when a naughty user enters a character instead. I have been 
trying to use the Type() function but I cannot work out how to check the 
return value? Caomparing it to 'int' or 'str' isn't working, or should I 
be using the isinstance property? I want to use raw_input and check that 
it is a number. Can someone point me in the right direction?

Thanks

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


Re: [Tutor] validation

2007-08-28 Thread Michael
Thanks Everybody

I now have several methods in my arsenal and they all look quite simple, 
now that I know. Just wondering, when would you use isInstance()?

Thanks

Alan Gauld wrote:
> "Michael" <[EMAIL PROTECTED]> wrote
>
>   
>> to check and make sure that an integer is entered and the program 
>> not
>> crashing when a naughty user enters a character instead.
>> 
>
> John F has already pointed you to the use of try/except for this,
> however...
>
>   
>> trying to use the Type() function but I cannot work out how to check 
>> the
>> return value? Caomparing it to 'int' or 'str' isn't working,
>> 
>
> The easiest way is to compare to another type:
>
> x = 42
> if type(x) == type(int()):
>
> or even
>
> if type(x) == type(2):
>
> Or you can use the types module:
>
> if type(x) == types.IntType
>
> But for your purposes the Python idiom of its 'better to ask
> forgiveness than permission' applies.
>
>
>   

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


[Tutor] interpreted or compiled?

2007-09-12 Thread Michael
Hi

As a new Python user I was curious if you can run Python without the 
environment, ie make it an executable?

Thanks

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


Re: [Tutor] interpreted or compiled?

2007-09-12 Thread Michael
wormwood_3 wrote:
> Michael,
>
> The most common method I know of to do this is py2exe: http://www.py2exe.org/ 
>  This lets you turn scripts into executable Windows programs.
>
> A different, and perhaps better, method is PyInstaller: 
> http://pyinstaller.python-hosting.com/  This creates executables for Windows 
> and Linux.
>
> If you just meant run a script without calling Python, you can add the 
> she-bang line (#!/usr/bin/python as the first line. Change to wherever Python 
> lives on your system), and make the file executable (this is all assuming you 
> are on Linux, sorry). Then you can just do "./mycoolscript.py" and run it.
>
> Hope these help!
>
> -Sam
>
> - Original Message 
> From: Michael <[EMAIL PROTECTED]>
> To: tutor@python.org
> Sent: Wednesday, September 12, 2007 9:58:46 AM
> Subject: [Tutor] interpreted or compiled?
>
> Hi
>
> As a new Python user I was curious if you can run Python without the 
> environment, ie make it an executable?
>
> Thanks
>
> Michael
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

Thanks guys. Amazingly quick response.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Top Programming Languages of 2013

2007-10-08 Thread Michael
I'd guess that by 2013 we'll be using a slightly more graceful, but still
horribly wrong (and unsupported by IE 7.666), redo of HTML, CSS, Javascript,
Flash, and Java with a poorly conceived back-end marriage of PHP + MySQL or
some horrible Microsoft technology for most apps. I'll also venture that as
great as Python is it won't have settled on a really good web development
framework by then because half it's fans want to copy bloat like Ruby on
Rails or .NET and the other half want to be able to develop every line of
code themselves and none of them can agree on a single stable easy-to-use
Pythonic platform. We still won't have a Python-based Javascript replacement
either because nobody can get motivated to replace the crappy client-side
scripting language web developers have come to know and hate.

2013 isn't that far away. A few buzzwords will become boring by then and
we'll mostly be doing what we're doing now.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] repeat

2007-11-16 Thread Michael
Hi All

This has probably been asked before but can I get some clarification on 
why Python does not have a repeat...until statement, and does that mean 
repeat...until is bad practice? I was trying to get Python on the 
standard langauge list for my state secondary school system but they say 
a langauge must have a test last structure in it to be considered.

Thanks

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


[Tutor] classes and the deepcopy function

2008-01-04 Thread Michael
Hi

I was trying to learn about classes in Python and have been playing 
around but I am having a problem with the deepcopy function. I want to 
have a function that returns a clean copy of an object that you can 
change without it changing the original, but no matter what I do the 
original changes as well. Can anyone give ma a pointer?

Thanks
Michael
--
import copy

class point:
"represents a point in 2d space"
x = 0
y = 0
def printpoints(self):
print "x is %g, y is %g" %(self.x, self.y)

class rectangle:
"represents a rectangle"
width = 0
height = 0
corner = point()

def move_rectangle(rect, dx, dy):
rect2 = copy.deepcopy(rect)
rect2.corner.x += dx
rect2.corner.y += dy
return rect2

r1 = rectangle()
r1.width = 20
r1.height = 40
r1.corner.x = 10
r1.corner.y = 10
r2 = move_rectangle(r1,5,2)
print 'Rectangle', r1.width, r1.height
r1.corner.printpoints()
print 'Rectangle 2', r2.width, r2.height
r2.corner.printpoints()



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


Re: [Tutor] classes and the deepcopy function

2008-01-04 Thread Michael
Hi Michael

Thanks for the quick reply, I think I get it. So becuase I did not 
declare them withing the init method using self they are shared by every 
object that is created, even completely brand new ones?

Is it normal practice to declare your variables in a class? I notice 
that you don't have to, you can create them as you go, but i thought 
declaring and initialising them in the class would make it easier to 
understand and see what the class is for and should contain.

Thanks again

Michael

Michael H. Goldwasser wrote:
> Hi Michael,
>
>   This is a very interesting example.  You do indeed have two distinct
>   copies.  The interdependence you are observing is because you have
>   defined CLASS-LEVEL variables (akin to static in Java) rather than
>   instance-level variables. This is because of their declaration
>   within the context of the class definition.
>
>   You should typically initialize instance variables within an
>   __init__ method and using names qualified with self.
>
>   Here is an updated version of your code.  If you still need another
>   explanation of why your previous code executed the way it did, just
>   let me know.
>
> With regard,
> Michael
>
> -
>
> import copy
>
> class point:
> "represents a point in 2d space"
> def __init__(self):
> self.x = 0
> self.y = 0
>
> def printpoints(self):
> print "x is %g, y is %g" %(self.x, self.y)
>
> class rectangle:
> "represents a rectangle"
> def __init__(self):
> self.width = 0
> self.height = 0
> self.corner = point()
>
> def move_rectangle(rect, dx, dy):
> rect2 = copy.deepcopy(rect)
> rect2.corner.x += dx
> rect2.corner.y += dy
> return rect2
>
> r1 = rectangle()
> r1.width = 20
> r1.height = 40
> r1.corner.x = 10
> r1.corner.y = 10
> r2 = move_rectangle(r1,5,2)
> print 'Rectangle', r1.width, r1.height
> r1.corner.printpoints()
> print 'Rectangle 2', r2.width, r2.height
> r2.corner.printpoints()
>
>
>
>
>
> On Saturday January 5, 2008, Michael wrote: 
>
>   
>>Hi
>>
>>I was trying to learn about classes in Python and have been playing 
>>around but I am having a problem with the deepcopy function. I want to 
>>have a function that returns a clean copy of an object that you can 
>>change without it changing the original, but no matter what I do the 
>>original changes as well. Can anyone give ma a pointer?
>>
>>Thanks
>>Michael
>>--
>>import copy
>>
>>class point:
>>"represents a point in 2d space"
>>x = 0
>>y = 0
>>def printpoints(self):
>>print "x is %g, y is %g" %(self.x, self.y)
>>
>>class rectangle:
>>"represents a rectangle"
>>width = 0
>>height = 0
>>corner = point()
>>
>>def move_rectangle(rect, dx, dy):
>>rect2 = copy.deepcopy(rect)
>>rect2.corner.x += dx
>>rect2.corner.y += dy
>>return rect2
>>
>>r1 = rectangle()
>>r1.width = 20
>>r1.height = 40
>>r1.corner.x = 10
>>r1.corner.y = 10
>>r2 = move_rectangle(r1,5,2)
>>print 'Rectangle', r1.width, r1.height
>>r1.corner.printpoints()
>>print 'Rectangle 2', r2.width, r2.height
>>r2.corner.printpoints()
>> 
>
>
>   

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


Re: [Tutor] classes and the deepcopy function

2008-01-06 Thread Michael
Okay

Just when I think I am getting it you throw this in. So why does a 
become local to each variable but b seem global?

Michael

bob gailer wrote:
> Michael wrote:
>> Hi Michael
>>
>> Thanks for the quick reply, I think I get it. So becuase I did not 
>> declare them withing the init method using self they are shared by 
>> every object that is created, even completely brand new ones?
>>
>> Is it normal practice to declare your variables in a class? I notice 
>> that you don't have to, you can create them as you go, but i thought 
>> declaring and initialising them in the class would make it easier to 
>> understand and see what the class is for and should contain.
> And now for the rest of the story:
>
> class Foo:
>  a = 0
>  b = []
>
> f = Foo()
> f.a = 3
> f.b.append(1)
>
> g = Foo()
> g.a = 4
> g.b.append(2)
>
> print f.a, g.a # 3 4
> print f.b, g.b # [1, 2] [1, 2]
>
> [snip]
>

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


[Tutor] processing a text file w/ OO?

2006-01-22 Thread Michael
Hi.

I'm processing a tab-delimited text file where I read in a file,  
perform a bunch of operations on the items, and then write them out  
again to a fixed-width text file.

I've been doing this with a very functional approach:

- loop over lines
- read line into dictionary
- process dictionary values ( format phone numbers and dates and  
amounts, etc.)
- pad dictionary values with spaces
- write dictionary values out to file

Anyway, this all works fine. Not knowing much about OO, I'm wondering  
if there's a way to approach this from an object-oriented  
perspective. Is there anything to be gained? Or is this type of  
problem best tackled with a functional approach?

TIA.

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


Re: [Tutor] processing a text file w/ OO?

2006-01-23 Thread Michael
Thanks, Alan. That's exactly the kind of explanation I was looking  
for. As this is pretty much a one-off project and the data  
transformations are pretty different for each field, I'll stick with  
the functional approach. The rule of thumb you mention is useful,  
too. I hadn't heard that before.

On Jan 23, 2006, at 2:53 AM, Alan Gauld wrote:

>> I'm processing a tab-delimited text file where I read in a file,   
>> perform a bunch of operations on the items, and then write them  
>> out  again to a fixed-width text file.
>> I've been doing this with a very functional approach:
>> Anyway, this all works fine. Not knowing much about OO, I'm  
>> wondering  if there's a way to approach this from an object- 
>> oriented  perspective. Is there anything to be gained? Or is this  
>> type of  problem best tackled with a functional approach?
>
> This is one of the types of problem where I personally don't try to  
> use objects too much. Where objects might be helpful is if you have  
> a number of similar but slightly different data records such that  
> the processing consists of lots of if/elif chains. In that case  
> identifying the type once and relying on polymorphism to deal with  
> the differences is useful. But if the records all have similar  
> processing then OOP will make the code bulkier, slower and not add  
> too much IMHO.
>
> OTOH if you were to write a lot of these kinds of applications OOP  
> might provide a higher level of code reuse between projects But  
> remember that the cost of reuse means that you need to reuse code 3 
> (*) or more times to make it economical!
>
> (*) Metrics suggest the actual figure varies between 3-10 times  
> depending on language, object complexity and level of generality.
>
> 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] Decorators

2006-04-11 Thread Michael
On Tuesday 11 April 2006 17:43, Alan Gauld wrote:
> >> There is no practical use for decorators IMHO
> >
> > It's true that decorators are syntactic sugar and don't add any new
> > functional capabilities to the language.
>
> Which is all I intended to imply.

You have a different meaning of "practical use" from common usage then. 
Something that makes it easier to:
   * Understand that a function has been modified
   * Make it clear that a function is a staticmethod/classmethod/etc *right at
  the beginning of a function* without having to read the entire body.
   * Reduce typing
   * Allow hinting of types for integration with tools like PyObjC
   * Make it clear when reading the definition of a method/function is
  memoised, traced etc
   * Simplifying augmentation of generators with arbitrary extra
  communications attributes.

... are all practical benefits. That means they have practical use in my
book :-)

Syntactic sugar *IS* a practical benefit. After all, every language above 
assember is syntactic sugar, and by your definition of no practical use.


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


Re: [Tutor] unit testing raw_input()

2006-04-18 Thread Michael
On Tuesday 18 April 2006 23:34, Andre Roberge wrote:
> Hi all-
>
> Suppose I had a function like the following:
>
> [ function that interacts with the outside world ]
...
> How could I go about to write an automated test for it?

You create a mock for raw_input, put the above code inside a module and rebind 
raw_input in the module before calling your function.

ie:
(CONTENTS of y_n.py)
def y_n(prompt="Answer yes or no"):
while True:
answer = raw_input(prompt)
if answer in ['y', 'Y', 'yes']:
print "You said yes!"
break
elif answer in ['n', 'N', 'no']:
print "You said no!"
break
else:
print "%s is an invalid answer."%answer
(END CONTENTS of y_n.py)

You can even create and test a mock in the command line interpreter, so here's 
a quick example:

>>> import y_n   # Import the module 
>>> def raw_input_mock(prompt): # create a mock
... return "y"
...
>>> y_n.raw_input = raw_input_mock  # rebind the name inside the module
>>> y_n.y_n() # Run, this now calls our mock instead of the real raw_input
You said yes!

To my mind this is generally useful for testing error conditions with complex 
modules (select & socket spring to mind).

To do this properly with your module, it makes more sense for your function
to return strings, which would allow you to directly test the result.
Alternatively you could wrap print in a function and then mock that instead.

The key thing about a mock is that it simply provides the results you want. If 
it's important *how* the mock was called (eg you're testing correct use of a 
library), your mock could append parameters to a list for later comparision.

Eg
>>> mocktrace = []
>>> def raw_input_mock(prompt): # create a mock
... mocktrace.append((prompt,))
... return "y"
...

As I say though, this sort of thing is (IME) often more about testing the 
correct usage of something.

Regards,


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


Re: [Tutor] Offtopic observation

2006-06-07 Thread Michael
On Wednesday 07 June 2006 17:55, doug shawhan wrote:
> This marks the third time this week I have been typing in a question for
> the group, and have made the answer apparent just by trying to explain my
> question clearly.
>
> This suggests that either I think better in text, or Proust was onto
> something ... but then again, I majored in english.

It's also called confessional debugging :-)

It's also something that actually tends to apply outside programming as well. 
The act of understanding the problem often leads to a solution :-)


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


Re: [Tutor] Functional Programming

2006-07-06 Thread Michael
On Friday 07 July 2006 00:39, Terry Carroll wrote:
> Neither of these is particularly directed to Python, though.

Also, much as I like python, it's not really suited to functional programming
approaches, given recursion isn't tail optimised, lambda is by comparison
crippled, some aspects of pythons approach to closures aren't as robust as
I'd like, mutablity of values, and things like currying aren't as simple as
they could be.

That said, functional programming is fun, and these days probably the best
introductions are either SML books or Haskell.

I also think that having an understanding of functional programming will 
generally improve someone's code, but I would suggest that learning the ideas 
in a language where functional programming is the norm rather the exception 
is a good idea. The come back to python, and learn to undo your recursive 
instincts!


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


[Tutor] directory traversal help

2008-07-03 Thread Michael

Hi

I have modified an algorithm from the think like a python programmer 
book for traversing folders and printing the files in those folders. It 
works for my original purposes but I have a students that wants to use 
it to run from a root folder, problem is that it crashes on the 
recycling bin as well as hidden and other types of folders. Is there a 
way to modify it to skip folders that would make it crash? I have tried 
using exception handling (try) and other functions in the os module but 
I cannot work it out. Any ideas? thanks


Michael

import os
import string

def walk(dir):
   for name in os.listdir(dir):
   path = os.path.join(dir,name)
   if os.path.isfile(path):
   beg = string.rfind(path,'\Student')
   end = len(path)
   filename = path[beg:end]
   #print "___ ",filename
   print "___ ",name

   else:
   print path
   walk (path)

cwd = os.getcwd()
walk(cwd)

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


Re: [Tutor] directory traversal help

2008-07-06 Thread Michael
Further to this query I actually hit the manuals and found that their 
already was a walk function. My final solution was thus...
Please note it is heavily commented because I am a teacher and created 
this for a student :-)


# Will create a listing in a file called dirlist.txt of all the files in 
all

# the directories of the directory it is started from.

import os   # imports all the functions in the os module (operating 
system functions)


cwd = os.getcwd()   # gets the current working directory and places it 
in the variable cwd


myfile=open("dirlist.txt","w")  # creates the file dirlist.txt ready for 
writing using the variable myfiles


# the walk function returns the current directory in root, the 
directories in dirs
# and the files in root in files. By using the for loop it traverses 
every folder

# from the starting folder.

for root, dirs, files in os.walk(cwd):
  myfile.write(root + "\n")   # writes to dirlist.txt the current 
directory name
  for thefiles in files:  # will iterate all the files in the 
current directory
  myfile.write("___ " + thefiles + "\n") # writes the 
filename to dirlist.txt. the


myfile.close() # Cleanly saves and closes the file dirlist.txt




# Note: the "\n" in the write lines adds the newline character so that 
the next write starts on a newline

Hi

I have modified an algorithm from the think like a python programmer 
book for traversing folders and printing the files in those folders. 
It works for my original purposes but I have a students that wants to 
use it to run from a root folder, problem is that it crashes on the 
recycling bin as well as hidden and other types of folders. Is there a 
way to modify it to skip folders that would make it crash? I have 
tried using exception handling (try) and other functions in the os 
module but I cannot work it out. Any ideas? thanks


Michael

import os
import string

def walk(dir):
   for name in os.listdir(dir):
   path = os.path.join(dir,name)
   if os.path.isfile(path):
   beg = string.rfind(path,'\Student')
   end = len(path)
   filename = path[beg:end]
   #print "___ ",filename
   print "___ ",name

   else:
   print path
   walk (path)

cwd = os.getcwd()
walk(cwd)

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



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


Just Because (Was: Re: [Tutor] Global presets ?)

2004-12-05 Thread Patric Michael
<>

Folks...

I originally discovered this list while searching Google for the 
mathematical expression to convert yards to inches.  Seems someone 
already did it in a python function.  (I think maybe it was Kent?)

At any rate, I subscribed to the list out of curiosity, partly because I like 
python (even the math challenged like me can manage it!) and because 
I am nowhere near fluent with it.

And I stay with the list, partly because the folks who frequent it are by 
and large quite friendly, and because there are always little tidbits like 
the one below:
 
> I avoid this by using the
>   import examplemodule as em

How many times have I clobbered a namespace while trying to save a 
bit of time typing...  Yeesh!

So, while most everyone here is better suited to make replies, let me 
just say "Thanks!" to everyone who takes the time to read, and 
especially to those who respond to the wide variety of questions we 
post.

Thanks!

Patric


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-08 Thread Michael Janssen
[forgot to cc to the list]


-- Forwarded message --
From: Michael Janssen <[EMAIL PROTECTED]>
Date: Wed, 8 Dec 2004 14:40:46 +0100
Subject: Re: [Tutor] MemoryError
To: Liam Clarke <[EMAIL PROTECTED]>


On Wed, 8 Dec 2004 23:29:38 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:

> I'm playing with a file, and attempting to replace a section with a
> string, and using the following command -
>
> seg=codeSt[element:endInd+len(endStr]
> codeSt=codeSt.replace(seg, hrefString)
>
> At the replace, I get a MemoryError. It's part of a for loop, but it
> gives the error the first time around.

Hello Liam,

You might try to narrow the code in where the error happen. Read the
file and replace a dummy-seq-string and see what happens. Does this
work:

"test string".replace("st st", "?")

When it works, what is bad with your file? Consider asking
comp.lang.python for a greater audience.

BTW: some time past the base64 module (base64 is a mail attachment
encoding) has a bug leading to a MemoryError when undecoding an empty
base64 string. Any free GB of ram did not help.

You can allways work arround the replace:

new = old[:start] + relace_string + old[end:]

which is ugly but perhaps makes your script running.

regards
Michael
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CGI Video collection application File I/O troubles

2004-12-09 Thread Patric Michael
<>
 
> Sorry for the delay but I was busy with soemthing else.
> The script prints the values of the variables fine in the
> browser so there must be a problem with the file writing part.
> When I run the script from my bash shell it creates the videodb
> database file, but when I run it from the browser it doesn't
> create no file whatsoever.
> At first I ran the script as a regular user and then I tried
> as root, I don't understand how the scripts writes the file
> from the shell when I am root but produces no output when
> I run it from the browser(as root also).

Just out of curiosity, does the directory where the file is to be written 
have write permission for others?

Since the server (hopefully!) isnt running as root, not only the 
destination file, but the directory where it is stored must have 
permissions to allow everyone (or at least the user the server is running 
as) to write there in the first place.

Also, did you check your webservers error log?

Patric


> > >
> > >
> > You know.  I that is what happened to me once.  I could not for the
> > life of me figure it out.  I just chmod 777 it.
> >
> 
> 
> 
> --
> The lady on the call box in Monkey Island 2
> Guybrush: I'm lost in the Inky Island Jungle in Monkey 2
> Lady: Just walk off the edge of the screen
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Array slices in python with negative step

2010-01-11 Thread Michael Sprayberry
> > Hello All,
> >
> > I am bit confuse how the slice works in case a negative step is
supplied
> > a = 'abcde'
> > a[::-1] gives me edcba
> >
> > but [4:0:-1] gives me edcb
> >
> > while searching net I came accross something which said the
following:
> >
> > If a negative stride is specified and the starting or stopping
indices
> are
> > omitted, they default to ``end of axis'' and ``beginning of axis''
> > respectively.
> > In my case 4 is end of axis and 0 is begining of the axis so a[::-1]
> should
> > be equivalent to [4:0:-1] but result which I get in both the cases
does
> not
> > validate.
>
> Your interpretation is wrong. In your case, 4 is start index, 0 is end
> index (as obviously shown by the result you get). Step -1 lets you
step
> backwards, but this does not change the fact that the end-index is the
> second argument of the slice, right? Now, python work with
(right-side)
> half-open intervals, meaning that the second border is excluded
(s[0:4]
> would return "abcd"). Which means in your case you won't get a[0] in
the
> result.

Hope I'm clear... It can be a bit misleading at start but, as it's
> consistent, once you get used to it all works fine ;-)
>

 Thanks for your response but I am still not clear; can you show me the
equivalent of [::-1]  in terms actually specifying start-index,
end-index
which gives me reverse of the given arrary.

Dennis,

I hope this clears up your question.

a[begin index: end index: step]
a = ['a','b','c','d','e']
there are 5 indexes 0 through 4
if you 
a[4:0:-1]
a = ['e','d','c','b'] because you stopped at index 0 but did not include
it
a[::-1] uses the last index going back to and including index 0
as the following example shows
>>> a =[1,2,3,4,5,6]
>>> b = a[5:0:-1]
>>> b
[6, 5, 4, 3, 2]
>>> b = a[5:-1:-1]
>>> b
[]
>>> a
[1, 2, 3, 4, 5, 6]
>>> b = a[5::-1]
>>> b
[6, 5, 4, 3, 2, 1]
>>> 

Like I said I hope that clears it up a little

Michael

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ipython, PYTHONPATH, on a MAC

2010-02-16 Thread Michael Fourman
If you start Python from command line you can just use usual bash methods

put


PYTHONPATH= xxx

in ~/.profile

or for use in a single shell

export PYTHONPATH=xxx

If you start Python from a dbl-clickable application you need to get the 
PYTHONPATH into the application's environment

See

http://mactip.blogspot.com/2004/04/setting-environment-variables.html

Hope this helps,

michael


On 16 Feb 2010, at 15:46, John [H2O] wrote:

> 
> Hello,
> 
> I'm not a Mac user, but I'm a promoter of Python! I have a good friend using
> a Mac who's becoming sceptical of python due to frustrations with the
> PYTHONPATH. I'm trying to help...
> 
> Everything is fine running vanilla python. Importing modules works fine. But
> in ipython, the module paths need to be appended individually. I can't even
> set a module directory into which ipython will look recursively for modules.
> 
> There is nothing custom set in .ipython/ipythonrc or ipy_user_conf.py
> 
> The PYTHONPATH variable doesn't need to be set using vanilla python. The
> path settings are set somehow, however (I can see this from import sys;
> sys.path). I'm not sure where this is all happening.
> 
> Any ideas on the best way to set the PYTHONPATH for a mac?
> 
> Thanks!
> -- 
> View this message in context: 
> http://old.nabble.com/ipython%2C-PYTHONPATH%2C-on-a-MAC-tp27610302p27610302.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 

Professor Michael Fourman FBCS CITP
Director, iDEA lab
Informatics Forum
10 Crichton Street
Edinburgh
EH8 9AB 
http://idea.ed.ac.uk/
twitter @iDEAatEd
For diary appointments contact :
mdunlop2(at)ed-dot-ac-dot-uk
+44 131 650 2690

The University of Edinburgh is a charitable body, registered in Scotland, with 
registration number SC005336.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] NLTK needs YAML?

2010-04-23 Thread Michael Scharf
Dear Friends,

I'm new to the list, and new to Python.  The last time I've tried
anything like the below was 20 years ago on a NeXT machine, and I had
no clue what I was doing then, either.

I've gotten IDLE up and have done some hello worlding.

I am now trying to get the NLTK working on my new iMac running OS X
10.6.3.  The Python version I have up is 2.6.5.  (There may be a
slightly older pre-install with faulty IDLE lingering somewhere on the
machine.)

I've installed Macports, and through it I installed NLTK by saying

$ sudo port install nltk

which worked.

But when, in a Python session, I try to

>>> import nltk
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named nltk

is what I get.

Macports says if that happens that I should

$ cd /tmp/nltk-installer

which works.  And that I should then

$ sudo python setup.py install

Traceback (most recent call last):
  File "setup.py", line 13, in 
import nltk
  File "/private/tmp/nltk-installer/nltk/__init__.py", line 92, in 
from yamltags import *
  File "/private/tmp/nltk-installer/nltk/yamltags.py", line 1, in 
import yaml
ImportError: No module named yaml

So I did this:

$ port search yaml

And got:

libyaml @0.1.3 (devel)
A YAML Parser.

p5-data-phrasebook-loader-yaml @0.09 (perl)
Abstract your queries ... with YAML!

p5-test-yaml-meta @0.15 (perl)
Validation of the META.yml file in a distribution.

p5-test-yaml-valid @0.04 (perl)
Test for valid YAML

p5-yaml @0.68 (perl)
YAML loader/dumper module

p5-yaml-libyaml @0.32 (perl)
Perl YAML Serialization using XS and libyaml

p5-yaml-syck @0.99 (perl)
A fast, lightweight YAML loader and dumper

p5-yaml-tiny @1.41 (perl)
Read/Write YAML files with as little code as possible

py-yaml @3.05 (python, devel)
YAML 1.1 parser and emitter for Python

py25-yaml @3.08 (python, devel)
YAML 1.1 parser and emitter for Python

py26-yaml @3.08 (python, devel)
YAML 1.1 parser and emitter for Python

rb-bee @0.5.1 (ruby, devel)
Bee is a build tool running YAML files

syck @0.55 (textproc, devel)
An extension for reading and writing YAML

yaml-mode.el @0.0.3 (editors)
An emacs major mode for editing yaml files.

Found 14 ports.

So I then did:

$ sudo port install py26-yaml
--->  Computing dependencies for py26-yaml
--->  Cleaning py26-yaml

closed and re-opened the terminal, and tried it all again.

But I still get the same

ImportError: No module named yaml

So my question is: do I really not have what I need here?  Or is it a
question of  something not finding something that's there?  Maybe I'm
using the wrong name somewhere?  Or??

Many thanks,
Mike S.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Exception Handling and Stack traces

2010-09-10 Thread Michael Powe
Hello,

I can't work out how to suppress stacktrace printing when exceptions
are thrown.

I want the thrown exception to pass a message on the console, just
like Java does when I catch an exception and print e.getMessage().

I tried some of the examples of controlling traceback through the
traceback module.

I have to admit, this is one of the cases where I wonder why it has to
be made so bloody complicated.  The other day, I read an article by
Guido in which he was proposing to remove 'map' and 'filter' from the
language because he though the developer shouldn't have to think too
much about using them.  But the exception handling is so non-intuitive
that the time saved from not having to think about using 'map' is
spent instead on trying to figure out how to promote a message to the
commandline when a method fails.

It seems that exceptions automatically are thrown up, so even if I put
a 'try/except' clause in a method; when that method fails, the
exception will still be thrown up to the top of the call chain.  So,
there seems to be no reason whatever to catch an exception in any
method except the top caller (i.e., 'main').  

Example:

def getData(auth) :
# create opener with auth headers here
try :
data = opener.open(url)
except urllib2.URLError("Badly formed URL") :
formatted_lines = traceback.format_exc().splitlines()
print formatted_lines[0]
print formatted_lines[-1]
sys.exit(1)
return data

This method is called by another method, printOutput(), which
processes the return data (XML from web service).

That method is called in main:

[printOutput(w) for w in weeks]

All I want to see is that if the exception is thrown in getData(), the
message is printed to stdout and the script exits.  Instead, I get the
stacktrace printed back down from main, I don't get the exception
handled in getData (i.e., the error message and exit).

Now, I'm sure somebody is going to explain to me why it's so
unreasonable to think that I ought to be able to get an error message
from e.getMessage() and a stacktrace from e.printStacktrace() and that
I ought to be able to choose between the two.  Because, it seems that
python is determined that I should have a stacktrace whether I want
one or not.

Sorry, I'm more than a little annoyed because even the example of
using the traceback module from the python docs does not provide the
handling that it is supposed to; and I really think this level of
complexity for handling exceptions cleanly is just unwarranted.  I
need to be able to give this script to someone who will want to be
able to read the error output without having to be a Python programmer
experienced in reading stack traces.  e.g. a "Badly formed URL"
message that tells them they set up the parameters for connecting to
the web service incorrectly.

Hopefully, you can get past the rant and help me solve this problem.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA

"The secret to strong security: less reliance on secrets."
-- Whitfield Diffie


pgpQKpff9ycFv.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception Handling and Stack traces

2010-09-10 Thread Michael Powe
On Fri, Sep 10, 2010 at 03:56:51PM +0200, Peter Otten wrote:
> Michael Powe wrote:
> 
> > I can't work out how to suppress stacktrace printing when exceptions
> > are thrown.
> 
> [snip rant]
> 
> It might have been a good idea to read a tutorial like
> 
> http://docs.python.org/tutorial/errors.html#handling-exceptions
 
> or ask before you got annoyed enough to write that rant ;)

Hello,

Thanks for the reply.  Stupid me, I just read a half dozen articles on
the web about python exception handling, including some at
docs.python.  At no point is the 'as' clause discussed as being
required.

Note that in section 8.3 of that article, the statement is made that
if the exception matches the the exception type in the following
format, the statements within the except clause are executed.

except URLError :
   # do something

That in fact, seems to me to be incorrect.  It is not my experience
(e.g., print statements are not executed in the example I gave and the
sys.exit() is not called).

I'll follow up on your suggestions.  I appreciate the help.

Thanks.

mp
 
> To catch an exception you have to put the class into the except clause, not 
> an instance. Basic example, using 2.6 syntax:
> 
> WRONG:
> 
> >>> try:
> ... 1/0
> ... except ZeroDivisionError("whatever"):
> ... print "caught"
> ...
> Traceback (most recent call last):
>   File "", line 2, in 
> ZeroDivisionError: integer division or modulo by zero
> 
> CORRECT:
> 
> >>> try:
> ... 1/0
> ... except ZeroDivisionError as e:
> ... print "caught", e
> ...
> caught integer division or modulo by zero
> 
> Peter
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"...we built a new continent in cyberspace where we could go live and be
free. And the nice thing is that, because we built it, we didn't have
to steal it from aboriginal peoples. It was completely empty, and we
invite everyone to live there with us. No immigration restrictions.
There's room for everyone in the world. Come live in the free world
and be free. That's our idea."  -- Richard Stallman


pgpnp3PNLKdQk.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception Handling and Stack traces

2010-09-10 Thread Michael Powe
On Fri, Sep 10, 2010 at 03:50:57PM +0200, Evert Rol wrote:

> This is a bit of a guess, but as far as I know, you can catch exceptions like 
> that. 
> Try:
 
> try:
> data = opener.open(url)
> except urllib2.URLError as msg:
> print msg
> sys.exit(1)
 
> If you're using an older version of Python, you'll need:
> 
> try:
> data = opener.open(url)
> except urllib2.URLError, msg:
> print msg
> sys.exit(1)
 
> In your example, you are *creating* an exception (but doing nothing
> with it; I have no idea what happens if you have a line like "except
> ". Perhaps it tries to compare one on one with
> that instance, but if it compares by id, that will not work).  In
> this way, you're not catching the exception. So, it will be pass
> your except clause, and just do what it always does: print the whole
> exception's traceback. Which is probably what you're seeing.

Hello,

Thanks for the reply.  As I indicated in the other message I just
wrote, the format I used is one I took straight from the
documentation. Of course, there may be assumptions in the documented
examples that I am not aware of.

It looks like you and Peter have pulled me out of the ditch and for
that I am grateful.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
It could have been an organically based disturbance of the brain --
perhaps a tumor or a metabolic deficiency -- but after a thorough
neurological exam it was determined that Byron was simply a jerk.  
-- Jeff Jahnke, runner-up, Bulwer-Lytton contest


pgpGqEYPwKKjY.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception Handling and Stack traces

2010-09-10 Thread Michael Powe
On Fri, Sep 10, 2010 at 04:42:35PM +0200, Peter Otten wrote:
> Michael Powe wrote:
 
> > On Fri, Sep 10, 2010 at 03:56:51PM +0200, Peter Otten wrote:
> >> Michael Powe wrote:

> >> > I can't work out how to suppress stacktrace printing when exceptions
> >> > are thrown.
 
> >> WRONG:
> >> 
> >> >>> try:
> >> ... 1/0
> >> ... except ZeroDivisionError("whatever"):
> >> ... print "caught"
> >> ...
> >> Traceback (most recent call last):
> >>   File "", line 2, in 
> >> ZeroDivisionError: integer division or modulo by zero
> >> 
> >> CORRECT:
> >> 
> >> >>> try:
> >> ... 1/0
> >> ... except ZeroDivisionError as e:
> >> ... print "caught", e
> >> ...
> >> caught integer division or modulo by zero
 
> > Note that in section 8.3 of that article, the statement is made that
> > if the exception matches the the exception type in the following
> > format, the statements within the except clause are executed.
> > 
> > except URLError :
> > # do something
> > 
> > That in fact, seems to me to be incorrect.  It is not my experience
> > (e.g., print statements are not executed in the example I gave and the
> > sys.exit() is not called).
 
> Sorry, the as-clause is *not* necessary. The relevant difference between the 
> correct and the wrong approach is that you must not instantiate the 
> exception:
 
> WRONG:
> 
> >>> try:
> ... 1/0
> ... except ZeroDivisionError("whatever"):
> ... print "caught"
> ...
> Traceback (most recent call last):
>   File "", line 2, in 
> ZeroDivisionError: integer division or modulo by zero
 
> CORRECT:
> 
> >>> try:
> ... 1/0
> ... except ZeroDivisionError:
> ... print "caught"
> ...
> caught
> 
> I just put in the as-clause to show an easy way to print the exception. I 
> did not anticipate that it would obscure the message.

Hello,

No problem, I am working on getting this sorted out.  The
documentation seems to be written as reminder for people who already
know how this stuff works, rather than as a clear explanation for
anybody working with it.

Eventually, I arrived at a workable conclusion by wrapping only the
call in main and using your suggested 'as' clause.  This successfully
suppresses the traceback and gives a useable error message.  Although,
in the case of URLError, 'getaddrinfo failed' may not actually mean
much to the end user, it'll have to do.

I don't like the fact that I cannot locate my thrown exception at the
point of throwing -- i.e., I don't necessarily mind catching the
exception in main but I would like to be able to print out exactly
where the exception occurred.  This is more useful when
troubleshooting. However, an entire stacktrace is unacceptably
verbose.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA


It's easier to fight for one's principles than to live up to them.


pgpQdf9CtsOF9.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trapping HTTP Authentication Failure

2010-09-10 Thread Michael Powe
Hello,

My script to call a web service authenticates.  I would like to be
able to trap an exception if the authentication fails.  The script
loops over a list of dates and I don't want it to retry for every
element in the list.  This could take a long time and be very annoying
when, after the long wait, a stacktrace spews out of the last attempt.
The assumption is that if it fails, it is not a transient network or
some other issue but that the credentials themselves are faulty.

Now, the authentication header is sent with the initial request, so it
does not look to me like the standard process of request, get a 401
and then re-request with credentials is relevant.  However, clearly
the opener issues a number of retries after the initial failure.

But, I don't see a mechanism in urllib2 for taking notice of a failure
and acting on it.

Can somebody point me toward a solution?

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA

"And I'd be a Libertarian, if they weren't all a bunch of tax-dodging
professional whiners." -- Berke Breathed


pgptBq2mUrmnN.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trapping HTTP Authentication Failure

2010-09-11 Thread Michael Powe
On Sat, Sep 11, 2010 at 01:28:26AM +0200, Evert Rol wrote:
> > My script to call a web service authenticates.  
 
> Sorry, but where is the (full) script? I missed an attachment or (preferably) 
> a link.

Hello,

Sorry, the verb of the sentence is "authenticates," as in, "My script
... authenticates."

But I can show the authentication portion.

8<-- start >8

# Creates an authentication object with the credentials for a given URL
def createPasswordManager(headers) :
passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
passwordManager.add_password(None,overview_url,headers[0],headers[1])
return passwordManager

# Creates an authentication handler for the authentication object created above
def createAuthenticationHandler(passwordManager) :
authenticationHandler = urllib2.HTTPBasicAuthHandler(passwordManager)
return authenticationHandler

# Creates an opener that sets the credentials in the Request
def createOpener(authHandler) :
return urllib2.build_opener(authHandler)


# Retrieves the data
def getData(authHeaders) :
opener = 
createOpener(createAuthenticationHandler(createPasswordManager(authHeaders)))
data = opener.open(overview_url)
return data
8<--- end >8

So, to restate the question, how can I trap an exception in the cases
in which authentication fails? 

Right now, the whole script is complete and working (thanks for your
help with my other exception-handling question).  Except for the case
of bad credentials.  The use case is that the user misspells a
username or password or puts in a wrong account information.  Then, I
don't want them to sit for 10 minutes while the script makes 30 data
connections, retries and fails each time.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
I hate a fellow whom pride, or cowardice, or laziness drives into a
corner, and who does nothing when he is there but sit and ; let
him come out as I do, and . -- Samuel Johnson


pgpaSYEIaSF3p.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trapping HTTP Authentication Failure

2010-09-11 Thread Michael Powe
On Sat, Sep 11, 2010 at 01:09:31PM +0200, Evert Rol wrote:

> >>> My script to call a web service authenticates.  
> > 
> >> Sorry, but where is the (full) script? I missed an attachment or 
> >> (preferably) a link.
> > 
> > Hello,
> > 
> > Sorry, the verb of the sentence is "authenticates," as in, "My script
> > ... authenticates."
> 
> Sorry, misread that.
> Although code does help :-). 

> I assume the rest of the code is just the loop around the items you
> want to fetch, calling getData each time with a new URL.

Yes, it's looping over a list.  Specifically, at startup the script
does a date detection and creates a list of identifiers for each week
of the year up to the point of invocation.  So, if it is week 36, I
get a list of 36 weeks.

Then, the data retrieval and processing takes place like this:

[processData(w) for w in weeks]

Where the processData function calls getData() and passes in the
current week to process.

[ code snipped ]
 
> > So, to restate the question, how can I trap an exception in the cases
> > in which authentication fails? 

[ snip ]
 
> I'm not sure what you're exactly doing here, or what you're getting,
>but I did get curious and dug around urllib2.py. Apparently, there is
>a hardcoded 5 retries before the authentication really fails. So any
>stack trace would be the normal stack trace times 5. Not the 30 you
>mentioned, but annoying enough anyway (I don't see how it would fail
>for every element in the loop though. Once it raises an exception,
>the program basically ends).

It never throws an exception.  Or, if it does, something about the way
I'm calling suppresses it.  IOW, I can put in a bogus credential and
start the script and sit here for 5 minutes and see nothing.  Then ^C
and I get a huge stacktrace that shows the repeated calls.  After the
timeout on one element in the list, it goes to the next element, times
out, goes to the next.

> I don't know why it's hard-coded that way, and not just an option
> with a default of 5, but that's currently how it is (maybe someone
> else on this list knows?).

I don't know, but even if I could set it to 1, I'm not helped unless
there's a way for me to make it throw an exception and exit the loop. 

> If that's what you're finding, perhaps the quickest way is to
> subclass urllib2.HTTPBasicAuthHandler, and override the
> http_error_auth_reqed method (essentially keeping it exactly the
> same apart from the hard-coded 5).

Now there's a challenge!  ;-)

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA


Is it time for your medication or mine?


pgpCntmjOvEx8.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trapping HTTP Authentication Failure

2010-09-11 Thread Michael Powe
On Sat, Sep 11, 2010 at 02:25:24PM +0200, Evert Rol wrote:
> 
 
> >> I'm not sure what you're exactly doing here, or what you're getting,
> >> but I did get curious and dug around urllib2.py. Apparently, there is
> >> a hardcoded 5 retries before the authentication really fails. So any
> >> stack trace would be the normal stack trace times 5. Not the 30 you
> >> mentioned, but annoying enough anyway (I don't see how it would fail
> >> for every element in the loop though. Once it raises an exception,
> >> the program basically ends).

> > It never throws an exception.  Or, if it does, something about the way
> > I'm calling suppresses it.  IOW, I can put in a bogus credential and
> > start the script and sit here for 5 minutes and see nothing.  Then ^C
> > and I get a huge stacktrace that shows the repeated calls.  After the
> > timeout on one element in the list, it goes to the next element, times
> > out, goes to the next.
 
> Ok, now I had to try and recreate something myself. So my processData is:
 
> def processData(f):
>global overview_url
>overview_url = baseurl + f
>getData(authHeaders)
> 
> (f being a filename, out of a list of many). Other code same as yours.
 
> It definitely throws a 401 exception after 5 retries. No time-outs,
> no long waits. In fact, a time-out would to me indicate another
> problem (it still should throw an exception, though). So, unless
> you're catching the exception in processData somehow, I don't see
> where things could go wrong.

> I assume you have no problem with correct credentials or simply
> using a webbrowser?

Hello,

Yes, I can retrieve data without any problem.  I can break the URL and
generate a 404 exception that is trapped and I can break it in other
ways that generate other types of exceptions.  And trap them.

I went back and looked at the code in urllib2.py and I see the
timeout counter and that it raises an HTTPError after 5 tries.  But I
don't get anything back.  If I just let the code run to completion, I
get sent back to the prompt.  I put a try/catch in the method and I
already have one on the call in main.

 
 
> >> I don't know why it's hard-coded that way, and not just an option
> >> with a default of 5, but that's currently how it is (maybe someone
> >> else on this list knows?).
> > 
> > I don't know, but even if I could set it to 1, I'm not helped unless
> > there's a way for me to make it throw an exception and exit the loop. 

Actually, there's a comment in the code about why it is set to 5 --
it's arbitrary, and allows for the Password Manager to prompt for
credentials while not letting the request be reissued until 'recursion
depth is exceeded.'

I guess I'll have to go back to ground zero and write a stub to
generate the error and then build back up to where it disappears.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
It turns out that it will be easier to simply block the top offenders
manually; the rules for pattern matching are too arcane, obscure, and
difficult to program. -- t. pascal, comp.mail.misc, "procmail to
filter spam"


pgpPHQmwJIOGq.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trapping HTTP Authentication Failure

2010-09-11 Thread Michael Powe
On Sat, Sep 11, 2010 at 10:48:13AM -0400, Michael Powe wrote:
> On Sat, Sep 11, 2010 at 02:25:24PM +0200, Evert Rol wrote:
> > 
>  
> > >> I'm not sure what you're exactly doing here, or what you're getting,
> > >> but I did get curious and dug around urllib2.py. Apparently, there is
> > >> a hardcoded 5 retries before the authentication really fails. So any
> > >> stack trace would be the normal stack trace times 5. Not the 30 you
> > >> mentioned, but annoying enough anyway (I don't see how it would fail
> > >> for every element in the loop though. Once it raises an exception,
> > >> the program basically ends).
 
> > > It never throws an exception.  Or, if it does, something about the way
> > > I'm calling suppresses it.  IOW, I can put in a bogus credential and
> > > start the script and sit here for 5 minutes and see nothing.  Then ^C
> > > and I get a huge stacktrace that shows the repeated calls.  After the
> > > timeout on one element in the list, it goes to the next element, times
> > > out, goes to the next.

Hello,

More experimentation revealed that one problem was testing the script
in Idle.  Idle does something to suppress the script failure for that
particular case (IOW, it correctly returns HTTPError for things like
'404' and URLError for things like a bad domain name).

When I run the script from the command line (cmd), it actually ignores
the '5' retry limit, seemingly.  I added another catch block:

except Exception as e:
   print "exception: ",e

That prints out "exception: maximum recursion depth exceeded."

I wonder if there is something hinky in Windows that is causing this
to happen.

Thanks.

mp
  
> > Ok, now I had to try and recreate something myself. So my processData is:
>  
> > def processData(f):
> >global overview_url
> >overview_url = baseurl + f
> >getData(authHeaders)
> > 
> > (f being a filename, out of a list of many). Other code same as yours.
>  
> > It definitely throws a 401 exception after 5 retries. No time-outs,
> > no long waits. In fact, a time-out would to me indicate another
> > problem (it still should throw an exception, though). So, unless
> > you're catching the exception in processData somehow, I don't see
> > where things could go wrong.
> 
> > I assume you have no problem with correct credentials or simply
> > using a webbrowser?
> 
> Hello,
> 
> Yes, I can retrieve data without any problem.  I can break the URL and
> generate a 404 exception that is trapped and I can break it in other
> ways that generate other types of exceptions.  And trap them.
> 
> I went back and looked at the code in urllib2.py and I see the
> timeout counter and that it raises an HTTPError after 5 tries.  But I
> don't get anything back.  If I just let the code run to completion, I
> get sent back to the prompt.  I put a try/catch in the method and I
> already have one on the call in main.
> 
>  
>  
> > >> I don't know why it's hard-coded that way, and not just an option
> > >> with a default of 5, but that's currently how it is (maybe someone
> > >> else on this list knows?).
> > > 
> > > I don't know, but even if I could set it to 1, I'm not helped unless
> > > there's a way for me to make it throw an exception and exit the loop. 
> 
> Actually, there's a comment in the code about why it is set to 5 --
> it's arbitrary, and allows for the Password Manager to prompt for
> credentials while not letting the request be reissued until 'recursion
> depth is exceeded.'
> 
> I guess I'll have to go back to ground zero and write a stub to
> generate the error and then build back up to where it disappears.
> 
> Thanks.
> 
> mp
> 
> -- 
> Michael Powe  mich...@trollope.orgNaugatuck CT USA
> It turns out that it will be easier to simply block the top offenders
> manually; the rules for pattern matching are too arcane, obscure, and
> difficult to program. -- t. pascal, comp.mail.misc, "procmail to
> filter spam"



> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
I hate a fellow whom pride, or cowardice, or laziness drives into a
corner, and who does nothing when he is there but sit and ; let
him come out as I do, and . -- Samuel Johnson


pgplLqVty92Am.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] SOLVED: Re: Trapping HTTP Authentication Failure

2010-09-11 Thread Michael Powe
Hello,

It is bloody Winblows.  The script works as designed and traps the 401
exception on my slackware box ... something in the implementation of
urllib2 on Windoze is broken.  This has to be a known issue.  Just did
not see it known anywhere.

Thanks.

mp

On Sat, Sep 11, 2010 at 02:16:07PM -0400, Michael Powe wrote:
> On Sat, Sep 11, 2010 at 10:48:13AM -0400, Michael Powe wrote:
> > On Sat, Sep 11, 2010 at 02:25:24PM +0200, Evert Rol wrote:
> > > 
> >  
> > > >> I'm not sure what you're exactly doing here, or what you're getting,
> > > >> but I did get curious and dug around urllib2.py. Apparently, there is
> > > >> a hardcoded 5 retries before the authentication really fails. So any
> > > >> stack trace would be the normal stack trace times 5. Not the 30 you
> > > >> mentioned, but annoying enough anyway (I don't see how it would fail
> > > >> for every element in the loop though. Once it raises an exception,
> > > >> the program basically ends).
>  
> > > > It never throws an exception.  Or, if it does, something about the way
> > > > I'm calling suppresses it.  IOW, I can put in a bogus credential and
> > > > start the script and sit here for 5 minutes and see nothing.  Then ^C
> > > > and I get a huge stacktrace that shows the repeated calls.  After the
> > > > timeout on one element in the list, it goes to the next element, times
> > > > out, goes to the next.
> 
> Hello,
> 
> More experimentation revealed that one problem was testing the script
> in Idle.  Idle does something to suppress the script failure for that
> particular case (IOW, it correctly returns HTTPError for things like
> '404' and URLError for things like a bad domain name).
> 
> When I run the script from the command line (cmd), it actually ignores
> the '5' retry limit, seemingly.  I added another catch block:
> 
> except Exception as e:
>  print "exception: ",e
> 
> That prints out "exception: maximum recursion depth exceeded."
> 
> I wonder if there is something hinky in Windows that is causing this
> to happen.
> 
> Thanks.
> 
> mp
>   
> > > Ok, now I had to try and recreate something myself. So my processData is:
> >  
> > > def processData(f):
> > >global overview_url
> > >overview_url = baseurl + f
> > >getData(authHeaders)
> > > 
> > > (f being a filename, out of a list of many). Other code same as yours.
> >  
> > > It definitely throws a 401 exception after 5 retries. No time-outs,
> > > no long waits. In fact, a time-out would to me indicate another
> > > problem (it still should throw an exception, though). So, unless
> > > you're catching the exception in processData somehow, I don't see
> > > where things could go wrong.
> > 
> > > I assume you have no problem with correct credentials or simply
> > > using a webbrowser?
> > 
> > Hello,
> > 
> > Yes, I can retrieve data without any problem.  I can break the URL and
> > generate a 404 exception that is trapped and I can break it in other
> > ways that generate other types of exceptions.  And trap them.
> > 
> > I went back and looked at the code in urllib2.py and I see the
> > timeout counter and that it raises an HTTPError after 5 tries.  But I
> > don't get anything back.  If I just let the code run to completion, I
> > get sent back to the prompt.  I put a try/catch in the method and I
> > already have one on the call in main.
> > 
> >  
> >  
> > > >> I don't know why it's hard-coded that way, and not just an option
> > > >> with a default of 5, but that's currently how it is (maybe someone
> > > >> else on this list knows?).
> > > > 
> > > > I don't know, but even if I could set it to 1, I'm not helped unless
> > > > there's a way for me to make it throw an exception and exit the loop. 
> > 
> > Actually, there's a comment in the code about why it is set to 5 --
> > it's arbitrary, and allows for the Password Manager to prompt for
> > credentials while not letting the request be reissued until 'recursion
> > depth is exceeded.'
> > 
> > I guess I'll have to go back to ground zero and write a stub to
> > generate the error and then build back up to where it disappears.
> > 
> > Thanks.
> > 
> > mp
> > 
> > -- 
> > Michael Powem

[Tutor] Documenting a Module

2010-09-13 Thread Michael Powe
Hello,

Are there any tools for documenting a module other than Sphinx? 

Apparently, I need a full-blown dev box with Visual Studio installed
to get Sphinx up, due to the dependency on Jinja, which comes
source-only and requires VC. 

I wrote a module, I'd like to produce a decent document of its
functionality from the comments and doc strings; and I already wasted
a considerable part of my Sunday afternoon trying to get along with
Sphinx. I'm not talking about a huge Python project, nor am I likely
to need that type of documentation tool in the near future.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA


Is it time for your medication or mine?


pgpbJeRok4c8e.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wierd replace problem

2010-09-13 Thread Michael Powe
Hello,

In your script, you need to escape each backslash, in order to have it
come out correctly to the interpreter.  IOW, in the shell, '\\' is
what is being processed.  But in your script, you want to send '\\' to
the shell, and in order to do that, you have to escape each backslash,
or ''.  

In a script, '\\' means 'send through a backslash' for shell
processing. The left-most backslash is escaping the one to its right. 

Thanks.

mp

On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:
> 
> Hello, 
> 
> I have this string called test with the contents of 'het is een wonder \\TIS'
> 
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS' 
> So that's right.
> 
> Now I try the same in a IDE with this programm :
>  
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
> line2 = line.replace ("\\","")
> line3 = line2.lower()
> woorden = line3.split()
> for letter in woorden:
> letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items 
>  
> But now Im gettting this output :
>  
> [('"\'tis', 1), 
>  
> Why does the \ stays here. It should have gone as the test in the python 
> prompt says.
>  
> Roelof
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"...we built a new continent in cyberspace where we could go live and be
free. And the nice thing is that, because we built it, we didn't have
to steal it from aboriginal peoples. It was completely empty, and we
invite everyone to live there with us. No immigration restrictions.
There's room for everyone in the world. Come live in the free world
and be free. That's our idea."  -- Richard Stallman


pgpW0enXO7mqW.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Documenting a Module

2010-09-13 Thread Michael Powe
On Mon, Sep 13, 2010 at 12:03:27PM +0200, r...@schoenian-online.de wrote:
> 
> Hi Michael,
> ??
> I can recommend epydoc. You can find it here:
> ??http://epydoc.sourceforge.net/??It's a nice tool and you should have no 
> problems
> with the installation.
> ??
> Ralf
> ??
> ??
> ??

Thank you, much appreciated.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA


47.3% of all statistics are made up on the spot. - Steven Wright


pgpZzxvhgS3f7.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wierd replace problem

2010-09-13 Thread Michael Powe
On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:
> 
> Hello, 
> 
> I have this string called test with the contents of 'het is een wonder \\TIS'
> 
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS' 
> So that's right.
> 
> Now I try the same in a IDE with this programm :
>  
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
> line2 = line.replace ("\\","")
> line3 = line2.lower()
> woorden = line3.split()
> for letter in woorden:
> letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items 
>  
> But now Im gettting this output :
>  
> [('"\'tis', 1), 
>  
> Why does the \ stays here. It should have gone as the test in the python 
> prompt says.

Hello,

Actually, on closer look I can see the answer.

The original text must look something like this:

\\"'tis the season to be jolly," said santa.

When you run your process against a string in that format, you get the
output shown: ('"\'tis', 1).  The appearance of the backslash is
fortuitous.  It has nothing to do with the string.replace(), it's
there to escape the single quote, which is appearing in the middle of
a single-quoted string.  IF the double-quote had not also been there,
python would have replaced the outer quotes with double quotes, as it
does on my system before I got to thinking about that lonely double
quote.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"I wrote what I did because as a woman, as a mother, I was oppressed
and brokenhearted with the sorrows and injustice I saw, because as a
Christian I felt the dishonor to Christianity, -- because as a lover
of my country, I trembled at the coming day of wrath." -- H.B. Stowe


pgpvaJk6H7T5x.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Documenting a Module

2010-09-13 Thread Michael Powe
On Mon, Sep 13, 2010 at 12:03:27PM +0200, r...@schoenian-online.de wrote:
> 
> Hi Michael,

> I can recommend epydoc. You can find it here:
> ??http://epydoc.sourceforge.net/??It's a nice tool and you should
> have no problems with the installation.

> Ralf

Hello,

I just want to follow up that epydoc is completely awesome and exactly
the right tool for the job.  I was able to get my doc generated and
wrapped up nicely in less time than I spent trying to get Sphinx
installed yesterday.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
I hate a fellow whom pride, or cowardice, or laziness drives into a
corner, and who does nothing when he is there but sit and ; let
him come out as I do, and . -- Samuel Johnson


pgpJwZcQZEZ6N.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] A Plea for Sensible Quoting

2010-09-14 Thread Michael Powe
Hello,

I read this list in a linux console using mutt. I dunno, maybe I'm the
only idiot left still using a console mail client.  I write my emails
and email replies in emacs, too, which may make me even weirder.

Few elements make a mail harder to read than 130 lines of nested
quoting, into which has been inserted 3 or 5 lines of comment.  Mutt
does a good job of identifying the quote nesting and highlighting the
quoted material; and I can use the `T' command to remove the quoting.
But sometimes, "context" in the sense of what was being replied to is
useful.  When a thread reponse is quoting 3 other respondents plus the
OP, "context" turns into "what everybody is saying," which is more
like standing in a crowded train terminal, where everybody is
shouting, than having a quiet, private conversation among 4 people.
Then, I have to page down four screens to find the 5 lines of new
comment, and try to figure out what portion of that three-level-nested
dialog that preceeds it was the trigger for the response.

Just a plea to remember to take the time to `C-k' or `dd' or whatever
is required to get that extraneous material out of the mail.  A little
formatting goes a long way.

Thanks.

mp



-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
Fun experiments:
  Get a can of shaving cream, throw it in a freezer for about a week.
  Then take it out, peel the metal off and put it where you want...
  bedroom, car, etc.  As it thaws, it expands an unbelievable amount.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] re.findall parentheses problem

2010-09-14 Thread Michael Scharf
Hi all,

I have a regex that matches dates in various formats.  I've tested the regex
in a reliable testbed, and it seems to match what I want (dates in formats
like "1 Jan 2010" and "January 1, 2010" and also "January 2008").  It's just
that using re.findall with it is giving me weird output.  I'm using Python
2.6.5 here, and I've put in line breaks for clarity's sake:

>>> import re

>>> date_regex =
re.compile(r"([0-3]?[0-9])?((\s*)|(\t*))((Jan\.?u?a?r?y?)|(Feb\.?r?u?a?r?y?)|(Mar\.?c?h?)|(Apr\.?i?l?)|(May)|(Jun[e.]?)|(Jul[y.]?)|(Aug\.?u?s?t?)|(Sep[t.]?\.?e?m?b?e?r?)|(Oct\.?o?b?e?r?)|(Nov\.?e?m?b?e?r?)|(Dec\.?e?m?b?e?r?))((\s*)|(\t*))(2?0?[0-3]?[0-9]\,?)?((\s*)|(\t*))(2?0?[01][0-9])")

>>> test_output = re.findall(date_regex, 'January 1, 2008')

>>> print test_output
[('', '', '', '', 'January', 'January', '', '', '', '', '', '', '', '', '',
'', '', ' ', ' ', '', '20', '', '', '', '08')]

>>> test_output = re.findall(date_regex, 'January 1, 2008')

>>> print test_output
[('', '', '', '', 'January', 'January', '', '', '', '', '', '', '', '', '',
'', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008')]

>>> test_output = re.findall(date_regex, "The date was January 1, 2008.  But
it was not January 2, 2008.")

>>> print test_output
[('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '',
'', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), ('', ' ', ' ', '',
'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ',
'', '2,', ' ', ' ', '', '2008')]

A friend says: " I think that the problem is that every time that you have a
parenthesis you get an output. Maybe there is a way to suppress this."

My friend's explanation speaks to the empties, but maybe not to the two
Januaries.  Either way, what I want is for re.finall, or some other re
method that perhaps I haven't properly explored, to return the matches and
just the matches.

I've read the documentation, googled various permutations etc, and I can't
figure it out.  Any help much appreciated.

Thanks,
Mike
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] re.findall parentheses problem

2010-09-14 Thread Michael Scharf
Hi Evert,

Thank you.  I should have figured "groups" were the paren groups.  I see it
clearly now.  And your solution will work for the larger thing I'm trying to
do --- thanks.

And yes: I know this matches some non-date-like dates, but the data is such
that it should work out ok.

Thanks again,
Mike



> This will also match '1 Janry 2010'.
> Not sure if it should?
>
>
> > A friend says: " I think that the problem is that every time that you
> have a parenthesis you get an output. Maybe there is a way to suppress
> this."
> >
>
The docs say: " If one or more groups are present in the pattern, return a
> list of groups". So your friend is right.
>
> In fact, your last example shows exactly this: it shows a list of two
> tuples. The tuples contain individual group matches, the two list elements
> are your two date matches.
> You could solve this by grouping the entire regex (so r"(([0-3 
> [0-9]))" ; I would even use a named group), and then picking out the first
> tuple element of each list element:
> [(' January 1, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '',
> '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'),
> (' January 2, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '',
> '', '', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')]
>
>
> Hth,
>
>  Evert
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] re.findall parentheses problem

2010-09-14 Thread Michael Powe
On Tue, Sep 14, 2010 at 01:09:21PM -0400, Michael Scharf wrote:

> Thank you.  I should have figured "groups" were the paren groups.  I see it
> clearly now.  And your solution will work for the larger thing I'm trying to
> do --- thanks.
 
> And yes: I know this matches some non-date-like dates, but the data is such
> that it should work out ok.

Hello,

I second the advice to use named groups.  This option makes it sooo
much easier to retrieve your captures; especially, if you have nested
groups. No more working out if the capture you want is in group 1 or
group 3.  Just matcher.group('January').

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"We had pierced the veneer of outside things.  We had `suffered,
starved, and triumphed, groveled down yet grasped at glory, grown
bigger in the bigness of the whole.'  We had seen God in his
splendors, heard the text that Nature renders.  We had reached the
naked soul of man." -- Sir Ernest Shackleton, 


pgpCawppq4rj0.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Regex comments

2010-09-16 Thread Michael Powe
 Hello,

The re module includes the option to comment a regular expression with
the syntax (?#comment).  e.g.

p=r'(.*) (?PWT.dl)(?#parameter)=(?P[^&]+)(?#value).*'

Is there a mechanism for extracting these values from the match, in
the way that group names are extracted?

I don't see one.

The point would be that in my processing of the match, I could
implement the comments as identifiers for the matched value.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"The most likely way for the world to be destroyed, most experts
agree, is by accident.  That's where we come in. We're computer
professionals. We cause accidents."  -- Nathaniel Borenstein, inventor
of MIME


pgpPf9G6Q0dBX.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regex comments

2010-09-16 Thread Michael Powe
On Thu, Sep 16, 2010 at 01:31:09PM +0200, Peter Otten wrote:
> Michael Powe wrote:
 
> > The re module includes the option to comment a regular expression with
> > the syntax (?#comment).  e.g.

> > Is there a mechanism for extracting these values from the match, in
> > the way that group names are extracted?

> > I don't see one.
 
> You could write a regular expression to extract them ;)

;-)
 
> > The point would be that in my processing of the match, I could
> > implement the comments as identifiers for the matched value.
> 
> But that's what the names are for, e. g.:
> 
> >>> re.compile(r'(.*) (?PWT.dl)=(?P[^&]+).*').search(
> " WTxdl=yadda&ignored").groupdict()
> {'parameter': 'WTxdl', 'value': 'yadda'}

That's right, I forgot about the dictionary.  Thanks!

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"No provision in our Constitution ought to be dearer to man than that
which protects the rights of conscience against the enterprises of the
civil authority." -- Thomas Jefferson to New London Methodists,
1809. ME 16:332


pgpH7zLFLwttx.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "Overloading" methods

2010-09-16 Thread Michael Powe
Hello,

Strictly speaking, this isn't overloading a method in the way we do it
in Java.  But similar.  Maybe.

I am writing a module for processing web server log files and one of
the methods I provide is to extract a given query parameter and its
value. Because there are several types of log files with different
line structures, I had the thought to write methods with descriptive
names that simply returned a generic method that processed the method
arguments. e.g.,

def setpattern_iis(self,pattern,parameter) :
type='iis'
return pattern_generator(self,type,pattern,parameter)

In this case, creating a regular expression to parse the log lines for
a query parameter.

This is just a bit more "self documenting" than using the generic
method with the 'type' argument and requiring the user to enter the
type.  At the same time, it allows me to put all the parsing code in
one method.

My question is, is this a bad thing to do in python?

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
War is a sociological safety valve that cleverly diverts popular
hatred for the ruling classes into a happy occasion to mutilate or
kill foreign enemies. - Ernest Becker


pgp4F5gOWmvX7.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Comparing two lists

2010-09-16 Thread Michael Powe
Hello,

I have two lists.

alist = ['label', 'guid']

blist = ['column0label', 'column1label', 'dimension0guid',
'description', 'columnid'] 

I want to iterate over blist and extract the items that match my
substrings in alist; alternatively, throw out the items that aren't in
alist (but, I've had bad experiences removing items from lists "in
place," so I tend toward the "copy" motif.)

In real life, blist column entries could have embedded column numbers
from 0 to 19.

I can do this with excrutiatingly painful 'for' loops.  Looking for
something more efficient and elegant.  

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA

"The secret to strong security: less reliance on secrets."
-- Whitfield Diffie


pgpbadqbDTubZ.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Comparing two lists

2010-09-16 Thread Michael Powe
On Thu, Sep 16, 2010 at 12:59:08PM -0600, Vince Spicer wrote:
> On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer  wrote:

> > On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe wrote:

> >> alist = ['label', 'guid']

> >> blist = ['column0label', 'column1label', 'dimension0guid',
> >> 'description', 'columnid']
> >>
> >> I want to iterate over blist and extract the items that match my
> >> substrings in alist; alternatively, throw out the items that aren't in
> >> alist (but, I've had bad experiences removing items from lists "in
> >> place," so I tend toward the "copy" motif.)

> > One solution is to use list comprehensions.

> > newlist = [x for x in blist if [a for a in alist if a in x]]

> > This works, although there may be more efficient ways to accomplish this

> On major speed up is to make a simple filter that returns as soon as a match
> is found instead of
> completing the loop every element in alist
 
> def filter_(x, against):
> for a in against:
> if a in x:
> return True
> return False
> 
> newlist = [x for x in blist if filter_(x, alist)]

Hello,

Very cool, thanks.

I've used list comprehensions before but I just couldn't get the
structure right this time, for some reason.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"No provision in our Constitution ought to be dearer to man than that
which protects the rights of conscience against the enterprises of the
civil authority." -- Thomas Jefferson to New London Methodists,
1809. ME 16:332


pgp9X5ry33hg8.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Comparing two lists

2010-09-16 Thread Michael Powe
On Thu, Sep 16, 2010 at 12:59:08PM -0600, Vince Spicer wrote:
> On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer  wrote:

> > On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe wrote:

> >> I have two lists.

> >> alist = ['label', 'guid']
> >>
> >> blist = ['column0label', 'column1label', 'dimension0guid',
> >> 'description', 'columnid']

> >> I want to iterate over blist and extract the items that match my
> >> substrings in alist; alternatively, throw out the items that aren't in
> >> alist (but, I've had bad experiences removing items from lists "in
> >> place," so I tend toward the "copy" motif.)

> On major speed up is to make a simple filter that returns as soon as
> a match is found instead of completing the loop every element in
> alist

> def filter_(x, against):
> for a in against:
> if a in x:
> return True
> return False

Hello,

Totally awesome.  I actually have a dictionary, with the key being an
ini file header and the value being one of these lists of ini
settings.  With your method, I am able to loop through the dictionary,
and expunge the unwanted settings.

I knew there had to be a way to take advantage of the fact that the 'i
in s' object test acts like a substring test for strings.  

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA

'Unless we approve your idea, it will not be permitted, it will not be
allowed.'  -- Hilary Rosen, President, RIAA


pgprtToq26Kft.pgp
Description: PGP signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Why are arguments sometimes on the left side?

2010-09-20 Thread Michael Scharf
Hi,


Why is it



   list0.extend(list1)



and not


   extend(list 0, list1)



or


   stri0 = stri0.strip()


and not


   stri0 = strip(stri0)



Why have arguments on the left side at all, when usually the dot notation
left to right implies a hierarchical relation: file.class or class.method
etc.



I googled this, but didn’t find it.



Thank you,

Mike
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why are arguments sometimes on the left side?

2010-09-20 Thread Michael Scharf
Okay, we now have a dog named Fluffy, which is just one instance of
> our dog class. With the way you would want to do things, I would have
> to say
> bark(f)
> But what is bark? Where is it defined? You can see it is in the dog
> class, but Python cannot; you passed a dog instance to bark(), but
> that will not tell Python to search in the dog class to find the bark
> method. Saying
> f.bark()
> will work since it tells Python:
> take this instance of dog, called f, and call its bark method. The
> bark method is in the dog class since bark is being called on a dog
> object (remember that an object is just an instance of a class).
> I hope this made some sense. 



This is terrific --- very clarifying.  Thank you so much.

Mike
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Grabbing Info from Text files?

2010-11-12 Thread Michael Stover
Hello,
I have been getting lost when trying to find the needed information on how to 
grab information from text files to be used in a python script I am working on. 
Essentially the script is calling upon other programs to grab specific 
information about files and putting that information into basic text files. 
When 
I say basic I mean basic, each piece of information has its own line such as:
InfoOne=?
InfoTwo=?
Where the ? is a value ranging from 1 character up to 5 (usually numbers), and 
it is the value I represented with ? that I need to grab. I am hoping it is 
possible to grab 1 line at a time so variables can be set for use later in my 
script.
I have tried to "decipher" the python documents on this, but honestly, being a 
dabbler in python I am getting "lost, dazed and confused" as friends would put 
it.
Thankfully this is not for any homework assignments, it is merely a script I am 
working on for making some repetitive tasks more automated, such as grabbing 
information about video files, and if needed convert them. I have yet to find a 
program that does what I am aiming for so I started creating a python script 
(as 
python is already installed on my Linux distro). It just seems to have become 
more complicated that I had hoped, but I am at a point now were I do not want 
to 
leave it unfinished. If an example of my script is needed I am more than 
willing 
to provide it for clarification of what I am trying to do.
Thanks,
Mike



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Grabbing Information from txt files

2010-11-12 Thread Michael Stover
My apologies for my last email, admittedly I was more tired that I thought as 
after re-reading it and the emails coming in, I found that I did not provided 
"proper" information.

1. I have a script that is detecting multiple various bits of information of a 
video file using MediaInfo and putting that information into a txt file with 
the 
format of:
(Example:)
num_vid_track=?
num_aud_track=?
num_sub_track=?

Granted that is only part of the information being obtained but it's all in the 
same format.
I have been trying multiple ways of grabbing this information for re-use, 
including using this snippet, suggested to me by fellow users of the #python 
irc 
channel..

import shlex as shlex_
from subprocess import Popen, PIPE

def shell(args, input=None, stdout=PIPE, stderr=PIPE, shlex=False, **kwargs):
"""Gets the output of a command run in a subprocess.

Arguments:
args:   A sequence of strings, or a single string if shlex=True.
input:  A string to be written to the process's stdin.
Any extra keyword arguments are forwarded to Popen.

Returns:
A tuple of (stdout, stderr)

>>> shell('basename /a/hello', shlex=True)
('hello\n','')
"""
if shlex:
args = shlex_.split(args)
stdin = PIPE if input is not None else None
p = Popen(args, stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
return p.communicate(input=input)

Then using a command line similar to:
p = subprocess.Popen(['foo', 'bar'], stdout=subprocess.PIPE); stdout, _ = 
p.communicate()

Where 'foo','bar' obviously is the program I am calling with its arguements. 
The 
only issue is, I can barely understand the documentation I kept getting pointed 
to for retrieving the information captured from stdout. Which is why I went 
with 
another friends suggestion of outputting all of the information to a text file. 
Sorry if this seems to have veered off course, but which method would be more 
recommended to implement? So far I have been able to write a different python 
script for a general conversion of videos from multiple different formats to a 
single format my xbox 360 can read (with or without is optional media update).

Again sorry for my previous email, and thank you in advance for the assistance 
and suggestions,
Mike



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2009-03-17 Thread Michael Connors
So the extent of your effort is "Would anyone know how to Ctrl+c".
That deserves an award.

2009/3/17 Jared White 

> Would anyone know how to Write an application that displays the following
> patterns separately, one below the other. Use for or while loops to generate
> the patterns. All asterisks (*) should be printed by a single statement of
> print( '*' ); which causes the asterisks to print side by side. A statement
> of println(\n); can be used to move to the next line.
> *
> **
> ***
> 
> *
> **
> ***
> 
> *
> **
>
> **
> *
> 
> ***
> **
> *
> 
> ***
> **
> *
> dukelx2...@gmail.com
>
> _______
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] Executing a C Program from RH Linux in Python for Win

2009-03-20 Thread Michael Farnham

On Fri, 2009-03-20 at 04:35 -0700, Wayne Watson wrote:
> Good. Thanks.
> 
> Here's my code.
> ==
> # Executing a Linux program under Win XP
> from subprocess import call
> myProg = call(["C:\Sandia_Meteors\Various\FuzzyLogic\wolf", "-h"])


If I understand your question - A C program which runs in Linux
cannot run in Microsoft Windows without being recompiled. I know
that many of the people who have replied in this thread know this
so maybe I misunderstood the question.

HTH
Mike


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


[Tutor] Parsing Question

2009-05-09 Thread Michael Morrissey
Forgive me if I'm asking something stupid, but I'm not sure how to do this
(there are so many options in Python, I'm overwhelmed and confused). I have
a text file that looks like this:
1 the 126 name
2 of 127 very
3 to 128 through
4 and 129 just
5 a 130 form
6 in 131 much
7 is 132 great
etc...

Each has 2 numbers and 2 words on it. Each number is related to the word
that comes after it. So "1" and "the" are connected (kinda like a
dictionary), and "126" and "name" are related.

Using the above text file as an input, I'm trying to make an output that
lists all the words, one word per line, but none of the numbers. I was
hoping to get the words listed in order of their related numbers. So, the
output needs to look like:

the
of
to
 (skip to the 127th line)
very
through
just

I can open and loop over the text, I'm just not sure what commands I should
use to parse each line. Can anyone give me suggestions or examples?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Best Python Editor

2009-06-14 Thread Michael Powe
On Sun, Jun 14, 2009 at 12:53:19PM -0700, Emile van Sebille wrote:

> On 6/14/2009 8:04 AM Alan Gauld said...
> >"Tom Green"  wrote

> >>Since VIM seems to be the editor of choice and I have been programming in
> >>Python for many years using Pyscripter and Eclipse I was wondering how I
> >>could transition away from the IDE world to VIM.

> >With great difficulty and to be honest I wouyldn't bother.
> >If you are used to eclipse then there is little to be gained from moving 
> >to vim.

> Seconded.  Editors are a personal choice and often the loss of 
> productivity while learning a new environment isn't worth it.  My 
> introduction to coding Turbo Pascal was eased owing to the WordStar 
> compatible/modeled editor it used.  Nowadays, any editor with 
> configurable syntax capability is sufficient.  It's all personal 
> preference after that.

It's good to see so much common sense prevailing on this topic.  An
IDE such as eclipse or VS really only becomes a necessity for
productivity when (a) you are dealing with multiple code files and
proper compilation and linking and so forth becomes complicated; or
(b) you are working in a language with which you are not as familiar
as you should like to be, and autocompletion because a real asset.

However, I will say that while following this thread, it occurred to
me that the one feature that VS and even the VBA editor in MS Office
has, is the ability to pop you into the debugger on error.  This
feature is so useful that it surprises me nobody else seems to do it.
Most often, simply the ability to jump to the error line is provided
and I suppose that must be generally acceptable.

Thanks.

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


Re: [Tutor] Best Python Editor

2009-06-15 Thread Michael Connors
Back when I used Windows I used this: http://www.crimsoneditor.com/

I think its not being developed anymore, but it is a great editor/IDE that
supports many languages.

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


Re: [Tutor] Best Python Editor

2009-06-15 Thread Michael Powe
On Mon, Jun 15, 2009 at 06:30:50AM -0700, johnf wrote:
> On Sunday 14 June 2009 07:31:53 pm Michael Powe wrote:

> > However, I will say that while following this thread, it occurred to
> > me that the one feature that VS and even the VBA editor in MS Office
> > has, is the ability to pop you into the debugger on error.  This
> > feature is so useful that it surprises me nobody else seems to do it.
> > Most often, simply the ability to jump to the error line is provided
> > and I suppose that must be generally acceptable.

> Wing does.  When error occurs it stops on the line and the programmer is 
> working in the debugger.

Hello,

I'll have to look at that.  

I have a kind of collection of editors -- the way I collect books, I
guess.  TextPad, vbsEdit, UltraEdit, SciTE, XmlCopyEditor, EditPlus,
emacs.  I never do anything with vi except munge conf files.

For actual "projects" I use VS and NetBeans.  When I get on a "back to
basics" kick, I re-enter emacs.  It used to be a joke about emacs not
being an editor but an operating system.  There is nothing on the
linux side that even comes close, IMO.  I don't like GUI-based stuff,
though, so right off, any editor built on the assumption that I'm a
mouse-oriented user is right out.

Thanks.

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


Re: [Tutor] Best Python Editor

2009-06-15 Thread Michael Powe
On Mon, Jun 15, 2009 at 06:34:04AM -0700, Emile van Sebille wrote:
> On 6/15/2009 2:49 AM Tom Green said...

> >Yes, vim or any text editor is suitable for Python, but I 
> >prefer having a nice GUI interface while coding.  I mean the automobile 
> >replaced the horse and buggy, while they both get you to your 
> >destination I would still rather travel in a car.

> Anyone know of any studies comparing text based vs GUI IDE based code 
> development?  As I recall, programming productivity is measured in 
> LOC/day and last time I noticed it seemed to be a very small number.

> I'm wondering if there might be documented benefits to migrating from my 
> horse and buggy.  :)

Are you in a hurry to get somewhere?  ;-)

I recently worked on a module for a large existing Java application.
The module I wrote had to be plugged in to the existing code base.  So
of course, I had to have all kinds of tie-ins to existing libraries
and classes.  First, I couldn't run the full application, so I had to
rely on unit testing to verify my functionality.  Second, I had to
connect to hundreds of classes inside the application.  I'm not that
smart -- I could not have done it without NetBeans, which has
fantastic introspection and can tell me most of the ways I'm violating
protocol while I'm working.  

I stubbed out a lot of stuff and prototyped in jEdit.  But when it was
game on, I had to go to NB.  It probably comes down to, How much stuff
can you carry in your head?

Thanks.

mp

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


[Tutor] Generating Deck Combinations

2009-06-20 Thread Michael Morrissey
I need to generate all possible deck combinations given two different lists
as input.

The Input:

List 1 has Card names listed inside it.
List 2 has Maximum Quantities for each Card name.

For example:

List1[0] would be: "Aether Vial"
List2[0] would be: "4"

List1[1] would be: "Mountain"
List2[1] would be: "10"

List1[2] would be: "Gempalm Incinerator"
List2[2] would be: "3"

etc.


A deck is 60 cards total (no more, no less). I need to loop over these lists
to generate all possible combinations of 60 card decks which use up to the
maximum quantity for each card.

So, from the example, I need to generate decks with '1' Aether Vial' and 59
other cards in all possible combinations (still within the maximum cap for
each card), and then I'd need to generate decks with '2' Aether Vial' and 58
other cards in all possible combinations

It is vital that I create all combinations and that the maximum quantities
are never breached.

I am hoping that the each deck could be output as two lists:

ListA = ['Cardname1', 'Cardname2', ...]
ListB = ['1', '2', ...]

These lists will have exactly 60 members.

If you have an idea of how to do this, please share it! =) I would be most
appreciative. I'll be testing all methods for speed because I have very
large amount of computing to do.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Michael Knowles/NONFS/USDAFS is out of the office.

2009-07-22 Thread Michael Knowles

I will be out of the office starting  07/22/2009 and will not return until
07/27/2009.

I am out of the office and will respond to your message when I return on
Monday, 30 Sep.

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


Re: [Tutor] noob question (Windows, Python 3.1)

2009-08-06 Thread Michael Connors
2009/8/6 Joshua Harper 

> Ok, so I am trying to learn python, and I am reading many tutorial type
> things and I am kind of stuck with implementing some of the code... so for
> example the tutorial says "*To get the examples working properly, write
> the programs in a text file and then run that with the interpreter*"
> Alright...simple enough so I wirte the example program:
>
> x = input("Please enter a number: ")
> print "The square of that number is
>
> I save this as a .py and Open With>python.exe. OK, so that gives me the
> terminal ansking me to enter a number, I enter a number and click enter and
> then it prints in like half a nanosecond and the cmd line window closes. I
> want to know how to have the window stay open so that, in future scripts I
> may be able to actually see what was printed. I talked to my friend and he
> said that he has the same problem...anybody?...help???
>
>
It closes because it is finished.

If you want to see the result, you could either:

- Place another input("") after the print statement.
- Run the program from the command prompt (in which case you will probably
need to set the path)

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


[Tutor] running python program on Linux Virtual Server - Plesk?

2009-09-02 Thread Michael Yang
Hi Everyone,

I'm new to programming and to python.

I have a program I want to run on my Media Temple Virtual Server (dv) -
Linux. which has the latest Plesk 9 virtuozzo installed.

Ultimately I want it to run the program (main.py) on a scheduled basis.  How
do I do this?



Thanks!

-Mike
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pyduino

2009-09-08 Thread Michael Connors
>
>
>
> You wouldn't want to run python on a 16 mhz processor, the interpreter
> would use up all your resources. The Arduino language is not too hard
> to learn.
>
>
>

I have followed some tutorials in the Arduino playground, for talking to the
arduino from Python. You can do things like tell your LED to turn on and off
based on a key press on your computers keyboard, and from there you can
probably figure out how to do plenty of other things.

The coding for the Arduino is still done in the native language, but the
client you use to speak to the connected arduino would be written in Python.

-- 
Michael Connors
Leiden
The Netherlands
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Invitation to connect on LinkedIn

2009-09-15 Thread Michael Connors
Gmail adds everyone you mail to your address book, and sites like LinkedIn
ask for your email account credentials to search for contacts from your
address book. I think this could happen to anyone who is unfamiliar with
either service.
Michael

2009/9/15 Kent Johnson 

> I'm going to be charitable and assume this is a mistake. This is completely
> inappropriate to post to the tutor list.
>
> Kent
>
> On Tue, Sep 15, 2009 at 6:50 AM, Govind Agrawal wrote:
>
>>   LinkedIn
>>
>> I'd like to add you to my professional network on LinkedIn.
>>
>> - Govind
>>
>> Accept Govind Agrawal's invite:
>> https://www.linkedin.com/e/isd/738276939/KwugpKmr/
>>
>> © 2009, LinkedIn Corporation
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Connors
Burggravenlaan 148,
Leiden 2313 HZ,
The Netherlands

0031611520252
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Example of use of (?P) and (?P=name) in Python regular expressions?

2009-11-28 Thread Michael Hannon
Greetings.  While looking into the use of regular expressions in Python, I saw 
that it's possible to name match groups using:

(?P...)

and then refer to them using:

(?P=name)

I was able to get this to work in the following, nonsensical, example:

>>> x = 'Free Fri Fro From'
>>> y = re.sub(r'(?P\bFro\b)', r'Frodo (--matched from \g)', x)
>>> y
'Free Fri Frodo (--matched from Fro) From'
>>> 

But, as you can see, to refer to the match I used the "\g" notation (that I 
found some place on the web).

I wasn't able to find a way to use the "P=" syntax, and I wasn't able to find 
any working examples of this syntax on the web.

If you have a working example of the use of the "P=" syntax, will you please 
send it to me?

Thanks.

-- Mike



  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Example of use of (?P) and (?P=name) in Python regular expressions?

2009-12-03 Thread Michael Hannon
Hi, folks.  I just wanted to thank Martin Walsh and Kent Johnson, both of whom 
furthered my education by replying (on-list) that the "P=" syntax is used to 
refer to a named group in the same regular expression, i.e., the one in which 
the "P" construct was used in the first place.  This is as opposed to the 
thing I was trying to do, which was to use the "P=" syntax in a substitution.

-- Mike



- Original Message 
From: Michael Hannon 
To: tutor@python.org
Sent: Sat, November 28, 2009 3:15:36 PM
Subject: [Tutor] Example of use of (?P) and (?P=name) in Python regular 
expressions?

Greetings.  While looking into the use of regular expressions in Python, I saw 
that it's possible to name match groups using:

(?P...)

and then refer to them using:

(?P=name)

I was able to get this to work in the following, nonsensical, example:

>>> x = 'Free Fri Fro From'
>>> y = re.sub(r'(?P\bFro\b)', r'Frodo (--matched from \g)', x)
>>> y
'Free Fri Frodo (--matched from Fro) From'
>>> 

But, as you can see, to refer to the match I used the "\g" notation (that I 
found some place on the web).

I wasn't able to find a way to use the "P=" syntax, and I wasn't able to find 
any working examples of this syntax on the web.

If you have a working example of the use of the "P=" syntax, will you please 
send it to me?

Thanks.

-- Mike



  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Generating Unique Permutations

2009-12-17 Thread Michael Morrissey
I'm just a philosophy teacher, and I don't know much about mathematics or
computers. I'm writing a python program (not the best language for this
topic, but it is what I know), and I need to solve a problem which requires
more knowledge than I have. I'm hoping you can help me. =)

I'm looking for an efficient way to create all the unique, non-duplicated
permutations of a list (I believe these are called "necklaces" in
combinatorics). I need to do this without actually generating every possible
permutation (which includes all the duplicates).

For example:

List = [a,a,b,b]

My output would be something like:

a,a,b,b
a,b,a,b
a,b,b,a
b,a,a,b
b,a,b,a
b,b,a,a

Importantly, you'll see that these are only generated once. There are four
permutations which can be generated from the list which all look like
(a,a,b,b), but I only want to generate this output a single time.

My problem is large enough that I can't feasibly generate all the
permutations (60! I think) and eliminate the duplicates from there, but I
could feasibly generate the unique ones (a much small search space),
especially if I use an efficient algorithm (I'm sorry to focus so much on
efficiency, but it matters).

What is the best way to do this? If you don't know how it would work in
Python, can you explain in psuedocode? As I said, I'm not very smart about
these things, so treat like a child to the topic (because I am a child to
the topic, an interested child!).

Oh, and thanks for this mailing/reading list! I spend countless hours
browsing and reading other people's code. It is a lot of fun =).




Sincerely,
Michael
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Computer Basics

2009-12-30 Thread Michael Sprayberry
Alan, it is great that you are taking such an active interest in computers.
As far as continuing your education in the field and Python I would suggest
reading "Python Programming: An Introduction to Computer Science" and "Gray
Hat Python: Python Programming for Hackers and  Reverse Engineers".


Michael
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Example of use of (?P) and (?P=name) in Python regular expressions?

2010-01-06 Thread Michael Fourman

I've used (?P=name) recently in an implementation of the porter2 stemming
algorithm from http://snowball.tartarus.org/algorithms/english/stemmer.html

This includes the rule:
## if the word ends with a double remove the last letter (so hopp -> hop)
where we
## Define a double as one of
## bb   dd   ff   gg   mm   nn   pp   rr   tt

re.sub("^(?P.*?[aeiouy].*?(?P[bdfgmnprt]?))(?P=dd)$", "\g",
word)

implements this rule.

Best,

Michael


Michael Hannon-2 wrote:
> 
> Greetings.  While looking into the use of regular expressions in Python, I
> saw that it's possible to name match groups using:
> 
> (?P...)
> 
> and then refer to them using:
> 
> (?P=name)
> 
> I was able to get this to work in the following, nonsensical, example:
> 
> >>> x = 'Free Fri Fro From'
> >>> y = re.sub(r'(?P\bFro\b)', r'Frodo (--matched from
> \g)', x)
> >>> y
> 'Free Fri Frodo (--matched from Fro) From'
> >>> 
> 
> But, as you can see, to refer to the match I used the "\g" notation (that
> I found some place on the web).
> 
> I wasn't able to find a way to use the "P=" syntax, and I wasn't able to
> find any working examples of this syntax on the web.
> 
> If you have a working example of the use of the "P=" syntax, will you
> please send it to me?
> 
> Thanks.
> 
> -- Mike
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Example-of-use-of-%28-P%3Cname%3E%29-and-%28-P%3Dname%29-in-Python-regular-expressions--tp26557967p27026833.html
Sent from the Python - tutor mailing list archive at Nabble.com.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tix NoteBook programming problem

2004-12-21 Thread Michael Lange
On Tue, 21 Dec 2004 14:16:56 +0900
Guillermo Fernandez Castellanos <[EMAIL PROTECTED]> wrote:

Hi Guille,

thats a classic case of geometry manager conflicts.
You dont need to pack the notebook pages explicitely, tix does this
automagically for you and *tix does not use pack()*, so when
you try to pack() the pages with

> hd.pack()
> gf.pack()

tix doesnt know what to do; by the way, instead of writing

> nb.add('hd',label="hard disk",underline=0)
> hd = nb.subwidget('hd')

you can simply do:

hd = nb.add('hd',label="hard disk",underline=0)

I hope this helps

Michael
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Tix Select programming problem

2004-12-22 Thread Michael Lange
On Wed, 22 Dec 2004 11:37:57 +0900
Guillermo Fernandez Castellanos <[EMAIL PROTECTED]> wrote:

Hi Guille,

> 
> I'm playing now with the Select buttons:
> 
> import Tix
> 
> def prtS():
> print fruits.cget('value')
> 
> def prtC(val):
> print val
> print sel.cget('value')
> 
> root = Tix.Tk()
> fruits=Tix.Select(root,label="Fruits:", orientation='horizontal')
> fruits.add('orange',text="Orange",width=6,command=prtS)
> fruits.add('lemon',text="Lemon",width=6,command=prtS)
> fruits.add('apple',text="Apple",width=6,command=prtS)
> fruits.pack()
> 
> sel=Tix.Control(root, label="X Coordinates", max=10, min=3,
> integer=True,command=prtC)
> sel.pack()
> 
> root.mainloop()
> 

The "command" option should be assigned to the Select widget itself, not to the 
added buttons.
It takes two arguments then (from the tixSelect man page):

   Command-Line Name:-command
   Database Name:  command
   Database Class: Command

  Specifies the TCL command to be executed when the -value of  the
  Select  widget is changed. This command will be invoked with two
  arguments. The first is the name of the  button  subwidget  that
  has  toggled.  The  second is a boolean value indicating whether
  the button subwidget is selected. This command is executed  only
  when the -disableCallback option is set to false.

So I changed your code a little to make it work:

import Tix

def prtS(*args):
print args
print fruits.cget('value')

def prtC(val):
print val
print sel.cget('value')

root = Tix.Tk()
fruits=Tix.Select(root,label="Fruits:", orientation='horizontal',command=prtS)
fruits.add('orange',text="Orange",width=6)
fruits.add('lemon',text="Lemon",width=6)
fruits.add('apple',text="Apple",width=6)
fruits.pack()

sel=Tix.Control(root, label="X Coordinates", max=10, min=3,
integer=True,command=prtC)
sel.pack()

root.mainloop()

Hope this helped

Michael
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cgi.FieldStorage and dictionary.get(' ')

2004-12-30 Thread Patric Michael

> Hi,
> 
> I've passed this through the interperter line-by-line, yet still can't
> get it to work right.
> 
> The first time the cgi driver script initiates it runs the login
> function which renders a zpt. Upon submission of their vitals,  the

I'm not sure what a zpt is, but it sounds like the form to request the vitals, 
so that's a 
start. :)

> user is authenticated via sqlobject, and if they pass the chapters
> function should run. However, what I get is zip, zilch, nada. Just a
> blank page, with the query string appended to the url.

First off, make sure that you have the "Content-Type: text/html\n\n"
line print before anything else whenever you send output to the web.  
Presumably it worked for the form display, but you have to keep resending it 
each time 
the page changes.  


> def main(form):
>if form.has_key('author') and form.has_key('password'):
>   q = Users.select(AND(Users.q.author==form.get('author'),
>   Users.q.password==form.get('password')))
>   if len(list(q))>0:
>  chapters(author=form.get('author'))
>   else:
>  login(failure=True)
>else:
>   login(failure=False)

Without seeing the def for login(failure), and not being familiar with SQL, 
I'll take a pass 
on these lines, but I am curious why you declare failure as true or false in 
the login 
function?

> 
> Out of curiosity I wrote a simple test cgi.
> 
> #!/usr/local/bin/python
> 
> print 'Content-type: text/plain\n\n'
> 
> import cgi
> 
> form = cgi.FieldStorage()
> if form.has_key('author') and form.has_key('password'):
> print form.keys()
> print form.get('author')
> print form.get('password')

Instead of form.get(), try this:

  print form['author'].value
  print form['password'].value

Working with cgi scripts is always a bit tricky because of the added variable 
of the server 
displaying the page, so I define this little function on anything I am working 
on:


from sys import stderr   # Unix only!

def s(msg):
s = stderr.write# Sends messages to the error log via s()
s(msg + '\n')   # adds a carriage return :)


Someone else more versed than I could probably tell you if there is a windows 
equivalent, but what I do is open another shell and tail -f the error log while 
I test the 
script.  Any errors or tracebacks appear there anyway, and I can add little 
notes between 
functions to see where the thing breaks down.  Especially handy to 
"pre-display" the 
expected output to make sure I get what I expect, and its not the web server 
that's eating 
the result or something.

> 
> Strangely, the calls to print form.get('author') and
> form.get('password') don't appear in the output. Only the form.keys()
> appears.
> 
> Additionally, why doesn't def main(form=cgi.FieldStorage()) work, I
> tried to do it as so, thinking it more graceful, and it floundered.

I am not sure about this, but I've always put the form = cgi.Fieldstorage in 
the global 
namespace so I could get at it with subsequent functions.

I am guessing that your version didn't work because the form namespace isnt 
getting 
filled with cgi.Fieldstorage --before-- the function is defined.  Remember 
python tries to 
look through all the defs and make sure they are syntactically correct before 
actually 
running the script.  You probably got an AttributeError, right?

Patric

OBTW...  the .value method might be superceded by newer versions of python.  I 
am not 
well versed on all the changes in 2.4 yet.  :)

> ___ 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] O.T.

2004-12-30 Thread Patric Michael
Hi Jacob...

> But who are you all, what are you're ages, what do you do, marriage
> status, etc? You obviously don't have to answer, I'm just curious who
> I'm boldly sending emails to.

I figure since I bit the bullet and actually posted a reply, I best answer 
this as well in the faint hope of why I don't answer much... :)

I'm 43 (just), no kids, no wife, no life.  I work in entertainment and you'll 
have seen any number of things I've worked on, but you wont ever see 
me in the credits. 

I barely survived high school so college was out of the question.  I 
started in BASIC on a TI99 4a.  Learned DOS on an IBM 8088.  Unix 
was next and now I manage a few servers. I got into python (I am by no 
means fluent) because I tried writing cgi scripts in perl and got dizzy.  It 
also reminds me of mushcode, which I am pretty good at.   I know just 
enough LISP to get myself in trouble because I am utterly fascinated 
with the idea of  AI.

Cheers!

Patric

> 
> Jacob Schmidt
> 
> P.S.
> I'm a student. 14 years. Play the piano better than I write scripts.
> Single. etc.
> 
> ___
> 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] O.T.

2004-12-31 Thread Michael Lange
> * Jacob S. <[EMAIL PROTECTED]> [041228 01:42]:
> > But who are you all, what are you're ages, what do you do, marriage status,
> > etc?

37, no kids but a girlfriend with a cat. I work at a clinical laboratory in a 
hospital in germany.
I'm just a hobby programmer and started with python about 2 years ago; I chose 
python as my first
(and yet only) language because I happened to find a cheap german version of 
Ivan van Laningham's
"Teach yourself python in 24 hours" in a local bookstore when I was looking for 
something to
start with. The book had a sticker on it that said something like "No 
programming knowledge required!"
which looked very promising to me back then.

A happy new year to all of you

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


Re: [Tutor] cgi.FieldStorage and dictionary.get(' ')

2004-12-31 Thread Patric Michael
Forwarded to the list...

> On Thu, 30 Dec 2004 22:58:14 -0800, Patric Michael <[EMAIL PROTECTED]>
> wrote: > > First off, make sure that you have the "Content-Type:
> text/html\n\n" > line print before anything else whenever you send
> output to the web. > Presumably it worked for the form display, but
> you have to keep resending it  > each time the page changes. > >
> Without seeing the def for login(failure), and not being familiar with
> SQL, I'll take > a pass on these lines, but I am curious why you
> declare failure as true or false in > the login function? > > Instead
> of form.get(), try this: > >  print form['author'].value >
>  print form['password'].value > 
> 
> Hi,
> 
> def main(form):
>if form.has_key('author') and form.has_key('password'):
>   author = form['author'].value
>   password = form['password'].value
>   q = Users.select(AND(Users.q.author==author,
>Users.q.password==password))
>   if len(list(q))>0:
>  chapters(author)
>   else:
>  login(failure=True)
>else:
>   login(failure=False)
> 
> Using form['author'].value works so long as it's assigned to a
> variable before being looked up by sqlobject. This is interesting
> because, if I try this from the interperter:
> 
> >>> author = form['author'].value
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: 'str' object has no attribute 'value'

Right.  If I recall correctly, the .value method is specific to the cgi 
module since FieldStorage() is actually a bunch of dictionaries 
contained in a list.  
The .value method shortcuts the need to extract the dictionary from the 
list, then extract the key/value pair from the result and lets you grab the 
value directly.  (Someone correct me if I misremember this, please!)

> 
> I define login(failure) as True or False because the first time the
> user reaches the login page they shouldn't be presented with a failure
> message. The second time round they should.

Oh cool.  I hadnt thought of that.  I usually use a try: statement to test 
for one of the keys to determine whether the script sends the initial login 
form, or the login form with appropriate error messages prepended.  
That way I can explicitly indicate which field(s) need attention.
> 
> Everything happens through a driver script:
> 
> #!/usr/local/bin/python
> 
> print 'Content-type: text/html\n\n'
> 
> import cgi
> from spanishlabs.gui import *
> 
> if __name__ == '__main__':
>main(form=cgi.FieldStorage())
> 
> Thanks for your help!
> 

No problem!

Patric

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


Re: [Tutor] doctest

2005-01-01 Thread Patric Michael
> Also, anything I can do... Presently, since I'm running windows xp, I
> would have to hunt for the command prompt and type in the command

Click Start, click Run, type CMD, press Enter.

Voila!  :)

Patric


> 
> '"C:\python24\python.exe" "C:\documents and
> settings\jacob\desktop\working python programs\testmodules.py" -v'
> 
> ...or make a batch file to do it for me...
> How can I make testmodules.py (shown below) append the -v to itself?
> Is there a self.results or something in testmod?
> 
> ## testmodules.py ###
> import doctest
> 
> modtotest = 'FractionReducer2'
> 
> exec "import %s" % modtotest
> doctest.testmod(eval(modtotest))
> raw_input()
> #
> 
> 
> Thanks,
> Jacob Schmidt
> 
> 
> > What docs are you looking at?? The module docs at
> http://docs.python.org/lib/module-doctest.html
> > have a complete example of testing a module with a main function. Or
> > you
> can use the code in my last
> > post.
> >
> > Kent
> >
> > Jacob S. wrote:
> > > Hi.
> > >
> > > Okay, so I look at the documentation at it says (in my words):
> > >
> > > "First Class - DocTest -- Make a test object with such and such
> attributes
> > > that you can test.
> > > Second Class - i don't remember the name - Make Jacob look stupid
> > > with
> big
> > > words
> > > Third Class - DocTestSuite - Convert a doctest object to a
> > > unittest
> object -
> > > Okay... so how does that help?
> > > Fourth Class - DocTestFinder - Find the docstrings that contain
> > > test
> code
> > > and extract them."
> > >
> > > So, my question, I guess, is How did the documentation help, and,
> > > How do
> I
> > > have doctest test all of my module's function's docstrings?
> > >
> > > Thanks in advance,
> > > Jacob Schmidt
> > >
> > > ___
> > > 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
> 


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


[Tutor] A not-so-basic question...

2005-01-02 Thread Patric Michael
Hi folks...

I was thinking about this the other day while prepping to write up 
another CGI thing.
It occurred to me to wonder how other folks prepare an app, script, 
whatever.
So the question is, and I am not looking for a "right answer" here.  (I 
doubt ther eis one, to be honest.)

How do you go about setting up a new application?

For example, suppose I need a script that will collect order information 
for a set of items ona  page.  Its output will go to a mail program so the 
artist can be notified.
I know that the script needs to be somewhat customizable since more 
than one person will use it, and I want to look to the future where such a 
script might get superceded for something like credit card orders, or 
possible integration with a larger order processing scheme.

I'd start out by commenting goals in a new file, like so:

--
# Initialize variables

# Gather form data

# Output results
--
Then I'd go back through each comment and either call modules I've 
prewritten, or write new defs.  
Then I'd add import statements to cover the modules and the defs:

--
from datetime import now
import cgi
from mailman import send

# Initialize variables
form = cgi.FieldStorage()

# Gather form data
for each in form:
  blah 
  blah

# Output results
result = {}
send(result)



And so on.  

So the question is, how do you do it?

Is there a method you prefer?  Something tried and true, or maybe 
foolproof?

Just curious...  And maybe a bit hopeful someone has a better way than 
mine.  Seems like I do an awful lot of testing... :)

Patric

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


Re: [Tutor] dumping .pck files

2005-01-02 Thread Patric Michael
> I want to explore some mailman config files, e.g.
> config.pck.  Some quick searches informed me that these
> contain pickled configuration info.
> 
> My first naive attempt to dump what was in them failed:
> 
> >>> import pickle
> >>> pickle.load(open("config.pck"))
> traceback
> ImportError: No module named Mailman.Bouncer
> 
> It seems that to do a good job of dumping the data, I need to tell it
> what this class looks like.
> 
> Are there alternatives?  Does the pickle format really not provide a
> way to inspect the data without the class definitions?  E.g. if I
> didn't have the source code or didn't want to dig around in it?
> 
> Is there a simple way to dump everything it does understand, and
> just print stubs for the parts it doesn't?
> 
> Or is there some nice software to do this all for me?
> 
> Or perhaps does mailman itself have handy command-line tools to aid in
> comparing configurations across mailing lists?

In the bin directory, find the script called "config_list".  From the help file 
(./config_list --help):

 --outputfile filename
-o filename
Instead of configuring the list, print out a list's configuration
variables in a format suitable for input using this script.  In this
way, you can easily capture the configuration settings for a
particular list and imprint those settings on another list.  filename
is the file to output the settings to.  If filename is `-', standard
out is used.

Dont forget to supply the list name in the command line.  
For example:

config_list -o outfile.txt mylist 

Patric




> 
> Are there other serialization options that would make this easier?
> 
> Many thanks,
> 
> Neal McBurnett http://bcn.boulder.co.us/~neal/
> Signed and/or sealed mail encouraged.  GPG/PGP Keyid: 2C9EBA60
> ___
> 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] here documents

2005-01-03 Thread Michael Powe
Hello,

In perl, I create variables of fairly involved text using here
documents.  For example,

$msg = <<"EOF";
  a bunch of text here.
  ...
EOF

Is there an equivalent method in python?  I usually use this method
when creating help messages for scripts -- put all the text into a
variable and the 'print $msg' for the output.  I find it an easy way
to produce formatted text.

Now, I'm trying to switch over to python and want to recreate or adapt
my processes.

Thanks.

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


Re: [Tutor] here documents

2005-01-03 Thread Michael Powe
On Mon, Jan 03, 2005 at 11:54:06PM -, Alan Gauld wrote:

> There was a detailed thread on this recently either here
> or on usenet group comp.lang.python...

I checked the archives for this list but didn't see anything.  I'll
try the ng.  Thanks.

> The bottom line was to use string formatting and triple
> quoted strings...
> 
> msg = '''
> A very long string that overspills
> onto multiple lines and includes
> my name which is %{name}s
> and a number which is my age: %{age}d
> '''
> 
> print msg % vars()

This is great, thanks to you and to Bill.  Much appreciated.

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


Re: [Tutor] Re: here documents

2005-01-03 Thread Michael Powe
On Mon, Jan 03, 2005 at 10:04:18PM -0200, Jorge Luiz Godoy Filho wrote:
> Alan Gauld, Segunda 03 Janeiro 2005 21:56, wrote:
> 
> > Oops, those should have been () not {}
> 
> I always do the same mistake ;-)  Using "{}" seems more intuitive to me. 

perhaps because of ${var} shell syntax?  ;-)

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


Re: [Tutor] A not-so-basic question...

2005-01-03 Thread Patric Michael
Hi Alan...

> Thats a great question, and I hope we get a few responses.

Me too!

Thank you for taking the time to reply.  

Your response is far more complex than my original example, but its very 
illustrative.  
Not so much in what to do, but how to think about doing it, and that was my 
goal.  To 
determine how others _think_ about building an app.

Very cool.  :)

Patric


> 
> > For example, suppose I need a script that will collect order
> information
> > for a set of items ona  page.  Its output will go to a mail program
> so the
> > artist can be notified.
> 
> I would start by abstracting the problem as much as possible
> and identifying the classes/objects (I think in OOP by default
> for anything non trivial) In this case I see an order and
> and order item (or possibly several)
> 
> Because I try to separate UI from application as much as possible I'd
> start with these and build the two objects in a module and test them
> using the >>> prompt.
>
> Order depends on order items so I'd build item first.
> Then I'd test it - can I create an item? Can I print
> an item? Because this is targetted at the web I might
> right a dedicated str/repr method to grenerate an XML
> representation...
> 
> Then I'd build the orderand test it.
> Can I add items to it? etc.
> 
> Then I'd think about how to extend the order items.
> I don't want to use subclassing since that means custom
> code for every new product we sell, better to use a
> dictionary of attributes I think... Lets try that out,
> back to item again...
> 
> OK, It all works from the >>> prompt lets think about the UI.
> 
> (Here I confess that I do very little web programming)
> 
> I need to
> - present the items for selection/browsing
> - offer the opportunity to create an order(add to basket)
> - present an order summary
> - capture customer details
> - allow confirmation of the order
> - process the order
> 
> This points out that I also need a customer object!
> Back to the application construction.
> OK I now have a customer object, back to the UI.
> 
> I'll build the UI in generic terms using the bullets above
> as hook functions - so I can change behaviour easily later.
> Thus calling Order.process(customer) will initially generate
> an email, but later I may subclass order to provide a direct
> link to the suppliers via a B2B gateway or Web Service...
> 
> I'll have to think about the order process at this point
> and join the bits up in the right order. Back to the >>>
> prompt for some experimenting.
> 
> Now I design the HTML and set up my web server environment.
> 
> I write my CGI handling parts to call the application objects
> as required.
> 
> It all works, but nothing is persisted.
> Build a persistence mechanism, how many orders?
> Maybe store the data in XML files somewhere for a few orders?
> Or go for growth and build a full database and write
> persistence methods to match.
> 
> I think I'm ready for accepance testing now.
> 
> In terms of modules, I'll probably put the order, item,
> and customer in separate modules.
> 
> I'll put the UI stuff in a single module.
> The database bits will probably go along with the objects
> themselves.
> 
> If its for production use rather than a prototype I'd
> document the class structure, the order processing
> sequence and the database schema and persistence mechanism.
> I'd also document the file structure on the web server.
> The rest of the documentation I'd leave as comments and
> docstrings since its a very small application. In total
> I'd expect a design document of 5-7 pages or so.
> 
> Alan G.
> 
> 


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


Re: [Tutor] A not-so-basic question...

2005-01-03 Thread Patric Michael
Hello Kent...

> I am a strong proponent of
> - incremental development
> - unit testing and test-first (or at least test-concurrent)
> programming - Don't Repeat Yourself and merciless refactoring

I see we have similarities.  I purely hate having to rewrite something I've 
already done once to satisfaction.

> 
> I look for a small piece of a problem, or a simplification of the
> problem, and write some code. I write unit tests for the code as I go.
> When I have the first bit working, I add some more. I refactor to
> improve the clarity of the code and avoid duplication.

Again, we are similar.  In my case though, its primarily because I don't 
do enough scripting to remember little things, like slices for example.

> 
> 
> 
> Look for a way to automate your tests. If you are writing a CGI and
> testing it in place with a web browser, the testing will quickly
> become tedious and you will rarely test more than the last code that
> you wrote. If your tests are automated and quick, you can run many
> tests at once. That way you have confidence that you haven't broken
> anything.

I don't quite grasp "automated testing".  And yes, I test in place 
constantly, but it only ever gets tedious when I cant figure out why a 
thing doesn't work.  ;)


> 
> In your example, automated testing may be a challenge. If I understand
> correctly, you are basically getting data from a form and putting it
> into an email. Some suggestions: - If there is any manipulation of the
> data in the middle, you can break that into functions and test those
> functions separately. - You can abstract the mailer into a generic
> back end. Then you can make a test version that doesn't actually send
> any mail, but that lets you verify that the program asked for mail to

Ah.  I see what you mean.  Ironically I do just that.  IF the final output is 
supposed to go to a mailer module, I'll send it to a page to make sure 
that whats supposed to be there shows up in print.

> be sent. Then use an automated tester for web apps to drive the front
> end and make sure the back end is called correctly. - This thread on
> comp.lang.python about unit testing CGIs may be helpful:
> http://tinyurl.com/5yr4c
> 
> It can take some work to set up a test jig but I find it usually pays
> off. Once you have done it once you will have the techniques down and
> you can use the same techniques in similar projects.
> 
> 
> 
> Look for duplication in your code and don't tolerate it. Not only in a
> single project but between projects. If you are writing many similar
> CGIs you should be building up a library of tested support modules
> that you can re-use. This will make subsequent projects easier.

It does make things MUCH easier.  When I started out, I was cutting 
from one script to another until I figured out what a "module" was.  
Now the calls to the database I/O are nothing more than importing a 
module or function.   And because they were tested when being built, if 
I send a dictionary to a module, I _know_ it will be inserted without 
checking.  Thats what you meant by abstracting, right?

> 
> Whenever you are tempted to copy and paste code, look for a way to
> abstract the code into a function or class so the copying is not
> needed.
> 
> Whenever you are tempted to copy and paste data, look for a way to
> centralize the data so all clients work from the same reference.

Yes, thank you.  I am glad to see my original thoughts are supported.

Patric


> 
> 
> HTH,
> Kent
> 
> Patric Michael wrote:
> > Hi folks...
> > 
> > I was thinking about this the other day while prepping to write up
> > another CGI thing. It occurred to me to wonder how other folks
> > prepare an app, script, whatever. So the question is, and I am not
> > looking for a "right answer" here.  (I doubt ther eis one, to be
> > honest.)
> > 
> > How do you go about setting up a new application?
> > 
> > For example, suppose I need a script that will collect order
> > information for a set of items ona  page.  Its output will go to a
> > mail program so the artist can be notified. I know that the script
> > needs to be somewhat customizable since more than one person will
> > use it, and I want to look to the future where such a script might
> > get superceded for something like credit card orders, or possible
> > integration with a larger order processing scheme.
> > 
> > I'd start out by commenting goals in a new file, like so:
> > 
> > --
> > # Initialize variables
> > 
> > # Gather form data
> > 
> > # Output result

Re: [Tutor] How to run a script file

2005-01-04 Thread Patric Michael
Hi Bernard...

The most basic form is to type "python" followed by the script you want 
to run.  If your script is not in the system path, you'll either need to cd to 
the directory, or give a full pathname: (the pythonpath doesn't come into 
play until the interperter is running.

python /usr/local/share/filename.py

Remember that the script will inherit whatever permissions you currently 
have, so either log in or su to the user that's expected to run the script.

Oh, and in case python itself isnt in your system path, (it probably is)  
you can find it by typing "which python" at the shell prompt.


Patric



> Hi,
> 
> Sorry if I missed something obvious, but how do I execute a python
> script file in the interpreter? I have "Using the Python Interpreter"
> in the Python tutorial but not much is said...
> 
> (this might be a lame quesiton but so far I always used either the
> PythonWin interpreter wich has the Import function, or I ran Python
> code in an application. Now I'm on Linux so I have to learn the hard
> way!)
> 
> 
> Thanks
> Bernard
> 
> ___
> 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] regex problem

2005-01-04 Thread Michael Powe
Hello,

I'm having erratic results with a regex.  I'm hoping someone can
pinpoint the problem.

This function removes HTML formatting codes from a text email that is
poorly exported -- it is supposed to be a text version of an HTML
mailing, but it's basically just a text version of the HTML page.  I'm
not after anything elaborate, but it has gotten to be a bit of an
itch.  ;-)

def parseFile(inFile) :
import re
bSpace = re.compile("^ ")
multiSpace = re.compile(r"\s\s+")
nbsp = re.compile(r" ")
HTMLRegEx =
re.compile(r"(<|<)/?((!--.*--)|(STYLE.*STYLE)|(P|BR|b|STRONG))/?(>|>)
",re.I)

f = open(inFile,"r")
lines = f.readlines()
newLines = []
for line in lines :
line = HTMLRegEx.sub(' ',line)
line = bSpace.sub('',line)
line = nbsp.sub(' ',line)
line = multiSpace.sub(' ',line)
newLines.append(line)
f.close()
return newLines

Now, the main issue I'm looking at is with the multiSpace regex.  When
applied, this removes some blank lines but not others.  I don't want
it to remove any blank lines, just contiguous multiple spaces in a
line.

BTB, this also illustrates a difference between python and perl -- in
perl, i can change "line" and it automatically changes the entry in
the array; this doesn't work in python.  A bit annoying, actually.
;-)

Thanks for any help.  If there's a better way to do this, I'm open to
suggestions on that regard, too.

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


Re: [Tutor] How to run a script file

2005-01-04 Thread Patric Michael
HI Bernard...

I think I see what you might mean

I'm guessing your session goes something like this:

>>> import sys
>>> sys.path.append(' /home/bernardl/python/')
>>> import  /home/bernardl/python/myScript
  File "", line 1
import /home/bernardl/python/myScript
  ^
SyntaxError: invalid syntax

Right?

If so, its because the full pathname is no longer necessary after you've 
added it to the path.  Just type 

>>>import myScript

and that will bring it in.  :)

Let us know if we've still misunderstood...

Patric


> Okay sorry I meant once you're in Python.
> 
> I'm in Bash console, type Python, enter the Python interpreter.
> 
> Then I add my custom path to the sys.path list (because my user 
> permissions do not allow my to put anything in the Lib directory) and
> then I try an import /home/bernardl/python/myScript.py but of course
> if fails as soon the first slash is read.
> 
> 
> Thanks
> Bernard
> 
> 
> John Purser wrote:
> > Bernard,
> > 
> > If you're new to Linux you might not be aware of an additional
> > method to run python scripts.  If the first line of your script is:
> > #!/usr/bin/python
> > 
> > And you've set your script permissions to be executable (chmod 700
> > myscript.py) then you can run your script just like any other
> > program.  You can double click on it in a GUI environment or run it
> > from a command prompt by just typing the script name.  Or depending
> > on the value of $PATH variable you might need to type
> > "./myscript.py".  Those first characters have to be right though. 
> > I'm assuming your python is in /usr/bin.  And that is a hash mark
> > followed by an exclamation point.  This is called "hash bang" in
> > uningo. 
> > 
> > John Purser
> > 
> > -Original Message-
> > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
> > Behalf Of Patric Michael Sent: Tuesday, January 04, 2005 14:56 To:
> > tutor@python.org Subject: Re: [Tutor] How to run a script file
> > 
> > Hi Bernard...
> > 
> > The most basic form is to type "python" followed by the script you
> > want to run.  If your script is not in the system path, you'll
> > either need to cd to the directory, or give a full pathname: (the
> > pythonpath doesn't come into play until the interperter is running.
> > 
> > python /usr/local/share/filename.py
> > 
> > Remember that the script will inherit whatever permissions you
> > currently have, so either log in or su to the user that's expected
> > to run the script.
> > 
> > Oh, and in case python itself isnt in your system path, (it probably
> > is)  you can find it by typing "which python" at the shell prompt.
> > 
> > 
> > Patric
> > 
> > 
> > 
> > 
> >>Hi,
> >>
> >>Sorry if I missed something obvious, but how do I execute a python
> >>script file in the interpreter? I have "Using the Python
> >>Interpreter" in the Python tutorial but not much is said...
> >>
> >>(this might be a lame quesiton but so far I always used either the
> >>PythonWin interpreter wich has the Import function, or I ran Python
> >>code in an application. Now I'm on Linux so I have to learn the hard
> >>way!)
> >>
> >>
> >>Thanks
> >>Bernard
> 
> ___
> 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] regex problem

2005-01-05 Thread Michael Powe
On Tue, Jan 04, 2005 at 09:15:46PM -0800, Danny Yoo wrote:
> 
> 
> On Tue, 4 Jan 2005, Michael Powe wrote:
> 
> > def parseFile(inFile) :
> > import re
> > bSpace = re.compile("^ ")
> > multiSpace = re.compile(r"\s\s+")
> > nbsp = re.compile(r" ")
> > HTMLRegEx =
> > 
> > re.compile(r"(<|<)/?((!--.*--)|(STYLE.*STYLE)|(P|BR|b|STRONG))/?(>|>)
> > ",re.I)
> >
> > f = open(inFile,"r")
> > lines = f.readlines()
> > newLines = []
> > for line in lines :
> > line = HTMLRegEx.sub(' ',line)
> > line = bSpace.sub('',line)
> > line = nbsp.sub(' ',line)
> > line = multiSpace.sub(' ',line)
> > newLines.append(line)
> > f.close()
> > return newLines
> >
> > Now, the main issue I'm looking at is with the multiSpace regex.  When
> > applied, this removes some blank lines but not others.  I don't want it
> > to remove any blank lines, just contiguous multiple spaces in a line.
> 
> 
> Hi Michael,
> 
> Do you have an example of a file where this bug takes place?  As far as I
> can tell, since the processing is being done line-by-line, the program
> shouldn't be losing any blank lines at all.

That is what I thought.  And the effect is erratic, it removes some
but not all empty lines.
 
> Do you mean that the 'multiSpace' pattern is eating the line-terminating
> newlines?  If you don't want it to do this, you can modify the pattern
> slightly.  '\s' is defined to be this group of characters:
> 
> '[ \t\n\r\f\v]'
> 
> (from http://www.python.org/doc/lib/re-syntax.html)
> 
> So we can adjust our pattern from:
> 
> r"\s\s+"
> 
> to
> 
> r"[ \t\f\v][ \t\f\v]+"
> 
> so that we don't capture newlines or carriage returns.  Regular
> expressions have a brace operator for dealing with repetition:
> if we're looking for at least 2 or more
> of some thing 'x', we can say:

I will take a look at this option.  Thanks.

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


Re: [Tutor] regex problem

2005-01-05 Thread Michael Powe
On Wed, Jan 05, 2005 at 07:37:58AM -, Alan Gauld wrote:
> > This function removes HTML formatting codes from a text email 
 
> Using regex to remove HTML is usually the wrong approach unless 
> you can guarantee the format of the HTML in advance. The 
> HTMLparser is usually better and simpler. I think theres an example
> in the module doc of converting HTML to plain text.

Thanks.  This is one of those projects I've had in mind for a long
time, decided it was a good way to learn some python.  I will look at
the HTMLParser module.  But then once I get started on one of these
projects, it has a way of taking over.  ;-)

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


Re: [Tutor] regex problem

2005-01-05 Thread Michael Powe
On Wed, Jan 05, 2005 at 06:33:32AM -0500, Kent Johnson wrote:
> If you search comp.lang.python for 'convert html text', the top four 
> results all have solutions for this problem including a reference to this 
> cookbook recipe:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52297
> 
> comp.lang.python can be found here:
> http://groups-beta.google.com/group/comp.lang.python?hl=en&lr=&ie=UTF-8&c2coff=1

Shame on me, I have to get back into that habit.  I will check these
references, thanks.

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


Re: [Tutor] Something is wrong in file input output functions.

2005-01-10 Thread Michael Powe
On Mon, Jan 10, 2005 at 12:15:18PM -0800, kumar s wrote:
> Dear group,
> I have written a small piece of code that takes a file
> and selects the columns that I am interested in and
> checks the value of the column on a condition (value
> that eqauls 25) and then write it the to another file.
> 
> 
> 
> Code:
> import sys
> from string import split
> import string
> print "enter the file name" ### Takes the file name###
> psl = sys.stdin.readline()  ### psl has the file
> object###

I may be wrong but it does not appear to me that you open the files
for reading/writing.  The variable psl does not contain the file
object, it contains the file name.  To create a file object, you have
to open it.  E.g.,

f = open(psl,"r")
w = open(out,"w")

Now str_psl = f.readlines()

creates an array of strings -- what you are trying to do with
psl.split? 

I don't know what sys.stdout.write returns (and I'm not looking it
up), but my guess would be something like the number of characters
written. 

As a matter of form, I suggest writing all function definitions and
then follow with execution code (input and function calls) -- makes it
easier to read and follow what you're doing.  I think it's unfortunate
that python does not allow us to put function defs at the end of the
file, so we can put execution code at the top ... but that's the way
of it.

I put my execution in a main function, and then call that.  Seems
tidier.


HTH

mp

> 
> f2 = sys.stdout.write("File name to write")
> def extCor(psl):
> ''' This function, splits the file and writes the
> desired columns to
> to another file only if the first column value equals
> 25.'''
> str_psl = psl.split('\n')
> str_psl = str_psl[5:]
> for ele in range(len(str_psl)):
> cols = split(str_psl[ele],'\t')
> des_cols =
> cols[0]+'\t'+cols[1]+'\t'+cols[8]+'\t'+cols[9]+'\t'+cols[11]+'\t'+cols[12]+'\t'+cols[13]+'\t'+cols[15]+'\t'+cols[16]+'\t'+cols[17])
>   if cols[0] == 25:
> '''This condition checks if the first
> column value == 25, then it writes it to the file, if
> not then it does not'''
> f2.write(des_cols)
> f2.write("\n")
> 
> extCor(psl)
> 
> 
> 
> Question:
> when i give it the file name that it should parse, I
> do not get to asked the file name i am interested in
> it gives me nothing. Please help me. 
> Thanks
> K
> 
> 
>   
> __ 
> Do you Yahoo!? 
> The all-new My Yahoo! - Get yours free! 
> http://my.yahoo.com 
>  
> 
> ___
> 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] CGI problem

2005-01-10 Thread Patric Michael
Hi David...

You need to explicitly name your form element to "inputkey" to make 
your current code work correctly. ( Based on what you have shown 
below.)

Or, to make the code correct, change "inputkey" to "language".

Remember that the name in each form element becomes the key in the 
key/value pairs sent via POST or GET. 

Patric


> I am trying to write a CGI program here is the code of
> the HTML
> 
>  
>   ALL
>   Bromley
>   Lewisham
> 
> Here is the python
> #!/usr/bin/env python
> 
> boroughdict = {
> 'BROMLEY': 0.5,
> 'LEWISHAM':0.1
> }
> 
> 
> class dummy:#mocked up input obj
> def __init__(self, str):
> self.value = str
> 
> import cgi, string
> form = cgi.FieldStorage()
> 
> def showboroughinfo(form):
> try:
> choice = form[inputkey].value
> except:
> choice = 'BROMLEY'
> print "not getting from form"
> choice = string.upper(choice)
> info = boroughdict[choice]
> #this is not being called
> newinfo = calcinfo(info)
> print ""
> print cgi.escape (newinfo) 
> print ""
> #print ''
> 
> def calcinfo(info):
> #this is calcuate stuff
> info = str(info)
> return info
> 
> print "Content-type: text/html\n"
> print "Languages"
> print "This will happen"
> 
> 
> showboroughinfo(form)
> #print "Hi"
> print ''
> 
> For some reason it is not get the info in the try
> block.
> If I do not have the try block I get this message :-
> Traceback (most recent call last):
>   File
> "/home/david/Documents/pyprogramming/cgi-bin/party2.py",
> line 45, in ?
> showboroughinfo(form)
>   File
> "/home/david/Documents/pyprogramming/cgi-bin/party2.py",
> line 19, in showboroughinfo
> choice = form[inputkey].value
>   File "/usr/lib/python2.3/cgi.py", line 552, in
> __getitem__
> raise KeyError, key
> KeyError: 'borough'
> 
> 
> Why is the input key not working ?
> Thanks in advance.
> 
> 
> 
> 
> 
> ___ 
> ALL-NEW Yahoo! Messenger - all new features - even more fun!
> http://uk.messenger.yahoo.com
> ___ 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] hi

2005-01-11 Thread Michael Janssen
On Tue, 11 Jan 2005 11:39:36 +0530, Gopinath V, ASDC Chennai
<[EMAIL PROTECTED]> wrote:

>   Can  any1 please tell me how do i open an editor in python running in
> linux os 

can be as easy as: os.system("editor-cmd")

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


Re: [Tutor] reinitializing namespace

2005-01-13 Thread Michael Janssen
On Thu, 13 Jan 2005 13:20:11 +0100, Dimitri D'Or
<[EMAIL PROTECTED]> wrote:

> For some purpose, I would like to reinitialize the main namespace, i.e. I want
> to delete all the variables I have created through the use of functions or
> keyboard entries.

Hello Dimiti,

sound like you're talking about an interactive session. Otherwise
(within a script) it would be a really bad idea to try this (better
put your stuff into functions, that don't create global variables).

Even in an interactive session it sounds like a not that brilliant
idea, especially since I can't think of a way other than using exec
"del %s" % key for appropriate keys from globals(). Finding
"appropiate" keys is one tricky thing.

Why not end your ugly python session and start a new one? You can
define all your imports in the python startfile (on Linux, consult
python manpage. On Windows, I don't know). You can also define useful
functions or variables in your python startfile. This way, you're
really shure that all ugly variables are away without del'iting
anything important.

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


Re: [Tutor] reinitializing namespace

2005-01-14 Thread Michael Janssen
On Fri, 14 Jan 2005 09:30:46 +0100, Dimitri D'Or
<[EMAIL PROTECTED]> wrote:

> Thank you for your answer. Actually, my question is not specific to
> interactive sessions. I've written a script that loads some modules, create
> variables and show figures. What I would like to find, is a command for
> clearing all the created variables and close all figures before beginning
> the execution of the script. This command will be placed at the beginning of
> the script and automatically reinitialize the namespace. The utility of this
> command is to guarantee that all the variables that are available in the
> namespace after the execution of the script were created by it and are not
> remainders from older commands or scripts.

In Python you do this by mentally tracking when and by which code
variables get created and by careful programm design. Most the time
it's as easy as:

var1 = func1()
var2 = func2()

It's obviously easy to track which variable gets created by which
function ;-) It's harder when func1 for example looks like:

def func1():
  global var3
  var3 = "something"
  return "somthing"

this way func1 has the *sideeffect* of setting var3. Sideeffects are
sometimes really bad and it's a good idea to a) document them and b)
use them seldom.

Furthermore, reusing old variables can happen and results in hard to
debug bugs. Look at this for-loop:

meaning_full_variable = None
for thing in list_of_things:
if strange_condition():
meaning_full_variable = check(thing)
print thing, meaning_full_variable

Of course, you will reuse the meaning_full_variable whenever
strange_condition() is not met. The print statment will print out the
actual "thing" but possibly the "meaning_full_variable" from an
earlier run.

You solve this issue by setting meaning_full_variable in every
iteration of this loop:

for thing in list_of_things:
  meaning_full_variable = None
  if strange_condition():
  meaning_full_variable = check(thing)
  print thing, meaning_full_variable 

which is a slightly saner version of the code ;-)

Since such problems are a little hard to debug, you should learn to
get wary when you see code like the above example (feel the problems
before running into them).


The main tactic to minimize namespace problems is to use functions and
classes which comes all with their own namespaces. Perhaps you should
post code, you find problematic, and we might find strategies to
restructure it, so that namespace problems are claryfied.


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


Re: [Tutor] Tix and Table printing

2005-01-14 Thread Michael Lange
On Fri, 14 Jan 2005 08:47:49 -
"Alan Gauld" <[EMAIL PROTECTED]> wrote:


>  Tk was written in the 80's so given 
> its origins was not likely to have a table. 
> 
> Of course it would be nice if they added one now!!!
> 

It looks like they are already working on it: 

http://wiki.tcl.tk/12753

Regards

Michael

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


  1   2   3   4   5   6   7   8   9   >