[Tutor] Using Python in Windows

2008-06-25 Thread Ben
Hi,

I'm trying to learn Python in Windows XP. I've been going through the
Python version of Allen Downey's open source textbook. I frequently
find that the instructions he gives don't work for me when I try to
run them in IDLE. For example, in Ch. 4 he says you should load up
GASP (http://openbookproject.net//thinkCSpy/ch04.xhtml#auto10) and
play around with it. Here's what happens when I try what he says to
do:

IDLE 1.2.2
>>> from gasp import *

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

When I try to put all the information in a module, save it, and run
it, I get "there's an error in your program: invalid syntax", and it
highlights instance. Below is what my module looks like.

from gasp import *
begin_graphics()
Circle((200, 200), 60)
Circle instance at (200, 200) with radius 60
Line((100, 400), (580, 200))
Line instance from (100, 400) to (590, 250)
Box((400, 350), 120, 100)
Box instance at (400, 350) with width 120 and height 100
end_graphics()

Similarly, I can't get the truth table to work in the Exercises
section at the bottom of ch. 4. I'm wondering if this is because I'm
using Windows. I've tried using Ubuntu, and it doesn't display
correctly.

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


Re: [Tutor] Astonishing timing result

2008-06-25 Thread Kent Johnson
On Wed, Jun 25, 2008 at 1:16 AM, Dick Moores <[EMAIL PROTECTED]> wrote:
> At 07:00 PM 6/24/2008, Marilyn Davis wrote:
>
>> Has anyone ever timed the difference between using a function that was
>> imported with:
>>
>> from my_module import MyFunction
>>
>> and:
>>
>> import my_module
>
> Here are 2 comparisons: , and
>  
>
> I don't see a significant difference.

I wouldn't expect much. The only difference is the extra attribute
lookup in the second form. Attribute lookup is slow enough to be
measurable and fast enough that you will only care if you are doing it
a lot of times.

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


Re: [Tutor] Using Python in Windows

2008-06-25 Thread broek


- Message from [EMAIL PROTECTED] -
Date: Tue, 24 Jun 2008 18:27:59 -0700
From: Ben <[EMAIL PROTECTED]>



Hi,

I'm trying to learn Python in Windows XP. I've been going through the
Python version of Allen Downey's open source textbook. I frequently
find that the instructions he gives don't work for me when I try to
run them in IDLE. For example, in Ch. 4 he says you should load up
GASP (http://openbookproject.net//thinkCSpy/ch04.xhtml#auto10) and
play around with it. Here's what happens when I try what he says to
do:

IDLE 1.2.2

from gasp import *


Traceback (most recent call last):
 File "", line 1, in 
   from gasp import *
ImportError: No module named gasp





Hi Ben,

gasp isn't part of python; it is a module specific to the book you are  
reading. There should be a link somewhere on the book's site from  
which you can dowload it.



When I try to put all the information in a module, save it, and run
it, I get "there's an error in your program: invalid syntax", and it
highlights instance. Below is what my module looks like.

from gasp import *
begin_graphics()
Circle((200, 200), 60)
Circle instance at (200, 200) with radius 60
Line((100, 400), (580, 200))
Line instance from (100, 400) to (590, 250)
Box((400, 350), 120, 100)
Box instance at (400, 350) with width 120 and height 100
end_graphics()


If you look at the page again, you will see that the relevant text looks like:


from gasp import *
begin_graphics()
Circle((200, 200), 60)

Circle instance at (200, 200) with radius 60

Line((100, 400), (580, 200))

Line instance from (100, 400) to (590, 250)

Box((400, 350), 120, 100)

Box instance at (400, 350) with width 120 and height 100

end_graphics()



The `>>>' are the prompts for the interactive interpreter[*] and the  
lines without them are the results of running the commands typed at  
the prompts. So, if you want to put it into a module, you will have to  
include only the `>>>' lines (don't include the `>>>'s themselves,  
though.


[*] Do you know what I mean by `interactive interpreter'?

Trying to run that will take you back to your first problem. So, see  
if you can find a download link for the module on the book's site, and  
give it another go. Report back if still stymied.


Best,

Brian vdB


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


Re: [Tutor] Hands-on beginner's project?

2008-06-25 Thread Jacqui
Hi, I'm a total newbie too, and I'm kind of replying to see if my
instinct on the whole GOTO thing is correct. It's hard to learn a
language without any feedback!

I used GW and Color Basic when I was a kid so I know all about GOTO (and
it was a mess! I programmed one of those interactive stories in grade 12
using it, it took all semester and was anything but elegant!)

I would expect with Python, instead of using GOTO you use defined
functions.

So for instance, you could define chapters as functions


def chapter2():
print "You've chosen to leap over the chasm"
print "too bad you forgot you were carrying an anvil"
print "What part of b-bye don't you understand?"


so that in your code, instead of 

> 0100  print "Ahead of you, you see a chasm.
> 0200 jump = raw_input("Do you wish to try jumping over it? Y/N")
> 0300 if jump = Y:
> 0400   goto 1700
> 0500 if jump = N:
> 0600  goto 2100

you could have

> 0100  print "Ahead of you, you see a chasm."
> 0200 jumpQ = raw_input("Do you wish to try jumping over it? y/n: ")
> 0300 if jumpQ == "y":
> 0400  chapter2()
> 0500 elif jumpQ == "n":
> 0600  chapter3()

I just tried this bit out

def chapter1():
print "this is an interactive story test"
print

def chapter2():
print "You have chosen to leap across the chasm"
print "Sadly you forgot you are carrying an anvil"
print "What part of b-bye don't you understand?"

def chapter3():
print "You wisely chose to turn back home"
print "The anvil you are carrying would surely cause you"
print "to plummet to your death"



def main():
chapter1()
print "You come across a chasm, would you like to jump?"
jumpQ = raw_input("y/n: ")
if jumpQ == "y":
chapter2()
elif jumpQ == "n":
chapter3()
main()

and it worked although I have doubts about how good it would be overall
once the story got very involved. I'm interested to see what others
think.

Jacqui

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


Re: [Tutor] python web documentation ( without frameworks?)

2008-06-25 Thread Kent Johnson
On Tue, Jun 24, 2008 at 11:00 PM, Patrick <[EMAIL PROTECTED]> wrote:
> Hi Everyone
>
> This is my first post here. I would like to switch from php/mysql to
> python(mod_python) and postgresql. There are several recent books on
> cherrypy, django and turbogears but for some reason I just don't want to use
> a framework. Are there any current books you could recommend for general
> python web programming? Most of the general web programming books seem to be
> from 2004 or before.

If you don't want to use a framework that pretty much limits you to
plain CGI or mod_python handlers. They don't provide much so there is
not much documentation. At this level of programming I don't think
much has changed since 2004. The cgi module docs are one place to
start:
http://docs.python.org/lib/module-cgi.html

Foundations of Network Programming covers many different aspects of
network programming including a chapter on CGI:
http://www.apress.com/book/view/1590593715

My guess is that, coming from php, you will find this level of web
programming to be pretty primitive and you will soon be looking at the
frameworks or at least a templating package.

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


[Tutor] Transporting Voices For Sapi

2008-06-25 Thread FT


Hi!

I am sending the latest version of my voice package and 2 different
tests. When compiling the Voice2.py you may get an error if you do not have
MSVcp.dll copied into your setup.py file. In other words a copy command to
copy the dll from your system32 folder. For if you do not, some computers it
is run on will fail if they do not have that dll installed.

I noticed that when compiling the Voice2 using py2exe and sending it to
someone else that it does not take the voices with it. I was wondering if
anyone knows how that can be done? How to wrap the voices you have installed
into the py2exe compiled version?

Sincerely
Bruce

#DRIVERS FOR SAPI 5 AND VOICES!
#NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE VALUES.
from comtypes.client import CreateObject
import _winreg

class constants4tts:
Wait = -1
Sync = 0
Async = 1
Purge = 2
Is_filename = 4
XML = 8
Not_XML = 16
Persist = 32
Punc = 64

class SynthDriver():
name="sapi5"
description="Microsoft Speech API version 5 (sapi.SPVoice)"
_voice = 0
_pitch = 0
_voices = []
_wait = -1 #WAIT INDEFINITELY
_sync = 0 #WAIT UNTIL SPEECH IS DONE.
_async = 1 #DO NOT WAIT FOR SPEECH
_purge = 2 #CLEAR SPEAKING BUFFER
_is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE
_xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER.
_not_xml = 16 #NO XML COMMANDS
_persist_xml = 32 #Changes made in one speak command persist to other calls 
to Speak.
_punc = 64 #PRONOUNCE ALL PUNCTUATION!
def check(self):
try:
r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice")
r.Close()
return True
except:
return False
#INITIALIZE ENGINE!
def init(self):
try:
self.tts = CreateObject( 'sapi.SPVoice')
self._voice=0
self._voiceCount = len(self.tts.GetVoices())
for v in range(self._voiceCount):
self._voices.append( self.tts.GetVoices()[v])
return True
except:
return False
#TERMINATE INSTANCE OF ENGINE!
def terminate(self):
del self.tts
#NUMBER OF VOICES FOR ENGINE!
def getVoiceCount(self):
return len(self.tts.GetVoices())
#NAME OF A VOICE BY NUMBER!
def getVoiceNameByNum(self, num):
return self.tts.GetVoices()[ num].GetDescription()
#NAME OF A VOICE!
def getVoiceName(self):
return self.tts.GetVoices()[ self._voice].GetDescription()
#WHAT IS VOICE RATE?
def getRate(self):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
return (self.tts.rate)
#WHAT IS THE VOICE PITCH?
def getPitch(self):
"PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!"
return self._pitch
#GET THE ENGINE VOLUME!
def getVolume(self):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
return self.tts.volume
#GET THE VOICE NUMBER!
def getVoiceNum(self):
return self._voice
#SET A VOICE BY NAME!
def setVoiceByName(self, name):
"VOICE IS SET BY NAME!"
for i in range( self._voiceCount):
if self.tts.GetVoices()[ i].GetDescription().find( name) >= 0:
self.tts.Voice = self._voices[i]
#self.tts.Speak( "%s Set!" % name)
self._voice=i
break
if i >= self._voiceCount:
self.tts.Speak( "%s Not Found!" % name)
#USED FOR BOOKMARKING AND USE LATER!
def _get_lastIndex(self):
bookmark=self.tts.status.LastBookmark
if bookmark!="" and bookmark is not None:
return int(bookmark)
else:
return -1
#NOW SET ENGINE PARMS!
#SET THE VOICE RATE!
def setRate(self, rate):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
if rate > 10: rate = 10
if rate < -10: rate = -10
self.tts.Rate = rate
#SET PITCH OF THE VOICE!
def setPitch(self, value):
"MICROSOFT SAPI 5 pitch is really controled with xml around speECH TEXT 
AND IS -10 TO 10"
if value > 10: value = 10
if value < -10: value = -10
self._pitch=value
#SET THE VOICE VOLUME!
def setVolume(self, value):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
self.tts.Volume = value
#CREATE ANOTHER INSTANCE OF A VOICE!
def createVoice(self, name):
num = 0
for i in range( self._voiceCount):
if self.tts.GetVoices()[ i].GetDescription().find( name) >= 0:
num=i
break
new_tts = CreateObject( 'sapi.SPVoice')
new_tts.Voice = self._voices[ num]
return (new_tts)
#SPEAKING TEXT!
#SPEAK TEXT USING BOOKMARKS AND PITCH!
def SpeakText(self, text, wait=False, index=None):
"SPEAK TEXT AND XML FOR PITCH MUST REPLACE ANY <> SYMBOLS BEFORE USING 
XML BRACKETED TEXT"
flags = constants4tts.XML
text = text.replace( "<", "<")
pitch = ((self._pitch*2)-100)/10
if isinstance(index

Re: [Tutor] Hands-on beginner's project?

2008-06-25 Thread Cédric Lucantis
Le Wednesday 25 June 2008 12:16:24 Jacqui, vous avez écrit :
> Hi, I'm a total newbie too, and I'm kind of replying to see if my
> instinct on the whole GOTO thing is correct. It's hard to learn a
> language without any feedback!
>
> I used GW and Color Basic when I was a kid so I know all about GOTO (and
> it was a mess! I programmed one of those interactive stories in grade 12
> using it, it took all semester and was anything but elegant!)
>
> I would expect with Python, instead of using GOTO you use defined
> functions.
>
> So for instance, you could define chapters as functions
>
> I just tried this bit out
>
> def chapter1():
> print "this is an interactive story test"
> print
>
> def chapter2():
> print "You have chosen to leap across the chasm"
> print "Sadly you forgot you are carrying an anvil"
> print "What part of b-bye don't you understand?"
>
> def chapter3():
> print "You wisely chose to turn back home"
> print "The anvil you are carrying would surely cause you"
> print "to plummet to your death"
>
>
>
> def main():
> chapter1()
> print "You come across a chasm, would you like to jump?"
> jumpQ = raw_input("y/n: ")
> if jumpQ == "y":
> chapter2()
> elif jumpQ == "n":
> chapter3()
> main()
>
> and it worked although I have doubts about how good it would be overall
> once the story got very involved. I'm interested to see what others
> think.
>


You instinct is not too bad :) but the main function will soon become 
unreadable and very hard to modify. In your examples the functions act as 
simple strings, you could write it like this:

chapter1 = "This is an interactive story test"
chapter2 = "..."

def main () :
print chapter1
...

One problem is that in such a game you often go back on your step and read the 
same chapter several times (ie there might be cycles in the story graph). 
This would be impossible to do this way. But the idea is not so bad, if the 
game logic is rather handled by the chapter function itself:

def chapter1 () :
print "You come across a chasm, would you like to jump?"
jumpQ = raw_input("y/n: ")
if jumpQ == "y":
chapter2()
elif jumpQ == "n":
chapter3()

def chapter2 () :
print "OK, but you can still change your mind"
r = raw_input("go back to the chasm ?")
if r == "y" :
chapter1()
else :
chapter4()

def main () :
chapter1()

Which introduces another problem: as functions/chapters will be called in 
chain (chapter1 calls chapter2 which calls chapterX...), you will soon fill 
the system stack and end with a 'maximum recursion error'. But in python 
functions are objects which can be handled like anything else, so they could 
return the destination chapter rather than calling it directly, and a main 
loop would do the job of calling them (note there is no () after the "return 
chapterX", so we return the function itself without calling it) :

def chapter1 () :
print "..."
r = raw_input("y/n: ")
if r == "y" :
return chapter2
else :
return chapter3

def chapter2 () :
...

def main () :

# Store the 'chapter1' function in 'current_chapter'
# without calling it
current_chapter = chapter1

while True :

# Call the function stored in current_chapter
# and keep the returned function object.
# Could also be written as 'current_chapter = current_chapter()'
next_chapter = current_chapter()
current_chapter = next_chapter

This way the 'main' function won't have to be modified and the content of each 
chapter is kept in a simple logical unit. It will make the future 
modifications much easier.

-- 
Cédric Lucantis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Transporting Voices For Sapi and DLL Correction

2008-06-25 Thread FT




Hi!

I am sending the latest version of my voice package and 2 different
tests. When compiling the Voice2.py you may get an error if you do not have
MSVcp71.dll copied into your setup.py file. In other words a copy command to
copy the dll from your system32 folder. For if you do not, some computers it
is run on will fail if they do not have that dll installed.

I noticed that when compiling the Voice2 using py2exe and sending it to
someone else that it does not take the voices with it. I was wondering if
anyone knows how that can be done? How to wrap the voices you have installed
into the py2exe compiled version?

Sincerely
Bruce







___
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] Hands-on beginner's project?

2008-06-25 Thread bob gailer

Jacqui wrote:

Hi, I'm a total newbie too, and I'm kind of replying to see if my
instinct on the whole GOTO thing is correct. It's hard to learn a
language without any feedback!

I used GW and Color Basic when I was a kid so I know all about GOTO (and
it was a mess! I programmed one of those interactive stories in grade 12
using it, it took all semester and was anything but elegant!)

I would expect with Python, instead of using GOTO you use defined
functions.

So for instance, you could define chapters as functions


def chapter2():
print "You've chosen to leap over the chasm"
print "too bad you forgot you were carrying an anvil"
print "What part of b-bye don't you understand?"
  


Even better is to define a Chapter class, with the various properties 
and methods pertinent thereto, then make each chapter an instance of 
that class.


class Chapter:

 def __init__(self, desc, ques=None, **actions):
   self.desc = desc
   self.ques = ques
   self.actions = actions
   self.prompt = ", ".join(actions.keys())
   
 def describe(self):

   print self.desc

 def ask(self):
   if self.ques:
 print self.ques
 for i in range(10):
   ans = raw_input(self.prompt).lower()
   next = self.actions.get(ans, None)
   if next:
 return next
   else:
 print "Invalid response"
 else:
   print "Too many failed attempts"
 
def main():

 chapters = [None]*11 # allow for 10 chapters starting with 1
 chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to 
jump over it?", y=2, n=3)

 chapters[2] = Chapter("Oops - that anvil is heavy. You die.")
 chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5)
 chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, w=2)
 chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3)
 chapters[6] = Chapter("Congratulations - you found the gold.")
 next = 1
 while True:
   chapter = chapters[next]
   chapter.describe()
   next = chapter.ask()
   if not next:
 print "Game over"
 break

main()   


--
Bob Gailer
919-636-4239 Chapel Hill, NC

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


Re: [Tutor] Hands-on beginner's project? CORRECTION

2008-06-25 Thread bob gailer

bob gailer wrote:

Jacqui wrote:

Hi, I'm a total newbie too, and I'm kind of replying to see if my
instinct on the whole GOTO thing is correct. It's hard to learn a
language without any feedback!

I used GW and Color Basic when I was a kid so I know all about GOTO (and
it was a mess! I programmed one of those interactive stories in grade 12
using it, it took all semester and was anything but elegant!)

I would expect with Python, instead of using GOTO you use defined
functions.

So for instance, you could define chapters as functions


def chapter2():
print "You've chosen to leap over the chasm"
print "too bad you forgot you were carrying an anvil"
print "What part of b-bye don't you understand?"
  


Even better is to define a Chapter class, with the various properties 
and methods pertinent thereto, then make each chapter an instance of 
that class.


class Chapter:

 def __init__(self, desc, ques=None, **actions):
   self.desc = desc
   self.ques = ques
   self.actions = actions
   self.prompt = ", ".join(actions.keys())
def describe(self):
   print self.desc

 def ask(self):
   if self.ques:
 print self.ques
 for i in range(10):
   ans = raw_input(self.prompt).lower()
   next = self.actions.get(ans, None)
   if next:
 return next
   else:
 print "Invalid response"
 else:
   print "Too many failed attempts"

# CORRECTION - indent

def main():
 chapters = [None]*11 # allow for 10 chapters starting with 1
 chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to 
jump over it?", y=2, n=3)

 chapters[2] = Chapter("Oops - that anvil is heavy. You die.")
 chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5)
 chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, 
w=2)

 chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3)
 chapters[6] = Chapter("Congratulations - you found the gold.")
 next = 1
 while True:
   chapter = chapters[next]
   chapter.describe()
   next = chapter.ask()
   if not next:
 print "Game over"
 break

main()  



--
Bob Gailer
919-636-4239 Chapel Hill, NC

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


Re: [Tutor] Hands-on beginner's project?

2008-06-25 Thread Jacqui
LOL You rock! That's definitely better than my example. I can't wait to
get better at this!

:-D

On Wed, 2008-06-25 at 09:22 -0400, bob gailer wrote:
> >   
> 
> Even better is to define a Chapter class, with the various properties 
> and methods pertinent thereto, then make each chapter an instance of 
> that class.
> 
> class Chapter:
> 
>   def __init__(self, desc, ques=None, **actions):
> self.desc = desc
> self.ques = ques
> self.actions = actions
> self.prompt = ", ".join(actions.keys())
> 
>   def describe(self):
> print self.desc
> 
>   def ask(self):
> if self.ques:
>   print self.ques
>   for i in range(10):
> ans = raw_input(self.prompt).lower()
> next = self.actions.get(ans, None)
> if next:
>   return next
> else:
>   print "Invalid response"
>   else:
> print "Too many failed attempts"
>   
> def main():
>   chapters = [None]*11 # allow for 10 chapters starting with 1
>   chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to 
> jump over it?", y=2, n=3)
>   chapters[2] = Chapter("Oops - that anvil is heavy. You die.")
>   chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5)
>   chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, w=2)
>   chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3)
>   chapters[6] = Chapter("Congratulations - you found the gold.")
>   next = 1
>   while True:
> chapter = chapters[next]
> chapter.describe()
> next = chapter.ask()
> if not next:
>   print "Game over"
>   break
> 
> main()   
> 

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


Re: [Tutor] Hands-on beginner's project?

2008-06-25 Thread bhaaluu
Brian Wisti has a very nice tutorial for Python beginners that uses Interactive
Fiction as the basis of a tutorial:

http://coolnamehere.com/geekery/python/ifiction/index.html
http://coolnamehere.com/geekery/python/ifiction/single-round.html
http://coolnamehere.com/geekery/python/ifiction/multiple-scenes.html
http://coolnamehere.com/geekery/python/ifiction/multiple-turns.html

Paul McGuire made an example adventure game using pyparsing:

http://wiki.python.org/moin/PyCon2006/Talks#4
http://www.geocities.com/ptmcg/python/pycon06/adventureEngine.py.txt

(you'll need the pyparsing package for it to work)

http://pyparsing.wikispaces.com/

Python Universe Builder (PUB) is an Interactive Fiction module for
Python. It provides a
programming environment similar to that of Inform or TADS but runs
under any Python
interpreter.

http://py-universe.sourceforge.net/

Here's a link to the Interactive Fiction archive containing a huge
array of text adventure
games and other adventure development tools.

http://www.ifarchive.org/

And finally, another link to TAGs based on Creating Adventure Games On
Your Computer.
http://www.geocities.com/ek.bhaaluu/python/index.html

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!


On Wed, Jun 25, 2008 at 9:39 AM, Jacqui <[EMAIL PROTECTED]> wrote:
> LOL You rock! That's definitely better than my example. I can't wait to
> get better at this!
>
> :-D
>
> On Wed, 2008-06-25 at 09:22 -0400, bob gailer wrote:
>> >
>>
>> Even better is to define a Chapter class, with the various properties
>> and methods pertinent thereto, then make each chapter an instance of
>> that class.
>>
>> class Chapter:
>>
>>   def __init__(self, desc, ques=None, **actions):
>> self.desc = desc
>> self.ques = ques
>> self.actions = actions
>> self.prompt = ", ".join(actions.keys())
>>
>>   def describe(self):
>> print self.desc
>>
>>   def ask(self):
>> if self.ques:
>>   print self.ques
>>   for i in range(10):
>> ans = raw_input(self.prompt).lower()
>> next = self.actions.get(ans, None)
>> if next:
>>   return next
>> else:
>>   print "Invalid response"
>>   else:
>> print "Too many failed attempts"
>>
>> def main():
>>   chapters = [None]*11 # allow for 10 chapters starting with 1
>>   chapters[1] = Chapter("Ahead of you, you see a chasm.", "Attempt to
>> jump over it?", y=2, n=3)
>>   chapters[2] = Chapter("Oops - that anvil is heavy. You die.")
>>   chapters[3] = Chapter("Good choice.", "Pick a direction", n=4, s=5)
>>   chapters[4] = Chapter("It's cold in here.", "Pick a direction", e=1, w=2)
>>   chapters[5] = Chapter("It's hot in here.", "Pick a direction", u=6, d=3)
>>   chapters[6] = Chapter("Congratulations - you found the gold.")
>>   next = 1
>>   while True:
>> chapter = chapters[next]
>> chapter.describe()
>> next = chapter.ask()
>> if not next:
>>   print "Game over"
>>   break
>>
>> main()
>>
>
> ___
> 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] Another Newbie question

2008-06-25 Thread Lie Ryan
That's because you're doing it in interactive mode. In interactive mode,
the code is treated like commands, it is executed immediately after the
command is finished. You may differentiate Interactive Mode and
Normal/Coding Mode by the prompt, in Coding Mode there is no prompt
cause, in Interactive mode, there is the '>>>' (default)

Example in Interactive Mode:
>>> print 'Blah blah blah'
Blah blah blah
>>> for i in xrange(5):
... print i
...
0
1
2
3
4
>>>

Some "commands", like 'for', 'while', dictionary literal, etc may
require more than one line, for those, the secondary prompt is shown
'...', although that depends on how you start python, if you started
python from IDLE, the secondary prompt is not, by default, shown.

That's a bit basic.

Now to the specific reason why python (interactive mode) "doesn't wait"
you to finish your command. In interactive mode, a blank line is
considered to be the end of multi-line command, so:

>>> for i in xrange(4):
... print i
... # The next line is empty
...
0
1
2
3
>>> 

that empty line is an instruction to start executing the multi-line
commands immediately (or another way to see it, an empty line is
considered to be the end of current instruction)

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


Re: [Tutor] Astonishing timing result

2008-06-25 Thread Lie Ryan
I'm a bit curious about how you do the timing. I think there is a flaw
in how you measured the time. I made this code and the result is
inconclusive.

## CODE: test.py
#!/usr/bin/env python

import imported
import time
from imported import *


def b():
a = 1

r = range(500)
t_a, t_b, t_c, t_d = 1000, 1000, 1000, 1000
for n in xrange(20):
# a - direct, no function call
start = time.time()
for _ in r:
a = 1
end = time.time()
t_A = end - start

# b - function call
start = time.time()
for _ in r:
b()
end = time.time()
t_B = end - start

# c - imported module
start = time.time()
for _ in r:
imported.c()
end = time.time()
t_C = end - start

# d - imported function
start = time.time()
for _ in r:
c()
end = time.time()
t_D = end - start

t_a = min(t_A, t_a)
t_b = min(t_A, t_b)
t_c = min(t_A, t_c)
t_d = min(t_A, t_d)

print t_a
print t_b
print t_c
print t_d

## CODE: imported.py
def c():
a = 1

## OUTPUT
# 1.02956604958
# 1.02956604958
# 1.02956604958
# 1.02956604958



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


Re: [Tutor] Hands-on beginner's project?

2008-06-25 Thread Lie Ryan
If it was me, I'd elaborate it a bit more by separating between program
(logic) and story (data). This would make it possible to tell story
without touching the program's code.

like this (in pseudocode):

# main.py

def querier(query):
while True:
print query.prompt
t = raw_input()
if t in query.ans:
return query.ans[t]
else:
print 'Unrecognized prompt'

def tell(storyfile):
""" Tell a story and process response """
# read from the storyfile, the  node
print storyfile.story

try:
if storyfile.end:
quit()
except AttributeError:
pass

# process the prompts and answers
if storyfile.query:
return querier(storyfile.query)

def main():
while True:
nextstory = tell(story)
if nextstory = ending:
break
else:
story = nextstory


# chapter1.sto

  this is an interactive story test


  You come across a chasm, would you like to jump?
  y
  n


# chapter2.sto

  You have chosen to leap across the chasm
  Sadly you forgot you are carrying an anvil
  What part of b-bye don't you understand?



# chapter3.sto

  You wisely chose to turn back home
  The anvil you are carrying would surely cause you
  to plummet to your death



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


Re: [Tutor] Astonishing timing result

2008-06-25 Thread Kent Johnson
On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:

>t_a = min(t_A, t_a)
>t_b = min(t_A, t_b)
>t_c = min(t_A, t_c)
>t_d = min(t_A, t_d)

What is this for? It should at least be t_B, t_C, t_D.

> ## OUTPUT
> # 1.02956604958
> # 1.02956604958
> # 1.02956604958
> # 1.02956604958

It's *very easy* to write bogus timing tests, as this thread
demonstrates. Some protections:
- when comparing different implementations of a function, make sure
each implementation returns the correct result by checking the return
value. You probably want to make this check outside the actual timing
test.
- when your results don't make sense, suspect your tests.

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


Re: [Tutor] Astonishing timing result

2008-06-25 Thread Lie Ryan
On Wed, 2008-06-25 at 12:56 -0400, Kent Johnson wrote:
> On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:
> 
> >t_a = min(t_A, t_a)
> >t_b = min(t_A, t_b)
> >t_c = min(t_A, t_c)
> >t_d = min(t_A, t_d)
> 
> What is this for? It should at least be t_B, t_C, t_D.

A common pitfall in benchmarking is averaging the benchmark result. That
is WRONG, FLAT WRONG. Why? Variations of how long a code is executed is
caused by the environment, not the code itself. The correct way to
benchmark is to use the one with the lowest time (i.e. min() function),
since the lowest one is the one that is least interfered by the
environment.

> > ## OUTPUT
> > # 1.02956604958
> > # 1.02956604958
> > # 1.02956604958
> > # 1.02956604958
> 
> It's *very easy* to write bogus timing tests, as this thread
> demonstrates. Some protections:
> - when comparing different implementations of a function, make sure
> each implementation returns the correct result by checking the return
> value. 

Since the purpose of the test is to benchmark the difference of where
the code is located, we should use a very simple function, that doesn't
even do much of anything, thus 'a = 1'. If that simple code is
substituted with anything else, I'm still confident that the result
won't be far off.

> You probably want to make this check outside the actual timing
> test.

Actually the timing is all equal because of the timer's resolution. I
don't have a high-precision timer on hand.

> - when your results don't make sense, suspect your tests.



> Kent
> Kent

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


Re: [Tutor] Tutor Digest, Vol 52, Issue 69

2008-06-25 Thread kinuthiA muchanE

On Wed, 2008-06-25 at 01:49 +0200, [EMAIL PROTECTED] wrote:
> > ... or you could start you fire up a text editor (something like 
> > Notepad
> > in Windows, or nano in Linux and type "3+4"(without the quotes!),
> 
> Actually it would need to be
> 
> print 3+4
> 
> otherwise Python would silently evaluate the expression but

> not display the result.

Oh my, I was in the middle of something, something like
http://projecteuler.net/index.php?section=problems&id=74 
> 
> > One of the indefatigable contributors to this mailing list, Alan 
> > Gauld
> > (where do you get the time?),
> 
> With increasing difficulty! :-)
I can understand that.
> 
> > Check it out at http://www.freenetpages.co.uk/hp/alan.gauld 
> > (correct?)
> 
> Correct, thanks for the plug!
> 
> Sadly it will need to move soon since Freenet have
> announced that they will soon be decommissioning
> their free web site(*). I'm trying to decide whether to go to
> another free site or spend the money for a proper
> hosted site with dedicated domain name etc...
Here (in Kenya) the cheapest unlimited internet access option costs you
around 9600 Kenya Shillings, about $146 a month! I am already stumped!
> 
> (*) They have already blocked ftp so I can't post updates
> anymore :-(
Dommage, dommage...
> 

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


Re: [Tutor] Astonishing timing result

2008-06-25 Thread Kent Johnson
On Wed, Jun 25, 2008 at 2:06 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:
> On Wed, 2008-06-25 at 12:56 -0400, Kent Johnson wrote:
>> On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:
>>
>> >t_a = min(t_A, t_a)
>> >t_b = min(t_A, t_b)
>> >t_c = min(t_A, t_c)
>> >t_d = min(t_A, t_d)
>>
>> What is this for? It should at least be t_B, t_C, t_D.
>
> A common pitfall in benchmarking is averaging the benchmark result. That
> is WRONG, FLAT WRONG.

Yes, I agree. I missed the outer loop that this is in. But your code
is still WRONG, FLAT WRONG!
 t_b = min( *** t_A ***, t_b) // should be t_B, etc.

>> > ## OUTPUT
>> > # 1.02956604958
>> > # 1.02956604958
>> > # 1.02956604958
>> > # 1.02956604958
>>
>> It's *very easy* to write bogus timing tests, as this thread
>> demonstrates. Some protections:
>> - when comparing different implementations of a function, make sure
>> each implementation returns the correct result by checking the return
>> value.

> Actually the timing is all equal because of the timer's resolution. I
> don't have a high-precision timer on hand.

Or maybe they are all equal because they are all t_A...

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


Re: [Tutor] python web documentation ( without frameworks?)

2008-06-25 Thread Alan Gauld


"Patrick" <[EMAIL PROTECTED]> wrote

cherrypy, django and turbogears but for some reason I just don't 
want to use a framework. Are there any current books you could 
recommend for general python web programming? Most of the general 
web programming books seem to be from 2004 or before.


There's a good reason for that! Vanilla CGI - the most basic web
programming mechanism available is a rsource hog, non scaleable
and very hard to maintain beyiond small trivial projects. So people
have moved to Frameworks which offer better performance,
easier implementation and far better maintainablility. All Frameworks
aim to achieve that, the choice is pretty much a personal prefernce.

The good news is that if you want to continuously reinvent the wheel
by using vanilla CGI the books from 2004 will all pretty much still 
work.

CGI hasn't changed much and neither have the core web modules in
Python.

HTH,



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


[Tutor] Removing files based upon time stamps

2008-06-25 Thread chase pettet
I'm trying to create a basic script that will remove old backup files (more
than 30 days) from a directory based upon timestamp.  The system it will run
on is Windows XP.  I created this and ran it on one box and it seemed to
work fine, when I ported it to the actual box it needs to run on it is not
removing the files.  I ran the script with "python -i" so it dumped me into
interactive mode and I confirmed that the current object was ok, I confirmed
it is in the correct directory, I confirmed I could so a manual
os.remove("file") and it would actually delete the file.  This makes me
think it is not a permissions issue.  But when I run the script it is a no
go.  I'm basically at a loss as to what to try for troubleshooting next.
Backstory, this directory is an iis ftp directory if that makes a
difference.

import os, time, sys
current = time.time()
os.chdir("c:\BACKUPS\DEV1")

for f in os.listdir('.'):
  modtime = os.path.getmtime('.')
  if modtime < current - 30 * 86400:
os.remove(f)


This is my first list post.  Thanks for any help!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Astonishing timing result

2008-06-25 Thread Lie Ryan
On Wed, 2008-06-25 at 15:53 -0400, Kent Johnson wrote:
> On Wed, Jun 25, 2008 at 2:06 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:
> > On Wed, 2008-06-25 at 12:56 -0400, Kent Johnson wrote:
> >> On Wed, Jun 25, 2008 at 12:05 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:
> >>
> >> >t_a = min(t_A, t_a)
> >> >t_b = min(t_A, t_b)
> >> >t_c = min(t_A, t_c)
> >> >t_d = min(t_A, t_d)
> >>
> >> What is this for? It should at least be t_B, t_C, t_D.
> >
> > A common pitfall in benchmarking is averaging the benchmark result. That
> > is WRONG, FLAT WRONG.
> 
> Yes, I agree. I missed the outer loop that this is in. But your code
> is still WRONG, FLAT WRONG!
>  t_b = min( *** t_A ***, t_b) // should be t_B, etc.

Ah, yes sorry, a slip of hand when copying the code.

The corrected timing.

Outer loop: 10x
Inner Loop: 500x
per Innerloop   Overall
a | 1.05028605461 | 10.6743688583
b | 2.21457099915 | 22.3394482136
c | 3.53437685966 | 35.6701157093
d | 2.5965359211  | 26.1492891312

Overall Running Time: 94.8337771893

Well, it's obvious that direct-method is the fastest, simply because it
bypasses function calling and module name look up overhead. Method C
(module) is the slowest because the name look up is done twice, the
module's name then the function's name inside the module, then function
calling. But anyway, considering that this overhead of (3.5 - 1 = 2.5
second) is accumulated over 5 000 000 iteration, it is silly to to use
method-a (not using function and method) for reason of speed. The
difference between method a and c is 2.5 second / 5 000 000 = 0.005
second = 0.5 microsecond. (DISCLAIMER: Timing is valid on my machine
only)

Sure, at a glance, it seems that the saving is good enough 1:3.5, that's
28.6% a saving of 71.4%, but remember that most functions are much more
complex than this 'a = 1', to put it into perspective:

a = n**2
Outer loop: 10x
Inner Loop: 500x
a | 2.1795668602 | 21.9916498661
b | 3.4880130291 | 35.1593179703
c | 4.97427606583 | 50.6705505848
d | 3.84812307358 | 39.1990897655

time: 43%, saving 57%

'a = math.sqrt(n ** 2 + n ** 2)'
'print 1'
Outer loop: 10x
Inner Loop: 5x
a | 0.805603027344 | 8.24900960922
b | 0.921233177185 | 9.31604623795
c | 1.03809094429 | 10.4301710129
d | 0.956300973892 | 9.58661794662
Total Time:  37.582244873

time: 78%, saving: 22%

'print 1'
Outer loop: 10x
Inner Loop: 5x
per Innerloop   Overall
a | 0.573838949203 | 6.04536104202
b | 0.578473091125 | 6.05607891083
c | 0.579005002975 | 6.08867025375
d | 0.570523023605 | 5.93990397453

Negligible.

So unless your function is extremely simple like 'a = 1', there is no
benefit of avoiding function/methods. A single print statement (print is
a very slow function/statement) would immediately nullify the speed
gain. Even an intermediate complexity function would make the saving
useless, and to think about it, I think nobody would make 'a = 1' to be
a function right? 

> >> > ## OUTPUT
> >> > # 1.02956604958
> >> > # 1.02956604958
> >> > # 1.02956604958
> >> > # 1.02956604958
> >>
> >> It's *very easy* to write bogus timing tests, as this thread
> >> demonstrates. Some protections:
> >> - when comparing different implementations of a function, make sure
> >> each implementation returns the correct result by checking the return
> >> value.
> 
> > Actually the timing is all equal because of the timer's resolution. I
> > don't have a high-precision timer on hand.
> 
> Or maybe they are all equal because they are all t_A...
> 
> Kent

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


[Tutor] Removing files based upon time stamps

2008-06-25 Thread Lie Ryan
I'm not sure what caused your problem, but...

> os.chdir("c:\BACKUPS\DEV1")

This is a no-no. What if you have a path like this:
'C:\nice\try'

what do you think would python be doing?
It would parse \n as newline and \t as tab

You should do this instead:
r'C:\nice\try'
OR
'C:\\nice\\try'

the first way is called raw string, the backslash lose its meaning
the second way is by escaping the backslash.

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


Re: [Tutor] Removing files based upon time stamps

2008-06-25 Thread Steve Willoughby

You might also want to consider using the path walk
facility in Python's standard lib as well, so you
can recurse into subdirectories doing this (if that
is helpful)
-- 
Steve Willoughby|  Using billion-dollar satellites
[EMAIL PROTECTED]   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Removing files based upon time stamps

2008-06-25 Thread Steve Willoughby
On Thu, Jun 26, 2008 at 04:53:14AM +0700, Lie Ryan wrote:
> I'm not sure what caused your problem, but...

Look at where you're checking the file time.  You're
not checking the file itself, but '.' (the time of the
current directory).

-- 
Steve Willoughby|  Using billion-dollar satellites
[EMAIL PROTECTED]   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fw: python web documentation ( without frameworks?)

2008-06-25 Thread ALAN GAULD
Forwarding to list.
Please use Reply All when reponding to posts.

- Forwarded Message 
From: Jeff Johnson <[EMAIL PROTECTED]>
To: Alan Gauld <[EMAIL PROTECTED]>
Sent: Wednesday, 25 June, 2008 9:51:33 PM
Subject: Re: [Tutor] python web documentation ( without frameworks?)

This was crazy.  The presenter at our Python user group last night left 
everything at home.  So he proceeded to borrow someone's laptop, 
download and install Python and web.py (http://webpy.org/) and we all 
went through building the demo which displayed records in an SQLite 
table and allowed you to add one and redisplay.  I have used Django and 
web.py works pretty much the same way using templates and all, but 
web.py is significantly "lighter".

You might want to install web.py and go through the demo.  Put it in a 
folder called "deleteme" and you can just delete the folder if you're 
not interested.

Alan Gauld wrote:
> 
> "Patrick" <[EMAIL PROTECTED]> wrote
> 
>> cherrypy, django and turbogears but for some reason I just don't want 
>> to use a framework. Are there any current books you could recommend 
>> for general python web programming? Most of the general web 
>> programming books seem to be from 2004 or before.
> 
> There's a good reason for that! Vanilla CGI - the most basic web
> programming mechanism available is a rsource hog, non scaleable
> and very hard to maintain beyiond small trivial projects. So people
> have moved to Frameworks which offer better performance,
> easier implementation and far better maintainablility. All Frameworks
> aim to achieve that, the choice is pretty much a personal prefernce.
> 
> The good news is that if you want to continuously reinvent the wheel
> by using vanilla CGI the books from 2004 will all pretty much still work.
> CGI hasn't changed much and neither have the core web modules in
> Python.
> 
> HTH,

-- 
Jeff

Jeff Johnson
[EMAIL PROTECTED]
Phoenix Python User Group - [EMAIL PROTECTED]

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


Re: [Tutor] Removing files based upon time stamps

2008-06-25 Thread broek


- Message from [EMAIL PROTECTED] -
Date: Thu, 26 Jun 2008 04:53:14 +0700
From: Lie Ryan <[EMAIL PROTECTED]>
Reply-To: [EMAIL PROTECTED]
 Subject: [Tutor]  Removing files based upon time stamps
  To: tutor@python.org



I'm not sure what caused your problem, but...


?os.chdir("c:\BACKUPS\DEV1")


This is a no-no. What if you have a path like this:
'C:\nice\try'

what do you think would python be doing?
It would parse \n as newline and \t as tab

You should do this instead:
r'?C:\nice\try'
OR
'C:\\nice\\try'

the first way is called raw string, the backslash lose its meaning
the second way is by escaping the backslash.



Or, better still, 'C:/nice/try' --- windows accepts the fwd slash as a  
path separator.


Best,

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


Re: [Tutor] python web documentation ( without frameworks?)

2008-06-25 Thread Patrick

Thanks guys for responding to my post.

I did buy a book on turbogears today and I am watching some screencasts 
as well, I don't want to be ignorant of frameworks.


I don't think anyone could argue that working without a framework is 
better for the majority of people, I can clearly see the value of 
frameworks. However the idea of having a bunch of directories that I 
don't understand does not appeal to me, and learning a framework 
specific way of working with MySql, Postgresql etc rather then their 
native manner won't help me to transfer that knowledge into other areas 
such as desktop applications or other languages such as C.


I have been working with PHP and I don't really like it. However there 
is tons of code out there that I can copy, paste and modify, I don't 
need to re-invent the wheel, just modify it for my own needs. This does 
not seem to be the case with mod_python code.


Would it be logical for me to take python cgi code and rework it for 
mod_python? The two don't seem that different, am I wrong about this?


Kent was saying that working without a framework would be fairly 
primitive, are there features I just can't get without a framework? If 
so why is this? Is a framework not just a collection of off the shelf 
technologies bundled into a slick package? Can I not access the same 
features without a framework?


Am I the only one who wants an end-to-end understanding of my web app? 
Am I crazy? I am feeling a bit alienated here-Patrick



ALAN GAULD wrote:

Forwarding to list.
Please use Reply All when reponding to posts.

- Forwarded Message 
From: Jeff Johnson <[EMAIL PROTECTED]>
To: Alan Gauld <[EMAIL PROTECTED]>
Sent: Wednesday, 25 June, 2008 9:51:33 PM
Subject: Re: [Tutor] python web documentation ( without frameworks?)

This was crazy.  The presenter at our Python user group last night left 
everything at home.  So he proceeded to borrow someone's laptop, 
download and install Python and web.py (http://webpy.org/) and we all 
went through building the demo which displayed records in an SQLite 
table and allowed you to add one and redisplay.  I have used Django and 
web.py works pretty much the same way using templates and all, but 
web.py is significantly "lighter".


You might want to install web.py and go through the demo.  Put it in a 
folder called "deleteme" and you can just delete the folder if you're 
not interested.


Alan Gauld wrote:
  

"Patrick" <[EMAIL PROTECTED]> wrote


cherrypy, django and turbogears but for some reason I just don't want 
to use a framework. Are there any current books you could recommend 
for general python web programming? Most of the general web 
programming books seem to be from 2004 or before.
  

There's a good reason for that! Vanilla CGI - the most basic web
programming mechanism available is a rsource hog, non scaleable
and very hard to maintain beyiond small trivial projects. So people
have moved to Frameworks which offer better performance,
easier implementation and far better maintainablility. All Frameworks
aim to achieve that, the choice is pretty much a personal prefernce.

The good news is that if you want to continuously reinvent the wheel
by using vanilla CGI the books from 2004 will all pretty much still work.
CGI hasn't changed much and neither have the core web modules in
Python.

HTH,



  


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


Re: [Tutor] python web documentation ( without frameworks?)

2008-06-25 Thread Kent Johnson
On Wed, Jun 25, 2008 at 6:47 PM, Patrick <[EMAIL PROTECTED]> wrote:

> I don't think anyone could argue that working without a framework is better
> for the majority of people, I can clearly see the value of frameworks.
> However the idea of having a bunch of directories that I don't understand
> does not appeal to me, and learning a framework specific way of working with
> MySql, Postgresql etc rather then their native manner won't help me to
> transfer that knowledge into other areas such as desktop applications or
> other languages such as C.

There are a number of different ways of working with databases in
Python. You can use DB-API which is a fairly simple interface to SQL.
You can use SQLAlchemy to make easier to write the SQL. You can use
SQLAlchemy, SQLObject or other ORMs to hide the SQL pretty thoroughly.
Most of these methods are portable to other Python apps including
desktop apps. None of them are truly portable to other languages
though if you stick with DB-API the SQL knowledge will certainly apply
in other languages.
>
> I have been working with PHP and I don't really like it. However there is
> tons of code out there that I can copy, paste and modify, I don't need to
> re-invent the wheel, just modify it for my own needs. This does not seem to
> be the case with mod_python code.

mod_python by itself is not too popular IMO.

> Would it be logical for me to take python cgi code and rework it for
> mod_python? The two don't seem that different, am I wrong about this?

I think you could do that. Do you have Python CGI code to start with?

> Kent was saying that working without a framework would be fairly primitive,
> are there features I just can't get without a framework? If so why is this?
> Is a framework not just a collection of off the shelf technologies bundled
> into a slick package? Can I not access the same features without a
> framework?

Python is a general-purpose language, it is not specific to web
programming. It has basic facilities built in for, for example, socket
communication, sending email, http requests, etc. There are many
features you will want in a web app that have to be built on top of
the basic capabilities of the language and standard libs. For example,
- request parsing
- request dispatching
- authentication and authorization
- session management
- object-relational mapping
- etc, etc., just look at the feature lists of any of the existing frameworks.

I don't think you understand how little you get with plain Python. I'm
not dissing Python, but again, it is a general purpose language, it
doesn't provide the same facilities as a single-purpose language like
php. Maybe you should try writing a CGI to see what is available.

TurboGears and Pylons do use off-the-shelf technologies, though they
are still third-party technology. Certainly you can use SQLAlchemy,
Genshi, Routes, etc without TurboGears, or you can write equivalent
features yourself, or you can let someone else help with picking
components and gluing them together.

Not every framework repackages other off-the-shelf components. Django
is just Django, AFAIK so is web.py.

Anyway, it really is your choice. If your needs are simple, or you
want to learn how stuff works, you can use plain CGI or mod_python. If
you will need the features of a framework, you might be better off
starting with a framework.

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


Re: [Tutor] python web documentation ( without frameworks?)

2008-06-25 Thread Alan Gauld


"Kent Johnson" <[EMAIL PROTECTED]> wrote


Anyway, it really is your choice. If your needs are simple, or you
want to learn how stuff works, you can use plain CGI or mod_python. 
If

you will need the features of a framework, you might be better off
starting with a framework.


I'd go so far as to say that its a good idea to write ONE web app
using CGI just to get a feel for it and to understand howmuch (or 
little)

a framework gives you. But to use CGI as your normal web tool would
be a bit like using assembler when you could use C or using C
when you could use python... Its possible but just a lot more work.

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



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


Re: [Tutor] Removing files based upon time stamps

2008-06-25 Thread Alan Gauld


"Lie Ryan" <[EMAIL PROTECTED]> wrote


You should do this instead:
r'C:\nice\try'
OR
'C:\\nice\\try'

the first way is called raw string, the backslash lose its meaning
the second way is by escaping the backslash.


Or just use forward slashes which work on *nix or windows...

'C:/nice/try'

HTH,

Alan G. 



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


Re: [Tutor] Removing files based upon time stamps

2008-06-25 Thread Marc Tompkins
On Wed, Jun 25, 2008 at 2:21 PM, chase pettet <[EMAIL PROTECTED]> wrote:


> import os, time, sys
> current = time.time()
> os.chdir("c:\BACKUPS\DEV1")
>
> for f in os.listdir('.'):
>   modtime = os.path.getmtime('.')
>   if modtime < current - 30 * 86400:
> os.remove(f)
>

I'm not in a place where I can test anything at the moment, but the first
thing I always do in situations like this is to throw print/logging
statements all over the place so I can see what's going on.  (Slows it down
terribly, but it's temporary, right?)

I would do something like this:

for f in os.listdir('.'):
  modtime = os.path.getmtime('.')
  print f, modtime
  if modtime < current - 30 * 86400:
print f, "  should be removed... is it?"
os.remove(f)

At least it'll give you some idea of where things are going wrong.  As I
say, it's always the first thing I try.  It's rarely the last.

> This is my first list post.  Thanks for any help!
>

Welcome to the list!  Pull up a chair...

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


Re: [Tutor] Astonishing timing result

2008-06-25 Thread Marilyn Davis
On Tue, June 24, 2008 10:16 pm, Dick Moores wrote:

> At 07:00 PM 6/24/2008, Marilyn Davis wrote:
>
>
>> Has anyone ever timed the difference between using a function that was
>> imported with:
>>
>> from my_module import MyFunction
>>
>> and:
>>
>>
>> import my_module
>
> Here are 2 comparisons: ,
> and  
>
> I don't see a significant difference.

Good.  Thank you.

I'm attaching another astonishing timing result, also wrong.

It's probably always true that if a timing result is astonishing, there's
a mistake somewhere, maybe in your thinking.

This one compares using os.popen, os.listdir, and subprocess.Popen.

Marilyn Davis


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


#!/usr/bin/env python
"""lab13_1.py -- Adding up the file sizes in the current directory,
three ways, and comparing them."""
import os
import subprocess
__pychecker__ = 'no-local'

def AccuracyTest():
print "os.listdir:", AddFilesOsListdir()
print "os.popen:  ", AddFilesOsPopen()
print "subprocess:", AddFilesSubprocess()

def AddFilesOsListdir():
total = 0
files = os.listdir('.')
for f in files:
if os.path.isdir('./' + f):
continue
total += os.path.getsize('./' + f)
return total

def AddFilesOsPopen():
return TotalLsSize(os.popen("ls -al"))

def AddFilesSubprocess():
return TotalLsSize(subprocess.Popen(["ls", "-al"], 
   stdout=subprocess.PIPE).stdout)
def ProfileTest():
for i in range(100):
AddFilesOsListdir()
AddFilesOsPopen()
AddFilesSubprocess()

def TotalLsSize(file_obj):
total = 0
for line in file_obj:
if line[0] == 'd':
continue
parts = line.split()
if len(parts) != 9:
continue
total += int(parts[4])
return total

def main():
AccuracyTest()
import profile
profile.run('ProfileTest()')

if __name__ == '__main__':
main()
"""
$ lab13_1.py
os.listdir: 26298
os.popen:   26298
subprocess: 26298
 30376 function calls in 1.872 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1010.0040.0000.0040.000 :0(WEXITSTATUS)
  1010.0120.0000.0120.000 :0(WIFEXITED)
  1010.0000.0000.0000.000 :0(WIFSIGNALED)
   770.0040.0000.0040.000 :0(append)
  3000.0160.0000.0160.000 :0(close)
  2000.0120.0000.0120.000 :0(fcntl)
  1000.0040.0000.0040.000 :0(fdopen)
  1000.0680.0010.0680.001 :0(fork)
  2000.0120.0000.0120.000 :0(isinstance)
 54000.1000.0000.1000.000 :0(len)
  1000.0320.0000.0320.000 :0(listdir)
  2000.0000.0000.0000.000 :0(pipe)
  1000.1080.0010.1080.001 :0(popen)
10.0000.0000.0000.000 :0(range)
  1000.0160.0000.0160.000 :0(read)
   780.0040.0000.0040.000 :0(remove)
10.0040.0040.0040.004 :0(setprofile)
 54000.1040.0000.1040.000 :0(split)
 53000.2360.0000.2360.000 :0(stat)
  1780.0040.0000.0040.000 :0(waitpid)
10.0000.0001.8681.868 :1()
  1000.1560.0020.8720.009 lab13_1.py:12(AddFilesOsListdir)
  1000.0240.0000.4400.004 lab13_1.py:21(AddFilesOsPopen)
  1000.0360.0000.5400.005 lab13_1.py:24(AddFilesSubprocess)
... The rest of the output is irrelevant.
It seems fishy that os.listdir() takes longer than both subprocess.Popen()
and os.popen().  Maybe somehow we are comparing apples and oranges?
$ """___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Invoking Python

2008-06-25 Thread kinuthiA muchanE

On Tue, 2008-06-24 at 11:11 -0700, Danny Laya wrote:
> ... or you could start you fire up a text editor (something like
>  Notepad
> in Windows, or nano in Linux and type "3+4"(without the quotes!),
> hmmm..., and save the file as anything you want, lets say for  now you
> save the file as "threePlusFour". Every time you invoke the python
> interpreter (do you know how to do that?) with "threePlusFour", you
>  will
> get the value seven! 
> 
> Well HE..HE i don't know. Let say I write the "threePlusFour" file in
> /home/danny/threePlusFour.py
> How I can invoke that file
>  ???
>From the forward slashes in the file path I assume you are using a Linux based 
>OS, Ubuntu perhaps? Well, to use python 
you need to to start the terminal or the shell. In Ubuntu, go to Main
Menu ==> Accessories and click on Terminal, you will now have a new
window open with something like this --- [EMAIL PROTECTED]:~$ . 

Enter the name "python" followed by the name of your file. In this case
you should enter "python /home/danny/threePlusFour.py"(without the
quotes!). If you want to enter into the Python interactive prompt,
simply type python and you should be rewarded with something like: 


Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

The ">>>" there means python is waiting for you to enter commands.
Try 3+4, or 4/3

Does this  help?
Kinuthia...


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