Re: [Tutor] new user question about while loops

2005-10-26 Thread Norman Silverstone


> I understand the format of while loops, but is it possible to use the
> random.randrange function in them?
>  
> My goal, create a program that flips a coin 100 times, at the end it
> says the number of times it flipped heads and flipped tails.

I am also trying to learn python and came across this very exercise. The
answer to your question is yes and, if you like I will post my attempt
at the code. Just for fun, I also got the process to repeat itself 10
times and report the results. It was fun doing it and very encouraging
when it worked.

Norman


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


Re: [Tutor] new user question about while loops

2005-10-26 Thread Johan Geldenhuys




I am confused. It looks to me as if the while loop will never work,
because it stays inside while <100 and further down in the loop, if
it is < 100, it should go out of the loop. How can it stay running
while <100 and yet go out if  < 100?

Johan
 

Nick Eberle wrote:

  
  
  print
"This is a coin flip game"
   
  print
"\n100 flips will be made and it will show the amount of times heads or
tails came up"
   
  
  import
random
  
#assigning variables to track the amount of times heads or tails comes
up
  heads=0
tails=1
   
  flip=100
while flip < 100:
    flip -= 1
    random.randrange(2)
    if flip < 100:
    break
   
  print
"\nThe amount of times tails came up was" , tails , "The amount of
times heads came up was" , heads
   
  raw_input()
  
  
  
  
  From: bob
[mailto:[EMAIL PROTECTED]]
  Sent: Tue 10/25/2005 10:58 PM
  To: Nick Eberle; tutor@python.org
  Subject: Re: [Tutor] new user question about while loops
  
  
  At 10:53 PM 10/25/2005, Nick Eberle wrote:
  Content-class:
urn:content-classes:message
Content-Type: multipart/alternative;
boundary="_=_NextPart_001_01C5D9F1.A836CF4F"

Sorry for potential double post, error with first
send
--
Hello all,
 
I had a new question about python. I am
pretty much in tutorial learning stages, but attempting to create
sample programs not in my book to learn how to construct scripts.
 
I understand the format of while loops,
but is it possible to use the random.randrange function in them?
 
My goal, create a program that flips a
coin 100 times, at the end it says the number of times it flipped heads
and flipped tails.
 
My dilemia, how do I get this to work
with a while loop? I tried intially assigning
 
heads=0
tails=1
 
then I figured I could just do a while
loop and then use the random function each time. At the end it could
count the number of times the random generated a 0 or a 1.
 
However I can't seem to construct it in
a way that makes or works. 
  
Show us your code, as flawed as it might be. Then we can advise you.
  

___
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] new user question about while loops

2005-10-26 Thread Danny Yoo


On Tue, 25 Oct 2005, Nick Eberle wrote:

>  My goal, create a program that flips a coin 100 times, at the end it
> says the number of times it flipped heads and flipped tails.

Hi Nick,

Do you might if we simplify the problem slightly?  Say that you're only
flipping the coin two times.  Can you write code to say how many times it
flips heads and tails?  Once you get that working, then modify that
program to do it for three coins, then four.

The idea is to try really small cases first, just so you get a better
sense of the problem.  From your initial code, it looks like you might be
getting stuck on another concept besides loops, so let's see if we can get
that cleared up first.

Please feel free to ask questions.  Good luck!

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


Re: [Tutor] new user question about while loops

2005-10-26 Thread Danny Yoo


> >  My goal, create a program that flips a coin 100 times, at the end it
> > says the number of times it flipped heads and flipped tails.
>
> Do you might if we simplify the problem slightly?  Say that you're only
> flipping the coin two times.  Can you write code to say how many times
> it flips heads and tails?  Once you get that working, then modify that
> program to do it for three coins, then four.

Duh: I forgot to add: can you try to do the above without loops?  Since
there's so little coin flipping going on, the code to do this shouldn't be
too long to write, even without loops.

(... although it will get longer for each additional coin we flip.  When
we want to scale our solution to more coins, then that's where loops can
come into play.)

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


Re: [Tutor] new user question about while loops

2005-10-26 Thread Pujo Aji
Hello,
 
I'm not so sure about your problem, but 
probably this code can help
 
    sumHead, sumTail = 0,0
    listHeadTime = []    listTailTime = []        for i in range(100):    time_start = time.clock()    coin = random.randint(0,1) # 0 head, 1 tail    time_stop = time.clock()    time_duration = time_stop - time_start
        if coin == 0:    sumHead += 1    listHeadTime.append(time_duration)    else:    sumTail += 1    listTailTime.append(time_duration)
    print sumHead, sumTail    print listHeadTime    print listTailTime
 
Cheers,
pujo 
On 10/26/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
> >  My goal, create a program that flips a coin 100 times, at the end it> > says the number of times it flipped heads and flipped tails.
>> Do you might if we simplify the problem slightly?  Say that you're only> flipping the coin two times.  Can you write code to say how many times> it flips heads and tails?  Once you get that working, then modify that
> program to do it for three coins, then four.Duh: I forgot to add: can you try to do the above without loops?  Sincethere's so little coin flipping going on, the code to do this shouldn't betoo long to write, even without loops.
(... although it will get longer for each additional coin we flip.  Whenwe want to scale our solution to more coins, then that's where loops cancome into play.)___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] new user question about while loops

2005-10-26 Thread Alan Gauld
As Danny says, try breaking the problem into chunks and solving
each bit separately. I'll provide a few comments on your code in
the meantime but try the "evolving soluition" approach too.

#assigning variables to track the amount of times heads or tails comes up
heads=0
tails=1

AG> Why not make both zero, after all there have been no flips so far!

flip=100
while flip < 100:

AG> flip is never less than 100 because you set it to 100!
AG> Thus you never enter the loop...

flip -= 1
random.randrange(2)
if flip < 100:
break

AG> And if you did after the first time through you make flip equal 99
AG> so that it will always exit the loop(break) here so it would only run 
once!

AG> Try getting a while loop to run 100 times printing out the loop test 
value.
AG> Or better stuill, since you know how many times you want the lopp to
AG> run use a for loop instead:

AG> for loop in range(100):
AG> # loop code here

print "\nThe amount of times tails came up was" , tails , "The amount of 
times heads came up was" , heads

AG> But the only values you assign to head/tails are the initial 1 and 0.
AG> Try Danny;'s suggestion of flipping the coin twice...

 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] threading issues

2005-10-26 Thread Kent Johnson
Chris Hallman wrote:

> I was finally able to get my script to not show duplicate PINGs. I also 
> realized that my script was not PINGing all the hosts in the input file. 

Congratulations on getting it to work! See below for a few notes.

> Here is my latest version:
> 
> 
> import os, re, string, sys, threading, time
> from threading import Thread
> from time import strftime
> 
> ms = re.compile("Reply")

You don't need a regular expression for this, you could use the simpler
  if "Reply" in pingas

> rpath = (r"c:\utils\network_ping_devices.txt")
> 
> if os.path.exists(r"c:\utils\network_ping_again.txt"):
> rpath = (r"c:\utils\network_ping_again.txt")
> wpath = (r"c:\logs\network_ping.out")
> tpath =  (r"c:\temp\ping.txt")
> if os.path.exists(tpath):
> os.remove(tpath)
> temp = open(tpath, "w")
> output = open(wpath, "a")
> output.write("\n" + "Network PING test started -" + strftime(" %H:%M:%S 
> %x") + "\n")
> output.flush()
> 
> class PingIT(threading.Thread):
> def __init__(self,rtr):
> Thread.__init__(self)
> self.rtr = rtr
> 
> def run(self):
> pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr)
> pingas = string.join(pingaf.readlines())
> if ms.search(pingas):
> #print (re.sub('\n','',self.rtr)) + " responded."#for 
> debugging

> return
> else:
> pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr)
> pingas = string.join(pingaf.readlines())
> if ms.search(pingas):
> #print (re.sub('\n','',self.rtr)) + " responded."# 
> for debugging

You don't need a regex for simple string replacements, either - you can use
  self.rtr.replace('\n', '')

In this case the \n is at the end of the string - it is included in the lines 
you read from the file - so you could also use self.rtr.strip().

But even better would be to strip the '\n' from rtr when you read it from the 
file below, then you wouldn't have to deal with it everywhere else.

> return
> else:
> temp.write(re.sub('\n','',self.rtr) + " did not respond.\n")

Instead of writing the results to a file you could accumulate them in a list 
and sort the list. Make a global
  failed = []
before you start any threads, then use
  failed.append(re.sub('\n','',self.rtr) + " did not respond.")

> 
> pinglist = []
> for rtr in file(rpath):

Here you should say
  rtr = rtr.strip()
to get rid of that annoying trailing newline

> current = PingIT(rtr)

Yes, that's exactly right - you pass the value of rtr as a parameter to the 
thread so it doesn't matter that the global value changes.

> pinglist.append(current)
> current.start()
> 
> for pingle in pinglist:
> pingle.join()
> 
> temp.close()
> temp = open(tpath, "r")
> lines = []
> for line in temp:
> lines.append(line.rstrip())
> lines.sort()

The sort should be outside the loop, you only have to sort once. If you use the 
failed list as I suggest above, here you just need
  failed.sort()
then
  for line in failed:

> for line in lines:
> print >>output, line
> 
> output.write("Network PING test completed -" + strftime(" %H:%M:%S %x") 
> + "\n")
> output.flush()
> output.close()
> 
> 
> All the hosts in the input file are sorted alphabetically but my results 
> were output out of order?! (possibly due to latency in PING responses or 
> some latency in the thread joining; not sure of either). I had to do the 
> crude temp output file so that I could sort the results, but it works!! 

Using threads introduces some indeterminance into the program. You can't be 
sure that the threads will run in the order that you start them, or that they 
will run to completion without interruption. And since the ping itself can take 
different amounts of time that affects the order in which they complete also.

Kent
-- 
http://www.kentsjohnson.com

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


Re: [Tutor] new user question about while loops

2005-10-26 Thread Norman Silverstone
This may not be up to the standard of the more experienced programmer
but here is my effort. An added bit is the ability to go on using the
code until you are fed up.

#To check the computers odds and evens
import random
anothergo = "y"
while(anothergo != "n"):
  

   oddsevens = random.randrange(2)
   odd = 0
   even = 0
   tries = 0
   
   while(tries != 100):
  oddevens = random.randrange(2)
  if (oddevens == 0):
 even += 1
  else:
 odd += 1
  tries += 1  
   print "In %d tries there were %d odds and %d evens" % (tries, odd,
even)
   
   anothergo = raw_input("Have another go y/n - ")  


Hope you like it.

Norman 


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


[Tutor] os command

2005-10-26 Thread Johan Geldenhuys
I have script that calls a system command that I want to run for 5 minutes.
"""
import os
cmd = 'tcpdump -n -i eth0'
os.system(cmd)
"""

I can start a timer after the cmd is issued, but I don't know how to 
send a control signal to stop the command after I issued it. This is 
normally from the shell  ^c.

This cmd my run in more than one thread on different interfaces and I 
don't whant all of then stopped at once. I think the best way is to make 
a thread for each interface where the cmd can be issued and stopped 
without the danger of stopping he wrong thread.

Can anybody help?

Thanks

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


Re: [Tutor] os command

2005-10-26 Thread Kent Johnson
Johan Geldenhuys wrote:
> I have script that calls a system command that I want to run for 5 minutes.
> """
> import os
> cmd = 'tcpdump -n -i eth0'
> os.system(cmd)
> """
> 
> I can start a timer after the cmd is issued, but I don't know how to 
> send a control signal to stop the command after I issued it. This is 
> normally from the shell  ^c.

This is problematic. In general there is no clean way to kill a thread in 
Python. The usual approach is to set a flag which the thread checks but this 
won't work for you.

A recent thread in comp.lang.python has some discussion and suggestions but it 
is inconclusive:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/94281f5a797489b1/ebca44930a016f74?q=os.system+thread&rnum=5&hl=en#ebca44930a016f74

Kent
-- 
http://www.kentsjohnson.com

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


Re: [Tutor] os command

2005-10-26 Thread Johan Geldenhuys




So, for a newbie like me I might struggle with this one  :-( 

I saw that the thread in comp.lang.python talks about a deamon flag for
a thread. This sounds like a idea that could work. I don't know how to
use that, but will use the example given there.

Thanks.

Kent Johnson wrote:

  Johan Geldenhuys wrote:
  
  
I have script that calls a system command that I want to run for 5 minutes.
"""
import os
cmd = 'tcpdump -n -i eth0'
os.system(cmd)
"""

I can start a timer after the cmd is issued, but I don't know how to 
send a control signal to stop the command after I issued it. This is 
normally from the shell  ^c.

  
  
This is problematic. In general there is no clean way to kill a thread in Python. The usual approach is to set a flag which the thread checks but this won't work for you.

A recent thread in comp.lang.python has some discussion and suggestions but it is inconclusive:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/94281f5a797489b1/ebca44930a016f74?q=os.system+thread&rnum=5&hl=en#ebca44930a016f74

Kent
  



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


[Tutor] packages,modules, and module attributes

2005-10-26 Thread Joris van Zwieten
Hi all,

I've a question, essentially about the import statement. Suppose I have
two python files, a.py and b.py:

a.py

flag = True

def getFlag():
return flag

b.py

from a import *

now, in the interpreter:

>>> import b
>>> b.flag
True
>>> b.flag=False
>>> b.flag
False
>>> b.getFlag()
True

this is probably related to namespaces? I find it very confusing, because
after the import, b _does_ have an attribute called 'flag' (try dir(b)),
which has the value that was assigned to it in a.py. (i.e. the second
statement in the interpreter does not inject a new variable 'flag' into
b.) however, modifications to 'flag' are not 'seen' by functions defined
in a.py, called from b (i.e. b.getFlag()).
could someone explain what is happening here?
thanks,


Joris van Zwieten

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


[Tutor] Glossory of terms in Python

2005-10-26 Thread Srinivas Iyyer
Dear python experts, 

  I am a novice python learner and aspiring to become
decent python programmer. I am reading 'Learning
Python' by Mark Lutz et al.  and it is one of the good
books that I find in addition to Alan Gauld's book
'Learn to Program Using Python'.

While reading these books step-by-step and progressing
ahead, I feel that some of the terms are highly
volatile.  In simple terms, while reading about lambda
functions after reading a lot of stuff before, I am
unable to clearly define what is an expression and
what is a statement.  

Although, I know the difference and what exactly they
mean inherently in my mind, I am unable to comprehend
and move ahead. This reamins a stumblick block.  

What I feel is that to overcome this stumbling block,
I need a glossory of terms at the end of the book that
defines the critical terms that are very easy to
programmer paralance such as :
a. Statement - A statement is .. . For eg.
xx is called a statment
b. Expression - An expression is something  .
For example, def f(x): xxx  return y is an expression.

c. Jump table: A jump table is a table where ..

d. Attribute : An attribute is a variable that is used
as an input to a function. For eg. def Xabl(a): here a
is an attribute. 


Such a glossory of terms would be a great gift from
python experts. This would help novice and learning
programmers who never talked the terms of computing
language in daily english. Whenever we come across
these terms I would refer to this glossory and refresh
my brain time to time.  I would love to paste this
glossory on my wall and gawk at them daily.  


What is your opinion ?

Thanks
Srini

--- Joris van Zwieten
<[EMAIL PROTECTED]> wrote:

> Hi all,
> 
> I've a question, essentially about the import
> statement. Suppose I have
> two python files, a.py and b.py:
> 
> a.py
> 
> flag = True
> 
> def getFlag():
> return flag
> 
> b.py
> 
> from a import *
> 
> now, in the interpreter:
> 
> >>> import b
> >>> b.flag
> True
> >>> b.flag=False
> >>> b.flag
> False
> >>> b.getFlag()
> True
> 
> this is probably related to namespaces? I find it
> very confusing, because
> after the import, b _does_ have an attribute called
> 'flag' (try dir(b)),
> which has the value that was assigned to it in a.py.
> (i.e. the second
> statement in the interpreter does not inject a new
> variable 'flag' into
> b.) however, modifications to 'flag' are not 'seen'
> by functions defined
> in a.py, called from b (i.e. b.getFlag()).
> could someone explain what is happening here?
> thanks,
> 
> 
> Joris van Zwieten
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




__ 
Yahoo! FareChase: Search multiple travel sites in one click.
http://farechase.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] new user question about while loops

2005-10-26 Thread bob


Thank you for posting your code. That really helps us see where you are
and therefore how to help.
I encourage you to "desk check" your code: pretend you are the
computer: write down the values of variables and expressions as things
change. Evaluate each statement to see what it does.
Example:
heads    tails    flip   
flip < 100 while flip < 100:
0   
1   100   
False loop not
entered
program ends.
I hope you understand why the loop is not entered. If not please (re)read
an explanation of while.
Noticing that you would alter the loop condition. To do that you need to
ask "When do I want the loop to end?"
Let's say you changed it to: while flip <= 100. Now your "desk
check" would look like:
heads    tails    flip   
flip <= 100 while flip <= 100:
0   
1   100   
True
loop entered
   
99 
random.randrange(2)
has no effect since nothing is done with the value returned 
flip < 100  
break
True leaves the
loop
print "\nThe amount of times tails came up
was" , tails , "The amount of times heads came up was" ,
heads
results in: The amount of times tails came up was 1 The amount of times
heads came up was 0
I hope this helps. 


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


Re: [Tutor] new user question about while loops

2005-10-26 Thread Nick Eberle
Ahh makes much more sense, thanks for all the help! 

I'll go back and rework it, keeping in mind trying to solve each piece 
separately.

Thanks again all.

-Original Message-
From: Alan Gauld [mailto:[EMAIL PROTECTED]
Sent: Wednesday, October 26, 2005 1:53 AM
To: Nick Eberle; bob; tutor@python.org
Subject: Re: [Tutor] new user question about while loops


As Danny says, try breaking the problem into chunks and solving
each bit separately. I'll provide a few comments on your code in
the meantime but try the "evolving soluition" approach too.

#assigning variables to track the amount of times heads or tails comes up
heads=0
tails=1

AG> Why not make both zero, after all there have been no flips so far!

flip=100
while flip < 100:

AG> flip is never less than 100 because you set it to 100!
AG> Thus you never enter the loop...

flip -= 1
random.randrange(2)
if flip < 100:
break

AG> And if you did after the first time through you make flip equal 99
AG> so that it will always exit the loop(break) here so it would only run 
once!

AG> Try getting a while loop to run 100 times printing out the loop test 
value.
AG> Or better stuill, since you know how many times you want the lopp to
AG> run use a for loop instead:

AG> for loop in range(100):
AG> # loop code here

print "\nThe amount of times tails came up was" , tails , "The amount of 
times heads came up was" , heads

AG> But the only values you assign to head/tails are the initial 1 and 0.
AG> Try Danny;'s suggestion of flipping the coin twice...

 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] new user question about while loops

2005-10-26 Thread Norman Silverstone
Yes I am going through the Michael Dawson book. Also, I am working from
the Alan Gauld book to reinforce my attempts at learning python.

Norman

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


Re: [Tutor] packages,modules, and module attributes

2005-10-26 Thread Alan Gauld
> I've a question, essentially about the import statement. Suppose I have
> two python files, a.py and b.py:

OK, I'll have a go although I'm only 90% sure I've got it right...

> a.py
> 
> flag = True
> 
> def getFlag():
>return flag
> 
> b.py
> 
> from a import *

This imports the names from a.
Thus b now has a name flag that points to TRue and a name 
getFlag that points to the function in a.

> now, in the interpreter:
> 
 import b
 b.flag
> True
 b.flag=False
 b.flag
> False

This first reads the value imported from a then creates a new name 
in b that overwrites the imported value and sets it to False.


 b.getFlag()
> True

This calls the function in a which returns the value from a which is 
still set to True.

> this is probably related to namespaces? I find it very confusing, 

It is to do with namespaces and shows why two bad practices you have 
used are indeed bad practices! :-)

First if you had used 

import a 

in b instead of 

from a import *

All would have worked as you expected because you would have 
been forced to specify 

b.a.flag 

etc.

Secondly relying on a global variable in the function getFlag meant that 
when you imported getFLag the function object remained in a and 
accessed the variable flag in a. If you had passed the name of the flag 
to getFlag as a parameter then it would have worked as expected 
- although only returning the value you already had! (But if Flag were 
a more complex object it would then make sense!)

So as usual the advice "do not use from X import *" holds.

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


[Tutor] urllib2 & form submit

2005-10-26 Thread Ed Hotchkiss
i am trying to write a class to log into myspace. either i am doing something wrong, or... myspace is requiring that i accept a cookie, or create a session? however i am new to urllib and urllib2. 
 
heres my code:
correctly formatted code is at: http://www.jeah.net/~marla/myspace.py
 
#!/bin/env python# ---import sgmllibimport urllibimport urllib2import urlparse# ---class myspace:# login to one myspace accountdef login(self, user, password):
the_url = "http://viewmorepics.myspace.com/index.cfm?fuseaction=login.process"user_agent = 'Mozilla/4.0 (compatible; MSIE 
5.5; Windows NT)'headers = { 'User-Agent' : user_agent }values = { 'email' : user, 'password' : password }data = "">req = urllib2.Request(the_url, data)try:handle = urllib2.urlopen
(req)except IOError:print 'Something went wrong'else:x = handle.read()temp = open("edspage.html", "w")temp.write(x)temp.close()# add friend based on users URLdef addFriend(self, friendURL):
return 1# delete friend based on users URLdef deleteFriend(self, friendURL):return 1# post a friends bulletindef postBulletin(self, bulletin):return 1# read all bulletins into a tuple named 'bulletins'
def readBulletins(self):bulletins = {}# a photo to your profiledef addPhoto(self, photoLocation):return 1# delete a photo from your profiledef deletePhoto(self, photoID):return 1
# return a tuple of people that match your browsing criteriadef browse(self, sex, ageBegin, ageEnd, gayBiStraight, zipCode, zipRange):    return 1# stick someones myspace page into an html file
def grabUserPageHTML(self, xURL, outputFile):req = urllib2.Request(xURL)handle = urllib2.urlopen(req)thepage = handle.read()    temp = open(outputFile, "w")    temp.write
(thepage)    temp.close()def logout(self):return 1# ---# example of class usageme = myspace()me.login("[EMAIL PROTECTED]", "password here")
#me.grabUserPageHTML("http://www.myspace.com/blahuser/","blah.html")#me.logout()# ---EOF
 
 
the form uses POST method. the action for the form is the_url. what am i doing wrong? all that the script does, is to refer me to another login page. is it detecting somehow that i am a script and not a users browser? any help would be appreciate, lost in the water here.
-- edward hotchkiss 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Glossory of terms in Python

2005-10-26 Thread Alan Gauld
> While reading these books step-by-step and progressing
> ahead, I feel that some of the terms are highly
> volatile.  In simple terms, while reading about lambda
> functions after reading a lot of stuff before, I am
> unable to clearly define what is an expression and
> what is a statement.  

Good catch. One of the things I tried very hard to do was 
define all these computer terms as I used them. 
But obviously I missed a few!

An expression is anything that can go on the right hand side 
of an assignment. ie it can be evaluated.

A statement is a little more tricky since it varies slightly from 
language to language. Basically its any single line that can be 
typed into the Python >>> prompt without raising an error
(including multiple lines where the \ character or unmatched 
brackets are used!) Statements may be expressions or include 
expressions. Thus

var = E

is a statement containing the expression E

someFunction()

is both a statement and an expression!

if E1 >- E2: print 42

is a statement that utilised two expressions E1 and E2 to form a third 
expression (E1 >=E2) the result of which determines the outcome of 
the statement.

Thats not a rigorous definition, for that you should read the language 
reference in the documentation. But hoppefully goves a flavour of 
the meanings.

> Although, I know the difference and what exactly they
> mean inherently in my mind, I am unable to comprehend
> and move ahead. This reamins a stumblick block.  

> a. Statement - A statement is .. . For eg.
> xx is called a statment
> b. Expression - An expression is something  .
> For example, def f(x): xxx  return y is an expression.

actually in that example only y is an expression, the rest are statements!

> c. Jump table: A jump table is a table where ..

I don't cover jump tables in my tutor but if I did I'd certainly 
define it :-)

> d. Attribute : An attribute is a variable that is used
> as an input to a function. For eg. def Xabl(a): here a
> is an attribute. 

Nope a is a parameter. The value passed in when you 
call XAbl() is an argument.

An attribute is an internal field of an object, usially a data field 
but sometimes methods are called attributes too.

> Such a glossory of terms would be a great gift from
> python experts. 

Actually it would be good for programmers in geneal.
The best I can think of is the Wikipedia. For example 
on the difference between statements and expressions see:

http://en.wikipedia.org/wiki/Statement_%28programming%29

It certainly dscribes all the terms you have listed so far...

> This would help novice and learning and programmers 
> who never talked the terms of computing language in 
> daily english. 

It sounds like a great idea and would encourage you to start
one straight way. Tell the usenet community and you will 
instantly receive lots of 'feedback'. Don't take any of it 
personally but use it to improve your site. You should fairly 
quickly become the owner of a frequently visited and useful 
internet resource.

I mean it, just do it and you will have contributed. You might 
even become an "internet hero" :-)

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] os command

2005-10-26 Thread Hugo González Monteverde
Hi,

os.system will return the errorval of the application. You need to

1) get the pid of the child process
2) kill it using os.kill(os.SIGTERM)
3) reap the killed process

This is all in unix/linux, of course.

what I do (untested, please check order of args and correct usage of exec):

pid = os.fork()

if pid == 0: #child process
 os.execvp("tcpdump", "tcpdump", "-n",  "-i",  "eth0")

else:   #parent
 time.sleep(5)
 os.kill(pid, os.SIGTERM)
 os.waitpid(pid, 0)   #wait for process to end



Johan Geldenhuys wrote:
> I have script that calls a system command that I want to run for 5 minutes.
> """
> import os
> cmd = 'tcpdump -n -i eth0'
> os.system(cmd)
> """
> 
> I can start a timer after the cmd is issued, but I don't know how to 
> send a control signal to stop the command after I issued it. This is 
> normally from the shell  ^c.
> 
> This cmd my run in more than one thread on different interfaces and I 
> don't whant all of then stopped at once. I think the best way is to make 
> a thread for each interface where the cmd can be issued and stopped 
> without the danger of stopping he wrong thread.
> 
> Can anybody help?
> 
> Thanks
> 
> Johan
> ___
> 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] urllib2 & form submit

2005-10-26 Thread Kent Johnson
Ed Hotchkiss wrote:
> i am trying to write a class to log into myspace. either i am doing 
> something wrong, or... myspace is requiring that i accept a cookie, or 
> create a session? however i am new to urllib and urllib2.

It's very likely that myspace is returning a cookie from the login, this is a 
common way to handle login sessions. You have to install an HTTPCookieProcessor 
into urllib2. In your setup code before you call urllib2.urlopen(), put these 
two lines:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) 
urllib2.install_opener(opener)

Now when you use urllib2.urlopen() it will save any cookies returned by the 
server, and send them in future requests.

There is an article on cookies at www.voidspace.org.uk. The site seems to be 
down now but the Google cache version is here:
http://64.233.161.104/search?q=cache:24L65pecYJ0J:www.voidspace.org.uk/python/articles/cookielib.shtml+httpcookieprocessor&hl=en&client=firefox-a

The article is overly complicated because it shows how to use an older cookie 
library as well as urllib2. You can just focus on the urllib2 part.

Kent

>  
> heres my code:
> correctly formatted code is at: http://www.jeah.net/~marla/myspace.py
>  
> #!/bin/env python
> 
> # ---
> 
> import sgmllib
> import urllib
> import urllib2
> import urlparse
> 
> # ---
> 
> class myspace:
> 
> # login to one myspace account
> def login(self, user, password):
> the_url = 
> "http://viewmorepics.myspace.com/index.cfm?fuseaction=login.process";
> user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
> headers = { 'User-Agent' : user_agent }
> values = { 'email' : user,
>  'password' : password }
> data = urllib.urlencode(values)
> req = urllib2.Request(the_url, data)
> try:
> handle = urllib2.urlopen (req)
> except IOError:
> print 'Something went wrong'
> else:
> x = handle.read()
> temp = open("edspage.html", "w")
> temp.write(x)
> temp.close()
> 
> # add friend based on users URL
> def addFriend(self, friendURL):
> return 1
> 
> # delete friend based on users URL
> def deleteFriend(self, friendURL):
> return 1
> 
> # post a friends bulletin
> def postBulletin(self, bulletin):
> return 1
> 
> # read all bulletins into a tuple named 'bulletins'
> def readBulletins(self):
> bulletins = {}
> 
> # a photo to your profile
> def addPhoto(self, photoLocation):
> return 1
> 
> # delete a photo from your profile
> def deletePhoto(self, photoID):
> return 1
> 
> # return a tuple of people that match your browsing criteria
> def browse(self, sex, ageBegin, ageEnd, gayBiStraight, zipCode, zipRange):
> return 1
> 
> # stick someones myspace page into an html file
> def grabUserPageHTML(self, xURL, outputFile):
> req = urllib2.Request(xURL)
> handle = urllib2.urlopen(req)
> thepage = handle.read()
> temp = open(outputFile, "w")
> temp.write (thepage)
> temp.close()
> 
> def logout(self):
> return 1
> 
> # ---
> 
> # example of class usage
> 
> me = myspace()
> me.login("[EMAIL PROTECTED] ", "password here")
> #me.grabUserPageHTML("http://www.myspace.com/blahuser/","blah.html 
> ")
> #me.logout()
> 
> # ---
> EOF
>  
>  
> the form uses POST method. the action for the form is the_url. what am i 
> doing wrong? all that the script does, is to refer me to another login 
> page. is it detecting somehow that i am a script and not a users 
> browser? any help would be appreciate, lost in the water here.
> 
> -- 
> edward hotchkiss
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] Matrix

2005-10-26 Thread Alan Gauld
This doesn't seem to have been answered...

"Shi Mu" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I can not understand the use of "cell in row" for two times in the code:
>
> # convert the matrix to a 1D list
> matrix = [[13,2,3,4,5],[0,10,6,0,0],[7,0,0,0,9]]
> items = [cell for row in matrix for cell in row]
> print items

Lets expand the list comprehension:

matrix = [[13,2,3,4,5],[0,10,6,0,0],[7,0,0,0,9]]
items = []
for row in matrix:
 for cell in row:
  items.append(cell)
print items

Does that explain whats going on? Its just nesting another for loop.

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] Python as Application

2005-10-26 Thread Lee Harr
>My son is learning something about using a spreadsheet  - extremely
>useful and I support it 100%.  That he thinks what he is learning is
>Excel is absolutely unforgivable, in terms of my understanding of
>ethical norms that once prevailed in an institute of higher education.
>

I guess it depends on whether that is what he was taught or if he
was ever taught about alternatives.

If this is an advanced class and was billed as "learn all the details
about Excel" that's fine. If this is an introductory course I believe it
should really start off with ... Excel is a spreadsheet. There are many
spreadsheet applications available. All spreadsheets share these
common traits 


>We understand that all the functionality he will ever need from Excel is
>available for free in other spreadsheet software.
>

Probably. Anything beyond the common spreadsheet functions is almost
certainly better done another way.


>Do I care that he is within an institution that has lost its bearings on
>fundamental matters of academic ethics.
>

Of course.

More frightening to me than the ubiquitous use of MS Office is the
omnipresence of windows. Every time a student sits down in front
of KDE in our lab and says "Where is the internet?" I can only cringe.

Microsoft may not own the internet, but that is not what we are
teaching. I seriously get about 10% of users who are unable to
see any other browser as performing the same function as
internet explorer.

If "what is a spreadsheet?" is pretty scary. "What is a browser?" is
downright terrifying.


>Do I care that I am made to feel that this point of view is somehow
>radical on a educational forum that is an offshoot of an open source
>software community.
>

Hmm... more like "preaching to the choir" isn't it?

_
Express yourself instantly with MSN Messenger! Download today it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


[Tutor] Tkinter problem (.create_image)

2005-10-26 Thread Rob Dowell
I am having a problem with Tkinter. The goal is a program that will copy 
images from one folder to another then delete them from the source dir 
after it is verified that they made it to the target dir. I have the 
base functionality figured out (comments on that are welcome of course). 
Now I want to have a gui that shows a small thumbnail of the image as it 
is copied. Right now everything works fine except that the gui only 
shows the last picture that is copied. Here is the code:

from Tkinter import *
import PIL.Image as image
import PIL.ImageTk as imagetk
import ConfigParser
import os
import time
import shutil


   

class MyApp:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent)
self.myContainer1.pack()

self.button1 = Button(self.myContainer1)
self.button1.configure(text="Copy Pics")
self.button1.pack()
self.button1.bind("", self.button1Click)

self.tv1 = StringVar()
self.tv1.set("Ready to copy.")
   
self.label1 = Label(self.myContainer1)
self.label1.configure(textvariable = self.tv1)
self.label1.pack()

self.canvas1 = Canvas(self.myContainer1)
self.canvas1.configure(width=200, height=200, bg='yellow')
self.canvas1.pack()

def button1Click(self, event):
files = {}
print "Here"
#Import config information from the ini file
configfile = "./GetPics.ini"
config = ConfigParser.ConfigParser()
config.read(configfile)
sourcedirloc = config.get("GetPics", "sourcedir")
targetdirloc = config.get("GetPics", "targetdir")
deleteold = config.get("GetPics", "deleteold")
enddict = {'1':'st',
   '2':'nd',
   '3':'rd',
   '4':'th',
   '5':'th',
   '6':'th',
   '7':'th',
   '8':'th',
   '9':'th',
   '0':'th'}
#OPen the source dir and get a list of the files making the new 
name and path as you go
sourcefiles = os.listdir(sourcedirloc)
files = {}
for file in sourcefiles:
filepath = sourcedirloc + "/" + file
if files.has_key(filepath):
#The file is duplicated?
pass
else:
files[filepath] = {}
files[filepath]['originalname'] = file
files[filepath]['modtuple'] = 
time.localtime(os.stat(filepath).st_mtime)
files[filepath]['size'] = os.stat(filepath).st_size
files[filepath]['monthdir'] = targetdirloc + "/" + 
time.strftime('%Y-%m', time.localtime(os.stat(filepath).st_mtime))
files[filepath]['daydir'] = files[filepath]['monthdir'] 
+ "/" + time.strftime('%d', time.localtime(os.stat(filepath).st_mtime)) 
+ enddict[time.strftime('%d', 
time.localtime(os.stat(filepath).st_mtime))[len(time.strftime('%d', 
time.localtime(os.stat(filepath).st_mtime)))-1]]
files[filepath]['newname'] = files[filepath]['daydir'] + 
"/" + time.strftime('%Y-%m-%d-%H-%M-%S', 
time.localtime(os.stat(filepath).st_mtime)) + os.path.splitext(file)[1]
#Now check to see if a file with this name already 
exists and increment the name if it does
n = 1
while os.path.isfile(files[filepath]['newname']):
files[filepath]['newname'] = 
os.path.splitext(files[filepath]['newname'])[0] + "-" + str(n) + 
os.path.splitext(files[filepath]['newname'])[1]
n += 1   
#Copy all of the file to the target dir
for file in files.keys():
#Check for the dir and create it if needed:
if not os.path.isdir(files[file]['monthdir']):
self.tv1.set("Creating (monthdir) " + 
files[file]['monthdir'])
os.mkdir(files[file]['monthdir'])
if not os.path.isdir(files[file]['daydir']):
self.tv1.set("Creating (daydir) " + files[file]['daydir'])
os.mkdir(files[file]['daydir'])
#copy the file
self.tv1.set("Copying " + file + " to " + 
files[file]['newname'])

#  DISPLAY THE THUMBNAIL
self.DisplayImage(file)

shutil.copy2(file, files[file]['newname'])

#Go back and remove the sorce files checking that the target 
file exists first
for file in files.keys():
if os.stat(files[file]['newname']).st_size == 
files[file]['size'] and deleteold.lower() == "true":
print deleteold.lower()
self.tv1.set("Deleting " + file)
os.remove(file)
else:
self.tv1.set("There was an error with " + file)
self.tv1.set("Copy done. " + str(len(files)) + " files were 
copied.")
   
def DisplayImage(self, file):
im = image.open(file)
origx, 

[Tutor] File IO help

2005-10-26 Thread Mike Haft
Hello all,
I'm new to python but so far I have to say its a really good language

I've been having some trouble with File IO can anyone help? I've got the
basics but my problem is that I have many files (one for each year of the
last 100 years or so) that look like this:

MONTH  RAIN   AVTEMP  RAD  EVAP

1  12.412.0*   10
2  13.930.0*   11
3

etc until month 12

So far all I know how to do in Python looks something like this:

def readInFile(inputName):
input = open(inputName, "r")
result = []
for line in input:
if line[:1] == "1":
fields = line.split()
data = fields[1] + fields[2] + fields[7]
result.append(data)
input.close()
return result

Thats basically all I've been able to do but I need to write script that
opens a file, reads the relevent data, stores that data and then closes
the file and moves on to the next file repeating the action until all the
files have been read. Then it needs to write a file with all the data it
has collected but in a different format.

If anyone can help I'd be really grateful. I hope I'm not asking too much
of the list but I haven't found anything that says READ THIS BEFORE
POSTING! on it to tell me otherwise.

Thanks in advance

Mike Haft

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


Re: [Tutor] Tkinter problem (.create_image)

2005-10-26 Thread Kent Johnson
Rob Dowell wrote:
> I am having a problem with Tkinter. The goal is a program that will copy 
> images from one folder to another then delete them from the source dir 
> after it is verified that they made it to the target dir. I have the 
> base functionality figured out (comments on that are welcome of course). 
> Now I want to have a gui that shows a small thumbnail of the image as it 
> is copied. Right now everything works fine except that the gui only 
> shows the last picture that is copied. Here is the code:

You have to give the GUI a chance to update by calling 
self.myParent.update_idletasks() after you set the new picture. You tell the 
GUI to show the picture but you never give a chance to do the actual work of 
drawing to the screen.

Kent

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


[Tutor] question about try & except

2005-10-26 Thread nephish
Hey there,
i am writing some (for me) pretty complicated stuff for work that
really needs to work. 
i have looked at exception handling in the Learning Python book.
and i am using some try / except statements. 
the problem is, that even though my script does not crash, i dont know
the exact error. 
is there a parameter that will allow me to use try and except but that
will also pring out the traceback statements that python usually does to
the terminal?

thanks

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


[Tutor] Module Thread

2005-10-26 Thread Joseph Quigley
I'm back to my IRC client. I accidentally found the thread module in the
Python 2.3 documentation while looking at the time module.

What I can't get ideas or hints from the documentation is:
What will i do to receive and send at the same time via console?

or:
Should I forget the idea of a console and start learning GUI which will
do this for me.

and lastly:
Should I have a program that handles all the sending and receiving and
puts it into a file and have to sub programs one that will write to the
file that the main program will read and send and one that just reads
the file which is received data.

I'm interested in python disto threads rather than other modules.

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


Re: [Tutor] question about try & except

2005-10-26 Thread Hugo González Monteverde
Yes,

You can catch an error object along with the exception, as in:

try:
 fileo = open("nofile")
except IOError, e:
 print "Alas...", e

As you see, the error object has a string representation equal wo what 
normally the python interpreter prints...

 >>>
Alas... [Errno 2] No such file or directory: 'nofile'
 >>>


Hope it helps. It took me originally a long time to know this trick, as 
it's kinda buried in the docs.

Hugo


nephish wrote:
> Hey there,
>   i am writing some (for me) pretty complicated stuff for work that
> really needs to work. 
>   i have looked at exception handling in the Learning Python book.
> and i am using some try / except statements. 
>   the problem is, that even though my script does not crash, i dont know
> the exact error. 
>   is there a parameter that will allow me to use try and except but that
> will also pring out the traceback statements that python usually does to
> the terminal?
> 
>   thanks
> 
> ___
> 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] question about try & except

2005-10-26 Thread nephish
Thanks Hugo,
Now that i know where to look
appreciate your help.
-sk


On Wed, 2005-10-26 at 21:27 -0600, Hugo González Monteverde wrote:
> Yes,
> 
> You can catch an error object along with the exception, as in:
> 
> try:
>  fileo = open("nofile")
> except IOError, e:
>  print "Alas...", e
> 
> As you see, the error object has a string representation equal wo what 
> normally the python interpreter prints...
> 
>  >>>
> Alas... [Errno 2] No such file or directory: 'nofile'
>  >>>
> 
> 
> Hope it helps. It took me originally a long time to know this trick, as 
> it's kinda buried in the docs.
> 
> Hugo
> 
> 
> nephish wrote:
> > Hey there,
> > i am writing some (for me) pretty complicated stuff for work that
> > really needs to work. 
> > i have looked at exception handling in the Learning Python book.
> > and i am using some try / except statements. 
> > the problem is, that even though my script does not crash, i dont know
> > the exact error. 
> > is there a parameter that will allow me to use try and except but that
> > will also pring out the traceback statements that python usually does to
> > the terminal?
> > 
> > thanks
> > 
> > ___
> > 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] Question about an re

2005-10-26 Thread ->Terry<-
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


os - Slackware
py - 2.4.1

I'm trying to grab the value 10 in

Visibility: 10 mile(s):0

but sometimes the value looks like

Visibility: 1/2 mile(s):0

My not working regex looks like

re.compile(': \d+|: \d/\d')

If I'm understanding right, this should match either or,
but it doesn't work for the fractional reading.

Can someone steer me in the right direction and explain
what I'm doing wrong?

Thanks much,
- -- 
 Terry

  ,-~~-.___. Terry Randall 
 / |  ' \
<   )0Linux Counter Project User# 98233
 \_/, ,-'
  //
   /  \-'~;/~~~(0)
  /  __/~|   /  |   If only Snoopy had Slackware...
=( __| (|

"He is your friend, your partner, your defender, your dog.
You are his life, his love, his leader. He will be yours,
faithful and true, to the last beat of his heart. You owe
it to him to be worthy of such devotion."-- Unknown

  (Best viewed with a mono-spaced font.)

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDYFhdQvSnsfFzkV0RAoPyAJ4jfwjWJ1eoqDatB6Hmg07XbUMGLQCeP/eQ
ognaRmmfxNlDW249jRqYE2g=
=Txx/
-END PGP SIGNATURE-

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


Re: [Tutor] question about try & except

2005-10-26 Thread w chun
> i am writing some (for me) pretty complicated stuff for work that
> really needs to work.
> i have looked at exception handling...
> and i am using some try / except statements.
> the problem is, that even though my script does not crash, i dont know
> the exact error.
> is there a parameter that will allow me to use try and except but that
> will also pring out the traceback statements that python usually does to
> the terminal?


exception handling is one of the greatest strengths of Python and
other high-level languages with this feature.  it allows the
programmer to anticipate potential problems and perhaps be able to
accept and process them at runtime.

let's say you have a code block called BLOCK.  newbies to Python would
typically do something like this to ensure that errors don't happen:

try:
BLOCK
except:
pass

however, this is not the case.  if errors *do* happen, they are thrown
away, thus serves no one any good, not the programmer nor the user.

the best solution is to catch specific exceptions and handle each
case.  (sure, and having just one handler for multiple exceptions is
also okay.).  one example is hugo's where he catches an IOError
exception and uses the exception instance 'e' to get more info out of
it.

now if you *don't* know what exceptions may happen, you can do
something similar.  it's almost a combination of the above two
handlers:

try:
BLOCK
except Exception, e:
print 'Caught exception without a specific handler:", e

this will at least tell you what exception happens in BLOCK, so that
you can modify it to be something like:

try:
BLOCK
except http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about try & except

2005-10-26 Thread nephish
Yeah, cool. i am just starting this part.
i am glad i started with python.
thanks for the help
sk


On Wed, 2005-10-26 at 21:32 -0700, w chun wrote:
> > i am writing some (for me) pretty complicated stuff for work that
> > really needs to work.
> > i have looked at exception handling...
> > and i am using some try / except statements.
> > the problem is, that even though my script does not crash, i dont 
> > know
> > the exact error.
> > is there a parameter that will allow me to use try and except but 
> > that
> > will also pring out the traceback statements that python usually does to
> > the terminal?
> 
> 
> exception handling is one of the greatest strengths of Python and
> other high-level languages with this feature.  it allows the
> programmer to anticipate potential problems and perhaps be able to
> accept and process them at runtime.
> 
> let's say you have a code block called BLOCK.  newbies to Python would
> typically do something like this to ensure that errors don't happen:
> 
> try:
> BLOCK
> except:
> pass
> 
> however, this is not the case.  if errors *do* happen, they are thrown
> away, thus serves no one any good, not the programmer nor the user.
> 
> the best solution is to catch specific exceptions and handle each
> case.  (sure, and having just one handler for multiple exceptions is
> also okay.).  one example is hugo's where he catches an IOError
> exception and uses the exception instance 'e' to get more info out of
> it.
> 
> now if you *don't* know what exceptions may happen, you can do
> something similar.  it's almost a combination of the above two
> handlers:
> 
> try:
> BLOCK
> except Exception, e:
> print 'Caught exception without a specific handler:", e
> 
> this will at least tell you what exception happens in BLOCK, so that
> you can modify it to be something like:
> 
> try:
> BLOCK
> except  # handle YourSpecificException code
> except Exception, e:
> print 'Caught exception without a specfic handler:', e
> 
> once you know the range of exceptions that may happen in BLOCK and
> have written handlers for them, you can dispense with the general
> catch-all.
> 
> hope this helps!
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2006,2001
> http://corepython.com
> 
> wesley.j.chun :: wescpy-at-gmail.com
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com

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