Re: [Tutor] Passing HTTP commands through Telnet using Python for web site testing?

2005-11-17 Thread Kent Johnson
Adisegna wrote:
> Hi,
> 
> I just started learning Python and would like to try writing a 
> monitoring script.
> 
> What I would like to do is use Telnet to send a GET via port 80 to a 
> status page in a directory to verify my site is up.

I use httplib for this. You can probably do it with urllib2 also but I don't 
know how to get the status codes from urllib2.

Here is an incomplete snippet:

try:
if self.method == 'http':
conn = HTTPConnection(self.server)
else:
conn = HTTPSConnection(self.server)

conn.request('GET', self.path)

resp = conn.getresponse()
data = resp.read()
status = resp.status

conn.close()

if status == 200:
success = self.successText in data

except socket.timeout:
clientErrorMsg = 'Ping failed due to timeout (%s seconds)' % timeout

except socket.error, msg:
clientErrorMsg = 'Ping failed with error ' + str(msg)

except:
clientErrorMsg = 
''.join(traceback.format_exception(*sys.exc_info()))

Kent

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] Passing HTTP commands through Telnet using Python forweb site testing?

2005-11-17 Thread Alan Gauld
Looks like you pretty well figured it out.

for the timestamp there is the basic timemodule, the datetime module
or the extra module mxdatetime. Each more sophisticated than the last...

Alan G
- Original Message - 
From: "Adisegna" <[EMAIL PROTECTED]>
To: 
Sent: Thursday, November 17, 2005 4:13 AM
Subject: Re: [Tutor] Passing HTTP commands through Telnet using Python 
forweb site testing?


So far this is what I have come up with doing some research.

import urllib
for line in urllib.urlopen('http://mywebsit.com/folder/folder/test.asp'):
if '400 Bad Request' in line:

text_file = open("mysite.log", "a")
text_file.writelines(line)
text_file.writelines("\n")
text_file.close()

This writes the to a new line each time the script is run. Now I have to
figure out an "if then else" to write the other possible error codes and
appending a timestamp followed by a space each time it runs.

Thanks

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


Re: [Tutor] Passing HTTP commands through Telnet using Python for website testing?

2005-11-17 Thread Alan Gauld
> Anyway, Can someone point me in the right direction on getting the Telnet
> working? Or if you have a better way to get what I am trying to do
> accomplished. Is there a Python Telnet module?

I think the urllib module will be easier.

Just open the url and read the output into a list. check the line and if
necessary write to the log file

Psuedocode:

import urllib as url
import time
logfile = open('log.txt','a;')  # append mode

page = url.open('www.whatever.com/wherever').read()
page = page.split()
if '404' in page[0]:  # will it be the first line?
   logfile.write('Whoops it went missing at: ' + 
str(time.strtime(time.time()))
url.close()

Does that look like the kind of thing?

Alan G.



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


Re: [Tutor] split a tuple

2005-11-17 Thread Chris or Leslie Smith
| Hi,
| 
| I couldn't get idea how to make the next thing
| 
 n=4 #split into so long parts
 l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split
 [l[i:i+n] for i in range(0,len(l),n)]
| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)]
| 
| But I have to make it like this
| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)]
| because i use it later in this
| 
 result = [l[i:i+n] for i in range(0,len(l),n)]
 zip(*result)
| [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)]
| 
| and as you can see it, the last element is missing here.
| 

Since it will always be the last one that is not the correct length; can you 
just add another line to extend the length of the last one by the correct 
number of default values (that number being the difference between how many you 
want and how many you have)?

##
>>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
>>> n=4
>>> regrouped = [l[i:i+n] for i in range(0,len(l),n)]
>>> default = 'default'
>>> regrouped[-1]=list(regrouped[-1])
>>> regrouped[-1].extend([default]*(n-len(regrouped[-1])))
>>> regrouped[-1]=tuple(regrouped[-1])
>>> regrouped
[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')]
>>> 
>>> ['a']*3 #so you can see what the rhs multiply does
['a', 'a', 'a']

##

Since tuples cannot be changed, you have to go through the tuple<->list 
conversion steps. If you can work with a list instead, then these two steps 
could be eliminated:

##
>>> l = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] #using a list instead
>>> regrouped = [l[i:i+n] for i in range(0,len(l),n)]
>>> regrouped[-1].extend([default]*(n-len(regrouped[-1])))
>>> regrouped
[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2], [3, 4, 5, 'default']]
>>> 
##

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


Re: [Tutor] Passing HTTP commands through Telnet using Python for web site testing?

2005-11-17 Thread Kent Johnson
Adisegna wrote:
> So far this is what I have come up with doing some research.
> 
> import urllib
> for line in urllib.urlopen('http://mywebsit.com/folder/folder/test.asp'):
>  if '400 Bad Request' in line: 
> 
> text_file = open("mysite.log", "a")
> text_file.writelines(line)
> text_file.writelines("\n")
> text_file.close()

You are counting on the HTTP status code being part of the body of the 
response. This will depend on the details of the server. Better is to look at 
the actual HTTP status. Here is an example of retrieving a page with urllib2 
and capturing HTTP status codes:
http://mail.python.org/pipermail/python-list/2003-July/175455.html

Kent

-- 
http://www.kentsjohnson.com

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


[Tutor] how to identify a list element is in the range of a tuple element or a list element

2005-11-17 Thread Srinivas Iyyer
Dear group, 

I have a list of numbers:

a = [10,3,4.6,2.3,4.8,10.8,4.1]
b = ['1-4','4.1-8','8.1-12','12.1-16']
c = ((1,4),(4.1,8),(8.1-12),(12.1,16))

Now I want to find if elements of list a are in the
range of list b and in the range of tuple b. 

I know (and my limited knowledge on range function) is
not allowing me to think of a new way. 

Could any one please help me.

I wish to have the answer as:

10   8.1-12
31-4
etc. 

Thank you for help in advance.

srini




__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to identify a list element is in the range of a tuple element or a list element

2005-11-17 Thread Kent Johnson
Srinivas Iyyer wrote:
> Dear group, 
> 
> I have a list of numbers:
> 
> a = [10,3,4.6,2.3,4.8,10.8,4.1]
> b = ['1-4','4.1-8','8.1-12','12.1-16']
> c = ((1,4),(4.1,8),(8.1-12),(12.1,16))
> 
> Now I want to find if elements of list a are in the
> range of list b and in the range of tuple b. 
> 
> I know (and my limited knowledge on range function) is
> not allowing me to think of a new way. 
> 
> Could any one please help me.
> 
> I wish to have the answer as:
> 
> 10   8.1-12
> 31-4
> etc. 
> 

A brute-force approach is straighforward. I ignore b since it has the same 
values as c, and I corrected the third entry in c to be a tuple.

 >>> a = [10,3,4.6,2.3,4.8,10.8,4.1]
 >>> c = ((1,4),(4.1,8),(8.1, 12),(12.1,16))
 >>> for x in a:
 ...   for lower, upper in c:
 ... if lower <= x <= upper:
 ...   print '%-5s%s-%s' % (x, lower, upper)
 ...
10   8.1-12
31-4
4.6  4.1-8
2.3  1-4
4.8  4.1-8
10.8 8.1-12
4.1  4.1-8

If a and c are large this could be slow, it could be optimized by searching in 
c instead of exhaustive search, or by terminating the inner loop when a match 
is found or when lower > x.

Kent

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] lambda in a loop

2005-11-17 Thread Christian Wyglendowski
Fred said:
> >> Obviously, the lambda is using "value" at the end of the loop (4),
> >>rather than what I want, "value" during the loop (0,1,2,3).  

Christian said:
> > Right.  I think the issue is that your lambda calls another funtion.
> > However, the function isn't called until the lambda is called later,
> > when value == 4.

Kent said:
> No, the problem is not when the function is called, but when 
> value is bound into the closure.

I don't think that the value is being bound into the closure, though.
It is using the global 'value', which is why I said "the function isn't
called until the lambda is called later, when value == 4".  I should
have been more clear and said "when global value == 4".  

I think this can be demonstrated by adding a "del value" statement after
the loop.  Here is the traceback I get after adding that statement:

Traceback (most recent call last):
  File
"C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py"
, line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\Documents and
Settings\cwyglendowski\Desktop\cp_playground\lambdatest.py", line 12, in
?
c()
  File "C:\Documents and
Settings\cwyglendowski\Desktop\cp_playground\lambdatest.py", line 7, in

commands.append(lambda:doLambda(value))
NameError: global name 'value' is not defined


Christian said:
> > I'd use a closure rather than a lambda. 

Kent said:
> The original solution does use a closure. 

Thanks for pointing that out.  I don't use lambda often and didn't think
about how you can create closures with lambda statements.

Kent said:
> The problem is that 
> variables are not bound into a closure until the scope of the 
> variable exits. That is why using a separate factory function 
> works - the closure is bound when the factory function exits 
> which happens each time through the loop. In the case of 
> closures in a loop the closure is not bound until exiting the 
> scope containing the loop and all the closures are bound to 
> the same value.

I'm not even going to go there ... Danny just wrote an excellent book on
this :-)

Thanks to all for the great discussion.

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


Re: [Tutor] how to identify a list element is in the range of a tuple element or a list element

2005-11-17 Thread Pujo Aji
for b you can use this code:
    a = [10,3,4.6,2.3,4.8,10.8,4.1]    b = ['1-4','4.1-8','8.1-12','12.1-16']    for x in a:    for y in b:    low,up = y.split('-')    if  float(low) < x < float(up):
    print '%s   %s - %s' % (x, low, up)    break    Cheers,
pujo 
On 11/17/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Srinivas Iyyer wrote:> Dear group,>> I have a list of numbers:>> a = [10,3,
4.6,2.3,4.8,10.8,4.1]> b = ['1-4','4.1-8','8.1-12','12.1-16']> c = ((1,4),(4.1,8),(8.1-12),(12.1,16))>> Now I want to find if elements of list a are in the> range of list b and in the range of tuple b.
>> I know (and my limited knowledge on range function) is> not allowing me to think of a new way.>> Could any one please help me.>> I wish to have the answer as:>
> 10   8.1-12> 31-4> etc.>A brute-force approach is straighforward. I ignore b since it has the same values as c, and I corrected the third entry in c to be a tuple.>>> a = [10,3,
4.6,2.3,4.8,10.8,4.1]>>> c = ((1,4),(4.1,8),(8.1, 12),(12.1,16))>>> for x in a:...   for lower, upper in c:... if lower <= x <= upper:...   print '%-5s%s-%s' % (x, lower, upper)
...10   8.1-1231-44.6  4.1-82.3  1-44.8  4.1-810.8 8.1-124.1  4.1-8If a and c are large this could be slow, it could be optimized by searching in c instead of exhaustive search, or by terminating the inner loop when a match is found or when lower > x.
Kent--http://www.kentsjohnson.com___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] split a tuple

2005-11-17 Thread János Juhász
Hi Chris,

Thanks your response.

I have just found another way.

>>> import math
>>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
>>> n = 4
>>> extended = l + ('default',)*int(n - math.fmod(len(l),n))
>>> [extended[i:i+n] for i in range(0,len(extended),n)]
[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')]


>>>| Hi,
>>>|
>>>| I couldn't get idea how to make the next thing
>>>|
>>> n=4 #split into so long parts
>>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split
>>> [l[i:i+n] for i in range(0,len(l),n)]
>>>| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)]
>>>|
>>>| But I have to make it like this
>>>| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)]
>>>| because i use it later in this
>>>|
>>> result = [l[i:i+n] for i in range(0,len(l),n)]
>>> zip(*result)
>>>| [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)]
>>>|
>>>| and as you can see it, the last element is missing here.
>>>|
>>>
>>>Since it will always be the last one that is not the correct length; can
you just add another line to extend the >>>length of the last one by the
correct number of default values (that number being the difference between
how many >>>you want and how many you have)?
>>>
>>>##
>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
>> n=4
>> regrouped = [l[i:i+n] for i in range(0,len(l),n)]
>> default = 'default'
>> regrouped[-1]=list(regrouped[-1])
>> regrouped[-1].extend([default]*(n-len(regrouped[-1])))
>> regrouped[-1]=tuple(regrouped[-1])
>> regrouped
>>>[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')]
>>
>> ['a']*3 #so you can see what the rhs multiply does
>>>['a', 'a', 'a']
>>>
>>>##
>>>
>>>Since tuples cannot be changed, you have to go through the tuple<->list
conversion steps. If you can work with a >>>list instead, then these two
steps could be eliminated:
>>>
>>>##
>> l = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] #using a list instead
>> regrouped = [l[i:i+n] for i in range(0,len(l),n)]
>> regrouped[-1].extend([default]*(n-len(regrouped[-1])))
>> regrouped
>>>[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2], [3, 4, 5, 'default']]
>>
>>>##
>>>
>>>/c


Yours sincerely,
__
János Juhász

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


Re: [Tutor] Using lists as table-like structure

2005-11-17 Thread Bernard Lebel
Thanks to everyone for the answers. I'll definitely check Numeric Python.


Cheers
Bernard




On 11/16/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
>
> On Wed, 16 Nov 2005, Bernard Lebel wrote:
>
> > Let say I have a list of lists. Each individual lists have a bunch of
> > elements. Now I would like to either get or set the first element of
> > each individual list. I could do a loop and/or list comprehension, but I
> > was wondering if it was possible with something like:
> >
> > aList = [ [1,1,1], [2,2,2,], [3,3,3] ]
> > aList[:][0] = 10
>
>
> Hi Bernard,
>
> I think I see what you're trying to do; you're trying to clear the first
> column of each row in your matrix.  Unfortunately, this is not done so
> easily in standard Python.  However, if you use the third-party Numeric
> Python (numarray) package, you can use its array type to do what you want.
>
>
> > If I print aList[:], I get the list with the nested sublists.
> >
> > >>> aList[:]
> > [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>
> Yes, sounds good so far.
>
>
> > But as soon as I introduce the [0], in an attempt to access the first
> > element of each sublist, I get the first sublist in its entirety:
> >
> > >>> aList[:][0]
> > [1, 1, 1]
>
>
> Let's do a quick substitution model thing here.  You mentioned earlier
> that:
>
> > >>> aList[:]
> > [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>
> So if we just plug that value into aList[:][0]:
>
>  aList[:][0]  ==>  [[1, 1, 1,], [2, 2, 2], [3, 3, 3]] [0]
>
> then we see that we're just asking for the first element of aList[:],
> which is [1, 1, 1].
>
>
>
> > I would have hoped to get something like [1, 2, 3]
>
> Take a look into Numeric Python: it'll give you the row/column slicing
> operations that you're expecting.  As a concrete example:
>
> ##
> >>> import numarray
> >>> a = numarray.array([[1, 2, 3],
> ... [4, 5, 6],
> ... [7, 8, 9]])
> >>> a[:, 0]
> array([1, 4, 7])
> >>> a[:, 1]
> array([2, 5, 8])
> >>> a[:, 2]
> array([3, 6, 9])
> ##
>
>
> Best of wishes!
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newb ?

2005-11-17 Thread Ed Singleton
These both work (though neither is very graceful).

text = "hello"
message = ""

for i in range(len(text)):
   message = message + text[(len(text)-i-1)]

print message


lst = list(text)
newstr = ""

for item in text:
   newstr += (lst.pop())

print newstr

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


[Tutor] How to remove Html from list.

2005-11-17 Thread Laszlo Antal
Hi,
This is what I would like to do.:
1: Read in an Html file as a list with readlines,
2: Loop through the list,
3: Take out the text or number that is between
  the Html,
4: Insert the text or number into a new list,
5: print out the new list with the text.

I have a problem with section 3 !
I can not figure out what kind of expresion I need to use to find Html 
code.

Any help would be great.

Thank you
Laszlo Antal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] slices

2005-11-17 Thread Will Harris
Is there an easy way to slice the last set of characters off a string
when I don't know the length of the string? For example say I have a
list of words like
   this
   though
   weather
I want to get the last 2 characters from each. But so far nothing I
have tried has seemed to work. Currently I am doing something like:

#!/usr/bin/python
import sys

for word in sys.argv[1:]:
 print word[-3:-1]

I have tried to change the numbers around but I always seem to end up
at the wrong place of the string. If I new the length each time I could
just do a positive.
Doesn't this work in the form of:

t    h   i    s
0   1   2   3
-4 -3  -2  -1

Did I miss something somewhere in some tutorial that someone would be kind enough to point me to?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slices

2005-11-17 Thread Will Harris
Blah brain freeze I saw my mistake as I hit send.
It should just be word[-2:]

So 

#!/usr/bin/python

import sys



for word in sys.argv[1:]:

 print word[-2:]

Works now. Thanks!
On 11/17/05, Will Harris <[EMAIL PROTECTED]> wrote:
Is there an easy way to slice the last set of characters off a string
when I don't know the length of the string? For example say I have a
list of words like
   this
   though
   weather
I want to get the last 2 characters from each. But so far nothing I
have tried has seemed to work. Currently I am doing something like:

#!/usr/bin/python
import sys

for word in sys.argv[1:]:
 print word[-3:-1]

I have tried to change the numbers around but I always seem to end up
at the wrong place of the string. If I new the length each time I could
just do a positive.
Doesn't this work in the form of:

t    h   i    s
0   1   2   3
-4 -3  -2  -1

Did I miss something somewhere in some tutorial that someone would be kind enough to point me to?


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


Re: [Tutor] new topic draft

2005-11-17 Thread Johan Geldenhuys
That will be great. In the "@TODO" part you will see that I still need 
to take the output from the command  and capture that into a file. Can 
you help me with that?

Johan

Alan Gauld wrote:

> Thanks, I may use that as one of the example programs if
> you don't mind?
>
> Alan G.
>
>
> - Original Message - From: "Johan Geldenhuys" 
> <[EMAIL PROTECTED]>
> To: "Alan Gauld" <[EMAIL PROTECTED]>
> Cc: "Python Tutor list" 
> Sent: Wednesday, November 16, 2005 8:12 AM
> Subject: Re: [Tutor] new topic draft
>
>
>> Alan,
>>
>> You may remember that I asked questions on killing a process, a while 
>> back,
>>
>> Sice this is relatedto the tutorial that yu are writing, this was the
>> best solution that worked for me to killa process for a command that
>> keeps on running like eg. 'tcpdump'.
>>
>> HTH
>>
>> Johan
>> BTW, There will a be many a felllow Pythonists that will benefit from a
>> tut like this, great work !!
>>
>>
>> Alan Gauld wrote:
>>
>>> I've just added an incomplete draft copy of my latest tutorial topic
>>> on using the Operating System from Python. The material that's
>>> there discusses the role of the OS and looks at file handling
>>> usng os/os.path/shutil etc.
>>>
>>> http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm
>>>
>>> If anyone would like to take a look and provide feedback on
>>> general direction/depth etc that'd be greatly appreciated.
>>>
>>> TIA,
>>>
>>> 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
>>>
>>>
>>>
>>
>
>
> 
>  
>
>
>
>> """
>>   This class will execute the command, let it run for 5 seconds and 
>> kill the process.
>>
>>   ::Author: Johan Geldenhuys
>> [EMAIL PROTECTED]
>>
>>   ::Version: 0.0.1
>>
>>   ::Date last updated: 2005-11-03
>>
>>   ::Changes:
>>
>>   :: TODO:  Capture the output from line 41 to a file.
>> """
>>
>> import os, signal, time
>>
>> class command(object):
>>
>>def __init__(self):
>>
>>pass
>>
>>
>>def kill(self, pid, signal=signal.SIGTERM):
>>try:
>>
>>print "trying to kill pid...", pid
>>os.kill(pid, signal)
>>#os.waitpid(pid, 0)
>>print "Killed %d"%pid
>>except:
>>   print "couldn't stop process"
>>
>>def main(self, interface):
>>
>>self.interface = interface
>>self.pid = os.fork()
>>
>>if self.pid == 0:
>>
>>   os.execvp('tcpdump', ['tcpdump', '-npi', self.interface])
>>
>>print 'PID: ',self.pid
>>print 'Let it run for 5 seconds...'
>>time.sleep(5)
>>self.kill(self.pid)
>>
>>
>> if __name__ == '__main__':
>>   print "starting test"
>>   c = command()
>>   c.main('eth0')
>>
>>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] new topic draft

2005-11-17 Thread Johan Geldenhuys




What is this line supposedto do?
cmd.run('www.python.org')


Christopher Arndt wrote:

  Alan Gauld schrieb:
  
  
Thanks, I may use that as one of the example programs if
you don't mind?

  
  
I took the liberty of refactoring Johan's example a bit, to make it more
reusable. See attached file.

Chris
  
  

"""Wrapper object for external commands, that allows to kill them after later..

   ::Author: Johan Geldenhuys
 [EMAIL PROTECTED]

   ::Version: 0.0.2

   ::Date last updated: 2005-11-16

   ::Changes:
  - refactored by Christopher Arndt

   :: TODO:  Capture the output from line 41 to a file.
"""

import os, signal, time

class KillableCommand(object):

def __init__(self, command, *args):
self.pid = None
self.command = command
self.args = args

def kill(self, signal=signal.SIGTERM):
try:
os.kill(self.pid, signal)
except:
raise OSError, "Could not kill process."

def run(self, *args):
self.pid = os.fork()
args = list(self.args + args)
if self.pid == 0:
   os.execvp(self.command, [self.command] + args)

if __name__ == '__main__':
cmdname = "ping"
print "Starting", cmdname
#cmd = KillableCommand('tcpdump', '-npi')
cmd = KillableCommand(cmdname, '-c', '10')
cmd.run('www.python.org')
print "PID: ", cmd.pid
print "Letting it run for 5 seconds..."
time.sleep(5)
try:
print "Trying to kill pid %d..." % cmd.pid
cmd.kill()
except OSError, e:
print e
else:
print "Killed pid %d." % cmd.pid
  
  

___
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 topic draft

2005-11-17 Thread Christopher Arndt
Johan Geldenhuys wrote:
> What is this line supposedto do?
> 
> cmd.run('www.python.org')

Run the command that was defined at object creation ('ping -c 10') with
the argument 'www.python.org'.

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


Re: [Tutor] new topic draft

2005-11-17 Thread Johan Geldenhuys




This script was not intended to be used from the command line, but to
be called from elsewhere. It was only a test piece of code. 
If you use the ping command with the args that you are calling it with,
there is no need to kill the process, it will terminate after 10
requests.   8-) 

Johan

Christopher Arndt wrote:

  Alan Gauld schrieb:
  
  
Thanks, I may use that as one of the example programs if
you don't mind?

  
  
I took the liberty of refactoring Johan's example a bit, to make it more
reusable. See attached file.

Chris
  
  

"""Wrapper object for external commands, that allows to kill them after later..

   ::Author: Johan Geldenhuys
 [EMAIL PROTECTED]

   ::Version: 0.0.2

   ::Date last updated: 2005-11-16

   ::Changes:
  - refactored by Christopher Arndt

   :: TODO:  Capture the output from line 41 to a file.
"""

import os, signal, time

class KillableCommand(object):

def __init__(self, command, *args):
self.pid = None
self.command = command
self.args = args

def kill(self, signal=signal.SIGTERM):
try:
os.kill(self.pid, signal)
except:
raise OSError, "Could not kill process."

def run(self, *args):
self.pid = os.fork()
args = list(self.args + args)
if self.pid == 0:
   os.execvp(self.command, [self.command] + args)

if __name__ == '__main__':
cmdname = "ping"
print "Starting", cmdname
#cmd = KillableCommand('tcpdump', '-npi')
cmd = KillableCommand(cmdname, '-c', '10')
cmd.run('www.python.org')
print "PID: ", cmd.pid
print "Letting it run for 5 seconds..."
time.sleep(5)
try:
print "Trying to kill pid %d..." % cmd.pid
cmd.kill()
except OSError, e:
print e
else:
print "Killed pid %d." % cmd.pid
  
  

___
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] How to remove Html from list.

2005-11-17 Thread Alan Gauld
> I can not figure out what kind of expresion I need to use to find Html 
> code.

Take a look at the regular expressions topic in my tutorial which gives 
an example of stripping stuff from HTML>

However be aware that using regular expressions on html is never 
reliable and a proper parser like BeautifulSoup or ElemTree will do 
a much better job.

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] compiled images

2005-11-17 Thread Fred Lionetti
Hi everyone,

Thanks everyone for the help with lambda expressions!  Your
suggestions and discussions were great!

I've got another question I think you may have come across before. 
I'm planning on purchasing a license to use some stock icons in an
application I'm developing.  The problem is the license requires this:

"Where an application is to be distributed, the graphical media must
be compiled into the application binary file or its associated data
files, documentation files, or components."

Anyone have any idea as to how I could basically "compile" all my
artwork into a data file for a python application?  Would this require
compiling them into a *.dll/*.so?  It seems like there must be any
easier way--Also, I need my application to work on windows + linux
(and mac).

Any suggestions/experience would be greatly appreciated!

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


Re: [Tutor] Newb ?

2005-11-17 Thread Liam Clarke-Hutchinson
How about -
print "\n\nWelcome to the Backwards Message Display."
print
message = raw_input("\nPlease Enter a Message.")
msgAsList = [ char for char in message]
msgAsList.reverse()
reversedMessage = ''.join(msgAsList)

I can't test that, but it should work.

But, with regard to - 

> print "\n\nWelcome to the Backwards Message Display."
> print
> message = raw_input("\nPlease Enter a Message.")
>
> high = len(message)
> low = -len(message)
> print
> print message[high:low]
> print
> print raw_input("Please Press Enter to Exit")

low will always be the first char of the string, won't it? In which case,
It'd always be 0. or len(message) - len(message) !

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Ed Singleton
Sent: Friday, 18 November 2005 6:11 a.m.
To: tutor@python.org
Subject: Re: [Tutor] Newb ?


These both work (though neither is very graceful).

text = "hello"
message = ""

for i in range(len(text)):
   message = message + text[(len(text)-i-1)]

print message


lst = list(text)
newstr = ""

for item in text:
   newstr += (lst.pop())

print newstr

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

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] compiled images

2005-11-17 Thread Liam Clarke-Hutchinson
Hehe, 

Sounds like someone's license was designed for C/C++.




-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Fred Lionetti
Sent: Friday, 18 November 2005 8:29 a.m.
To: tutor@python.org
Subject: [Tutor] compiled images


Hi everyone,

Thanks everyone for the help with lambda expressions!  Your suggestions and
discussions were great!

I've got another question I think you may have come across before. 
I'm planning on purchasing a license to use some stock icons in an
application I'm developing.  The problem is the license requires this:

"Where an application is to be distributed, the graphical media must be
compiled into the application binary file or its associated data files,
documentation files, or components."

Anyone have any idea as to how I could basically "compile" all my artwork
into a data file for a python application?  Would this require compiling
them into a *.dll/*.so?  It seems like there must be any easier way--Also, I
need my application to work on windows + linux (and mac).

Any suggestions/experience would be greatly appreciated!

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

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newb ?

2005-11-17 Thread Christian Wyglendowski
Liam said:
> 
> How about -
> print "\n\nWelcome to the Backwards Message Display."
> print
> message = raw_input("\nPlease Enter a Message.")
> msgAsList = [ char for char in message]

You could also do:

msgAsList = list(message)

list() takes any iterable and returns a list object.

> msgAsList.reverse()
> reversedMessage = ''.join(msgAsList)

In Python 2.4, the following is also possible:

reversedMessage = ''.join(reversed(list(message)))

It's amazing how in Python even one-liners can be so pretty :-)

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


Re: [Tutor] Newb ?

2005-11-17 Thread Liam Clarke-Hutchinson

>list() takes any iterable and returns a list object.
Hmm, I did not know that the list(str) thing worked that way.That'll reduce
the list comprehensions, but is it intuitive? Would a newbie see that and
think that list("Hi") returns ["Hi"] or ["H","i"] ?
 
>reversedMessage = ''.join(reversed(list(message)))

Yes, but for clarity when demonstrating a concept, one-liners should be
minimised, I think. ;)
But I agree, you can create some obscenely complicated one liners, which are
still understandable.
I find I have to force myself sometimes to refactor some of the ones I come
up with, however. Good rule of thumb is when you're feeling impressed with
your own cleverness, you probably need to refactor. 
(Thanks c2 wiki, for teaching me that.)


-Original Message-
From: Christian Wyglendowski [mailto:[EMAIL PROTECTED] 
Sent: Friday, 18 November 2005 9:31 a.m.
To: Liam Clarke-Hutchinson; tutor@python.org
Subject: RE: [Tutor] Newb ?


Liam said:
> 
> How about -
> print "\n\nWelcome to the Backwards Message Display."
> print
> message = raw_input("\nPlease Enter a Message.")
> msgAsList = [ char for char in message]

You could also do:

msgAsList = list(message)

list() takes any iterable and returns a list object.

> msgAsList.reverse()
> reversedMessage = ''.join(msgAsList)

In Python 2.4, the following is also possible:

reversedMessage = ''.join(reversed(list(message)))

It's amazing how in Python even one-liners can be so pretty :-)

Christian

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] compiled images

2005-11-17 Thread Christian Wyglendowski
Fred said:
> 
[snip] 
> I've got another question I think you may have come across before. 
> I'm planning on purchasing a license to use some stock icons in an
> application I'm developing.  The problem is the license requires this:
> 
> "Where an application is to be distributed, the graphical media must
> be compiled into the application binary file or its associated data
> files, documentation files, or components."
> 
> Anyone have any idea as to how I could basically "compile" all my
> artwork into a data file for a python application?  Would this require
> compiling them into a *.dll/*.so?  It seems like there must be any
> easier way--Also, I need my application to work on windows + linux
> (and mac).

Hhhmm...from what I remember, getting at icons in DLLs is pretty easy.
I think that is where windows stores a lot of its icons actually.  If
they are just looking to dissuade the "casual icon theft" maybe they
would be ok if you included the images as base64 encoded strings in your
source code:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52264

You could even take that further by having a resource file or something
that contained pickled base64 encoded image strings.  Maybe that would
be "compiled" enough for them?

> Any suggestions/experience would be greatly appreciated!

Hope some of this helps.  I guess asking them how they have dealt with
interpreted languages in the past might help.

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


Re: [Tutor] Newb ?

2005-11-17 Thread Orri Ganel
Christian Wyglendowski wrote:

>Liam said:
>  
>
>>How about -
>>print "\n\nWelcome to the Backwards Message Display."
>>print
>>message = raw_input("\nPlease Enter a Message.")
>>msgAsList = [ char for char in message]
>>
>>
>
>You could also do:
>
>msgAsList = list(message)
>
>list() takes any iterable and returns a list object.
>
>  
>
>>msgAsList.reverse()
>>reversedMessage = ''.join(msgAsList)
>>
>>
>
>In Python 2.4, the following is also possible:
>
>reversedMessage = ''.join(reversed(list(message)))
>
>It's amazing how in Python even one-liners can be so pretty :-)
>
>Christian
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Or you could just do the following:

>>> print "\n\nWelcome to the Backwards Message Display."
>>> print
>>> message = raw_input("\nPlease Enter a Message.")
>>> print message[::-1]


This is the equivalent of print ''.join(reversed(message)), since 
reversed works on any iterable sequence, including strings.  In any 
case, the syntax for this sort of thing in general is: 
sequence[start:stop:step], with start defaulting to 0, step defaulting 
to sys.maxint (which, for all intents and purposes, means the end of the 
string), and step defaulting to 1.  However, when step is negative, 
start and end switch defaults.  So by doing [::-1], you're telling 
Python to return the values of the sequence that can be found from the 
end to the start  Another way to do this would be:

 >>> import sys
 >>> for i in range(len(sequence)-1,-1,-1):
   sys.stdout.write(sequence[i]) # to remove spaces between elements,
 # which would be produced by the more
 # intuitive "print sequence[i]," 
technique

So, the first time around, i is len(sequence)-1, or the last element, 
because that's the start value.
Next, it's len(sequence)-2, or the second to last element, because the 
step is -1.
etc . . .
Until the last round when i is 0, after which step is added to i and 
i==-1, so the loop is not re-entered.

HTH,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

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


Re: [Tutor] Newb ?

2005-11-17 Thread Christian Wyglendowski
Orri said:
> Or you could just do the following:
> 
> >>> print "\n\nWelcome to the Backwards Message Display."
> >>> print
> >>> message = raw_input("\nPlease Enter a Message.")
> >>> print message[::-1]

Interesting.  I forgot about the 'step' option when slicing.
 
> This is the equivalent of print ''.join(reversed(message)), since 
> reversed works on any iterable sequence, including strings.  

Ha!  Good call.  Makes it even clearer.

> In any 
> case, the syntax for this sort of thing in general is: 
> sequence[start:stop:step], with start defaulting to 0, step 
> defaulting 
> to sys.maxint (which, for all intents and purposes, means the 
> end of the 
> string), and step defaulting to 1.  However, when step is negative, 
> start and end switch defaults.  So by doing [::-1], you're telling 
> Python to return the values of the sequence that can be found 
> from the 
> end to the start

Cool.  Thanks for this explanation.

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


Re: [Tutor] compiled images

2005-11-17 Thread John Fouhy
On 18/11/05, Fred Lionetti <[EMAIL PROTECTED]> wrote:
> Anyone have any idea as to how I could basically "compile" all my
> artwork into a data file for a python application?  Would this require
> compiling them into a *.dll/*.so?  It seems like there must be any
> easier way--Also, I need my application to work on windows + linux
> (and mac).

Maybe you could use shelve?

For instance, if you have myIcon1.gif, myIcon2.gif, myIcon3.gif:


import shelve
shelf = shelve.open('iconData')
for fn in ['myIcon1.gif', 'myIcon2.gif', 'myIcon3.gif']:
shelf[fn] = file(fn, 'rb').read()


Then, in future, you should be able to access your icons by just:

 shelf = shelve.open('iconData')
 doSomething(shelf['myIcon2.gif'])

(and if your methods require a file-like object instead of just a
binary string, you can use the StringIO module)

There may be space or time issues --- you might want to experiment :-)
--- but it will definitely be cross-platform.

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


Re: [Tutor] new topic draft

2005-11-17 Thread Christopher Arndt
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Johan Geldenhuys schrieb:
>  This script was not intended to be used from the command line, but to
> be called from elsewhere. It was only a test piece of code.
> If you use the ping command with the args that you are calling it with,
> there is no need to kill the process, it will terminate after 10
> requests.  8-)

Yes, that's right. It was just an example and I wanted it to terminate wether
the killing of the process succeeded or not. I just thought I might be of help
in turning an interesting idea into something instantly reusable.

Chris

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.5 (GNU/Linux)
Comment: Seeing only garbage? Get my OpenPGP key here:
http://chrisarndt.de/contact.html

iD8DBQFDfQ4/XWGCGKl166oRAuP5AJ97+yt1C79AC1XUGn2oWtuDUmN3KgCfcQPu
hAZibDiEVrdDtzBJDv+hWWo=
=EukF
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] opts and try except

2005-11-17 Thread Eric Walker
All,
I have a program now that works just like I want it. Now I want to 
integerate something to say print usage info when the user puts in the wrong 
number or type of options. Also print usage say if you type program name and 
-h or -H. I currently just have functions defined and at the bottom make a 
function call. Do I need to do like the def main(): and then the if __name__ 
== "__main__"? I need an example of how to implement this. 

Thanks in advance.


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


[Tutor] building nonbinary trees

2005-11-17 Thread Vincent Wan
I would like to have a tree data structure with trees whose nodes  
could have an arbitrary
number of descendants and that I could iterate over by the names of  
nodes

I'v got a start but I'm stuck because I don't understand how to call  
a tree's nodes by name.

Here is the code I have so far:

import random

# constants that control the simulation
NUMBER_REPS = 10# run's the simulation
MAX_LINAGES = 10# number of species in each run
BRANCHING_PROBABILITY = 0.5

class Tree(object):
 numLinages = 0
 class Node(object):
 def __init__(self, name):
 self.name = name
 self.alive = True
 self.descendents = []
 Tree.numLinages += 1
 def __init__(self):
 self.rootnode = Tree.Node(0)
 def AddBranch(self, linage, offspring):
 new = Tree.Node(offspring)
 self.descendents.append(new)
 def NumLinages(  ):
 return Tree.numLinages
 NumLinages = staticmethod(NumLinages)

currentTree = Tree()
print Tree.NumLinages()

for i in range(NUMBER_REPS):
 j = 0
 while j <= currentTree.NumLinages():
 if random.random() >= BRANCHING_PROBABILITY:
 currentTree.AddBranch(j, currentTree.NumLinages() + 1)
 j += 1


thank you,


Vincent Wan

 
--
PhD Candidate
Committee on the Conceptual and Historical Studies of Science
University of Chicago

PO Box 73727
Fairbanks, AK 99707

wan AT walrus DOT us (change CAPS to @ and . )

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


Re: [Tutor] building nonbinary trees

2005-11-17 Thread Liam Clarke-Hutchinson


Erm, a dictionary of names to references?
 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Vincent Wan
Sent: Friday, 18 November 2005 2:21 p.m.
To: tutor@python.org
Subject: [Tutor] building nonbinary trees


I would like to have a tree data structure with trees whose nodes  
could have an arbitrary
number of descendants and that I could iterate over by the names of  
nodes

I'v got a start but I'm stuck because I don't understand how to call  
a tree's nodes by name.

Here is the code I have so far:

import random

# constants that control the simulation
NUMBER_REPS = 10# run's the simulation
MAX_LINAGES = 10# number of species in each run
BRANCHING_PROBABILITY = 0.5

class Tree(object):
 numLinages = 0
 class Node(object):
 def __init__(self, name):
 self.name = name
 self.alive = True
 self.descendents = []
 Tree.numLinages += 1
 def __init__(self):
 self.rootnode = Tree.Node(0)
 def AddBranch(self, linage, offspring):
 new = Tree.Node(offspring)
 self.descendents.append(new)
 def NumLinages(  ):
 return Tree.numLinages
 NumLinages = staticmethod(NumLinages)

currentTree = Tree()
print Tree.NumLinages()

for i in range(NUMBER_REPS):
 j = 0
 while j <= currentTree.NumLinages():
 if random.random() >= BRANCHING_PROBABILITY:
 currentTree.AddBranch(j, currentTree.NumLinages() + 1)
 j += 1


thank you,


Vincent Wan

 
--
PhD Candidate
Committee on the Conceptual and Historical Studies of Science University of
Chicago

PO Box 73727
Fairbanks, AK 99707

wan AT walrus DOT us (change CAPS to @ and . )

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

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] building non binary trees CLARIFIED

2005-11-17 Thread Vincent Wan
Let me try to clarify my problem.

I would like to have a tree data structure with trees whose nodes  
could have an arbitrary
number of descendants and that I could iterate over by the names of  
nodes

this is the first time I've used objects.

I tried to model my code on a binary tree data structure Roel  
Schroeven wrote in reply to an earlier post of mine

http://mail.python.org/pipermail/tutor/2005-November/043214.html

but I don't understand what's happening in his code on the line  
commented # what's happening here

 class Tree(object):
 class Node(object):
 def __init__(self, linage, left=None, right=None):
 self.linage = linage
 self.left = left
 self.right = right
 def __init__(self, rootlinage):
 self.rootnode = Tree.Node(rootlinage)
 self.linagetonode = {rootlinage: self.rootnode}  #  
what's happening here
 def AddBranch(self, linage, newlinage):
 node = self.linagetonode[linage]
 left = Tree.Node(linage)
 right = Tree.Node(newlinage)
 node.left = left
 node.right = right
 self.linagetonode[linage] = left
 self.linagetonode[newlinage] = right


my code seems to barf because when I call Tree's AddBranch method I'm  
not telling
it which node to add to. I don't know how to go from the name of a  
node (here a integer) to reference to
the node with that name to pass to AddBranch.

my code

import random

# constants that control the simulation
NUMBER_REPS = 10# run's the simulation
MAX_LINAGES = 10# number of species in each run
BRANCHING_PROBABILITY = 0.5

class Tree(object):
 numLinages = 0
 class Node(object):
 def __init__(self, name):
 self.name = name
 self.alive = True
 self.descendents = []
 Tree.numLinages += 1
 def __init__(self):
 self.rootnode = Tree.Node(0)
 def AddBranch(self, linage, offspring):
 new = Tree.Node(offspring)
 self.descendents.append(new)
 def NumLinages(  ):
 return Tree.numLinages
 NumLinages = staticmethod(NumLinages)

currentTree = Tree()
print Tree.NumLinages()

for i in range(NUMBER_REPS):
 j = 0
 while j <= currentTree.NumLinages():
 if random.random() >= BRANCHING_PROBABILITY:
 currentTree.AddBranch(j, currentTree.NumLinages() + 1)
 j += 1


Vincent Wan

 
--
PhD Candidate
Committee on the Conceptual and Historical Studies of Science
University of Chicago

PO Box 73727
Fairbanks, AK 99707

wan AT walrus DOT us (change CAPS to @ and . )

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


[Tutor] displaying properties/methods

2005-11-17 Thread Gregorius Gede Wiranarada
Hi all, i'm a newbie to python and now learning OOP. How do i display 
methods or properties that is owned by a class or a module? for example: i 
know that module sys has a property/method called path. i want to know what 
other methods it has, how do i find them from python command line?
thx. 

regards,
Gregor 

___
Dibuka pendaftaran Program Magister dan Double Degree Pascasarjana UAJY
(MM - MTF atau sebaliknya; M.Hum - MTF; M.Hum - MM; MTS. - MM).
Penerimaan mahasiswa setiap Mei, September dan Januari. 


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


Re: [Tutor] building nonbinary trees

2005-11-17 Thread Alan Gauld
> I'v got a start but I'm stuck because I don't understand how to call  
> a tree's nodes by name.

Every time you see call by name, think dictionary.

class Node:
 def __init__(self):
 self.children = {}
 def addChild(self,child,name):
 self.children[name] = child
 etc...

HTH,

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


Re: [Tutor] displaying properties/methods

2005-11-17 Thread Alan Gauld

> Hi all, i'm a newbie to python and now learning OOP. How do i display
> methods or properties that is owned by a class or a module? for example: i 
> know that module sys has a property/method called path. i want to know 
> what other methods it has, how do i find them from python command line?

Try:

import sys
dir(sys)
help(sys)

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] opts and try except

2005-11-17 Thread Danny Yoo


On Thu, 17 Nov 2005, Eric Walker wrote:

> I have a program now that works just like I want it. Now I want to
> integerate something to say print usage info when the user puts in the
> wrong number or type of options. Also print usage say if you type
> program name and -h or -H. I currently just have functions defined and
> at the bottom make a function call. Do I need to do like the def main():
> and then the if __name__ == "__main__"? I need an example of how to
> implement this.


Hi Eric,

Yes, there's a whole option-parsing system called 'optparse' that handles
option-parsing and the -h documentation generator:

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

The examples in the documentation there should help you get started.


If you have more questions, though, please feel free to ask.  Good luck!

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