[Tutor] printing value returning from a Class

2007-09-13 Thread Varsha Purohit
Hello friends,,
  I have a problem in displaying data  which i have invoked from
class. City is the name of the class which i havent displayed here. There is
another script using that class. It has a function name setCities which
takes a text file as argument. Text file contains name of the city, x and y
location. there are 4 datas in 4 different lines. Code is as follows.

import City

def setCities(inFile):
# puts city.txt content into City class objects
# the field order of input file is: name x y   x, y are integers. data
are in newlines.
f = open(inFile, 'r')
body = f.readlines()
f.close()
cities = []  # list of cities
for row in body:
cityData = row.strip().split()
cityName = cityData[0]
cityX = cityData[1]
cityY = cityData[2]
newCity = City(cityName, cityX, cityY)  # city class is invoked
cities.append(newCity)
return cities


abc = setCities(C:\MS\sem5\Lab2_scripts\cities.txt)  # setCities function
will return the array with values read from the file.
print abc

I am getting output like
[city.City instance at 0x023E82D8, city.City instance at 0x023E8300, 
city.City instance at 0x023E8350, city.City instance at 0x023E83C8]

I want the data and not the instance... what should i do ??


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


[Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread John
I've written a program which calculates areas of grid cells distributed over
the globe. It works fine with Python 2.5, however, when I run it with
2.4(the Enthon edition) I get the following error:

OverflowError: long int too large to convert to int

It occurs on this line:

 for ix in range(nx): area[ix,iy]=gridarea

I have no idea which int it's referring to? The values of ix/nx will not
exceed 360, iy will not exceed 180. Any suggestions on what to change for
the backward compatability?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] editTextFile.py

2007-09-13 Thread Kent Johnson
Christopher Spears wrote:
 I created a script that opens an existing text file,
 allows the user to write over the original contents,
 and then save the file.  The original contents are
 then saved in a separate file.  Here is the script:
 
 #!/usr/bin/python
 
 'editTextFile.py -- write over contents of existing
 text file'
 
 import os, string
 
 # get filename
 while True:
 fname = raw_input('Enter file name: ')
 if not (os.path.exists(fname)):
 print*** ERROR: '%s' doesn't exist % fname
 else:
 break
 
 # get file content (text) lines
 all = []
 print \nEnter lines ('.' by itself to quit).\n
 
 # loop until user terminates input
 while True:
 entry = raw_input(' ')
 if entry == '.':
 break
 else:
 all.append(entry)
 
 # write lines to file with NEWLINE line terminator
 print 1) Replace file's contents
 print Any other key quits function without replacing
 file's contents
 choice = raw_input(Make a choice: )
 
 if choice == '1':
 fobj = open(fname, 'r')
 fobj_lines = fobj.readlines()
 fobj.close()
 fobj = open(fname, 'w')

It would be safer to write the '_orig' file before opening the original 
file for writing (which erases its contents)
 
 fname_orig = fname + '_orig'
 fobj_orig = open(fname_orig, 'w')
 stripped_lines = []
 for line in fobj_lines:
   string.strip(line)

This doesn't change line. You need to assign the result back to line:
   line = string.strip(line)
or, better,
   line = line.strip()

Note that this will also strip leading and trailing whitespace from the 
lines so the copy will not be a duplicate of the original.

A simpler way to copy a file is to read the entire contents using 
fobj.read() and write them as a single string. Even easier is to use 
shutil.copyfile() which does this for you.

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


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread Kent Johnson
John wrote:
 I've written a program which calculates areas of grid cells distributed 
 over the globe. It works fine with Python 2.5, however, when I run it 
 with 2.4 (the Enthon edition) I get the following error:
 
 OverflowError: long int too large to convert to int
 
 It occurs on this line:
 
  for ix in range(nx): area[ix,iy]=gridarea   
 
 I have no idea which int it's referring to? The values of ix/nx will not 
 exceed 360, iy will not exceed 180. Any suggestions on what to change 
 for the backward compatability?

Are you sure nx is not large? The argument to range() must be an int. I 
would split the line in two so you know which part of it is generating 
the error, then insert a print statement to give you some more data.

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


Re: [Tutor] printing value returning from a Class

2007-09-13 Thread Kalle Svensson
Hello!

On 9/13/07, Varsha Purohit [EMAIL PROTECTED] wrote:
 Hello friends,,
   I have a problem in displaying data  which i have invoked from
 class. City is the name of the class which i havent displayed here. There is
 another script using that class. It has a function name setCities which
 takes a text file as argument. Text file contains name of the city, x and y
 location. there are 4 datas in 4 different lines. Code is as follows.

 import City

 def setCities(inFile):
 # puts city.txt content into City class objects
 # the field order of input file is: name x y   x, y are integers. data
 are in newlines.
 f = open(inFile, 'r')
 body = f.readlines()
 f.close()
 cities = []  # list of cities
 for row in body:
 cityData = row.strip().split()
 cityName = cityData[0]
 cityX = cityData[1]
 cityY = cityData[2]
 newCity = City(cityName, cityX, cityY)  # city class is invoked
 cities.append(newCity)
 return cities


 abc = setCities(C:\MS\sem5\Lab2_scripts\cities.txt)  #
 setCities function will return the array with values read from the file.
 print abc

 I am getting output like
 [city.City instance at 0x023E82D8, city.City instance at 0x023E8300,
 city.City instance at 0x023E8350, city.City instance at 0x023E83C8]

 I want the data and not the instance... what should i do ??

Well, that depends on the City class. When you print a list, it just
calls repr() on each item in the list and prints that. Now, suppose
there is a method printCity() in the City class for printing the city
data. In that case you should probably just loop over the list of
instances and call the method, like this:

 abc = setCities(city file)
 for city in abc:
... city.printCity()

If there is no such method, maybe you can extract the data from the
class and write your own printing function, or modify the class to add
one.

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


[Tutor] is this a vista issue

2007-09-13 Thread sacha rook
Hi 
 
when I run this code on a winxp box I get a nice list of url's
when I run this code on a win VISTA box I get this
 
 
print urlparse.urlparse(href)[1]TypeError: 'module' object is not callable
 
can a. someone tell me why  b. how do i get rid of this condition before I 
throw vista away :)
 
Many thanks in advance
 
S
 
 
[CODE]
 
from BeautifulSoup import BeautifulSoupdoc = ['htmlheadtitlePage 
title/title/head',   'bodyp id=firstpara align=centerThis is 
paragraph bone/b.',   'p id=secondpara align=blahThis is 
paragraph btwo/b.',   'a href=http://www.google.co.uk;/a',   
'a href=http://www.bbc.co.uk;/a',   'a 
href=http://www.amazon.co.uk;/a',   'a 
href=http://www.redhat.co.uk;/a',   '/html']soup = 
BeautifulSoup(''.join(doc))blist = soup.findAll('a')print blist
import urlparsefor a in blist:href = a['href']print 
urlparse.urlparse(href)[1]
 
 
[/CODE]
_
Get free emoticon packs and customisation from Windows Live. 
http://www.pimpmylive.co.uk___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is this a vista issue

2007-09-13 Thread Kent Johnson
sacha rook wrote:
 Hi
  
 when I run this code on a winxp box I get a nice list of url's
 when I run this code on a win VISTA box I get this
  
  
 print urlparse.urlparse(href)[1]
 TypeError: 'module' object is not callable

Please show the whole traceback.

Kent

  
 can a. someone tell me why  b. how do i get rid of this condition 
 before I throw vista away :)
  
 Many thanks in advance
  
 S
  
  
 [CODE]
  
 from BeautifulSoup import BeautifulSoup
 doc = ['htmlheadtitlePage title/title/head',
'bodyp id=firstpara align=centerThis is paragraph 
 bone/b.',
'p id=secondpara align=blahThis is paragraph btwo/b.',
'a href=http://www.google.co.uk;/a' 
 http://www.google.co.uk;/a',
'a href=http://www.bbc.co.uk;/a' http://www.bbc.co.uk;/a',
'a href=http://www.amazon.co.uk;/a' 
 http://www.amazon.co.uk;/a',
'a href=http://www.redhat.co.uk;/a' 
 http://www.redhat.co.uk;/a',   
'/html']
 soup = BeautifulSoup(''.join(doc))
 blist = soup.findAll('a')
 print blist
 import urlparse
 for a in blist:
 href = a['href']
 print urlparse.urlparse(href)[1]
  
  
 [/CODE]
 
 
 Are you the Quizmaster? Play BrainBattle with a friend now! 
 http://specials.uk.msn.com/brainbattle
 
 
 
 
 ___
 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] 2.5 to 2.4 problem with Int

2007-09-13 Thread John
The error occurs here:
area[ix,iy]=gridarea

The values of nx, ix, iy leading up to the error are:
360 0 0
360 1 0
360 2 0
360 3 0
360 4 0
360 ... ...
360 357 9
360 358 9
360 359 9
360 0 10
OverflowError: long int too large to convert to int

I guess then the problem occurs when iy goes from 9 to 10, but why?? It
wasn't a problem before and it's not a problem for ix???

Thanks!


On 9/13/07, Kent Johnson [EMAIL PROTECTED] wrote:

 John wrote:
  I've written a program which calculates areas of grid cells distributed
  over the globe. It works fine with Python 2.5, however, when I run it
  with 2.4 (the Enthon edition) I get the following error:
 
  OverflowError: long int too large to convert to int
 
  It occurs on this line:
 
   for ix in range(nx): area[ix,iy]=gridarea
 
  I have no idea which int it's referring to? The values of ix/nx will not
  exceed 360, iy will not exceed 180. Any suggestions on what to change
  for the backward compatability?

 Are you sure nx is not large? The argument to range() must be an int. I
 would split the line in two so you know which part of it is generating
 the error, then insert a print statement to give you some more data.

 Kent




-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread Kent Johnson
John wrote:
 The error occurs here:
 area[ix,iy]=gridarea

What is area? Is it a dict or something else? What is gridarea?

Please show more code and the complete traceback.

Kent
  
 The values of nx, ix, iy leading up to the error are:
 360 0 0
 360 1 0
 360 2 0
 360 3 0
 360 4 0
 360 ... ...
 360 357 9
 360 358 9
 360 359 9
 360 0 10
 OverflowError: long int too large to convert to int
 
 I guess then the problem occurs when iy goes from 9 to 10, but why?? It 
 wasn't a problem before and it's not a problem for ix???
  
 Thanks!

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


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread John
In all it's glory: I'm just a bit embarrassed because I'm sure it's poor
coding:



def gridarea(H):
  returns an array of area corresponding to each nx,ny,nz
 %===
 %
 %---
 % input
 %   - H  : Header dict object with nx, ny, nz
 %
 % output
 %   - Numpy array area corresponding to nx,ny,nz
 %---
 %
 %---
 % last changes: ww, 2007
 %===
 
 import math
 import numpy as N

 pih=math.pi/180.
 r_earth=6.371e6
 cosfunc = lambda y : math.cos(y*pih)*r_earth
 nz=H['nz']
 nx=H['nx']
 ny=H['ny']
 outlat0=H['outlat0']
 dyout=H['dyout']
 dxout=H['dxout']
 area=N.zeros((nx,ny)) #creates numpy array

 for iy in range(ny):
  ylata=outlat0+(float(iy)+0.5)*dyout
  ylatp=ylata+0.5*dyout
  ylatm=ylata-0.5*dyout
  if (ylatm0 and ylatp0): hzone=dyout*r_earth*pih
  else:
   cosfact=cosfunc(ylata)
   cosfactp=cosfunc(ylatp)
   cosfactm=cosfunc(ylatm)
   if cosfactpcosfactm: hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt
(r_earth**2-cosfactm**2)
   else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt
(r_earth**2-cosfactp**2)

  gridarea=2.*math.pi*r_earth*hzone*dxout/360.
  for ix in range(nx):
   print nx, ix, iy
   area[ix,iy]=gridarea

 return area #returns numpy array of area



Here's the traceback:

...

360 357 9
360 358 9
360 359 9
360 0 10
OverflowError: long int too large to convert to int
Traceback:
  File string, line 1, in ?
  File c:\07\Programming\Python\mod_fp\getfp.py, line 11, in ?
H,fail=readheader(pathname,1,0)
  File c:\07\Programming\Python\mod_fp\mod_fp.py, line 170, in readheader
H['area'] = gridarea(H)
  File c:\07\Programming\Python\mod_fp\mod_fp.py, line 332, in gridarea
area[ix,iy]=gridarea
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Class Inheritance

2007-09-13 Thread Lamonte Harris
Okay

class A:
   def __init__(self,x,y):
 self.x = x
 self.y = y

   def save(self,fn):
 f = open(fn,w)
 f.write(str(self.x)+ '\n') # convert to a string and add newline
 f.write(str(self.y)+'\n')
 return f # for child objects to use

   def restore(self, fn):
 f = open(fn)
 self.x = int(f.readline()) # convert back to original type
 self.y = int(f.readline())
 return f

class B(A):
   def __init__(self,x,y,z):
 A.__init__(self,x,y)
 self.z = z

   def save(self,fn):
 f = A.save(self,fn)  # call parent save
 f.write(str(self.z)+'\n')
 return f # in case further children exist

   def restore(self, fn):
 f = A.restore(self,fn)
 self.z = int(f.readline())
 return f

In the class B,  I'm not understanding the A.__init(self,x,y) part.  So its
initializing the class A, and basically you can use the A class like normal?
Part im confused about is the self.z, does that belong to the class A or
class B?  Else I think I'm understanding it correctly.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread Kent Johnson
I have no clue; anyone else?

Maybe you should try the numpy list.

Kent

John wrote:
 for the record:
 nx=360
 ny=180
 nz=1
 
  
 On 9/13/07, *John* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote:
 
 
 In all it's glory: I'm just a bit embarrassed because I'm sure it's
 poor coding:
  
  
 
 def gridarea(H):
   returns an array of area corresponding to each nx,ny,nz
  %===
  %
  %---
  % input
  %   - H  : Header dict object with nx, ny, nz
  %
  % output
  %   - Numpy array area corresponding to nx,ny,nz
  %---
  % 
  %---
  % last changes: ww, 2007
  %===
  
  import math
  import numpy as N
  
  pih=math.pi/180.
  r_earth=6.371e6
  cosfunc = lambda y : math.cos(y*pih)*r_earth
  nz=H['nz']
  nx=H['nx']
  ny=H['ny']
  outlat0=H['outlat0']
  dyout=H['dyout']
  dxout=H['dxout']
  area=N.zeros((nx,ny)) #creates numpy array
  
  for iy in range(ny):
   ylata=outlat0+(float(iy)+0.5)*dyout
   ylatp=ylata+0.5*dyout
   ylatm=ylata-0.5*dyout
   if (ylatm0 and ylatp0): hzone=dyout*r_earth*pih
   else:
cosfact=cosfunc(ylata)
cosfactp=cosfunc(ylatp)
cosfactm=cosfunc(ylatm)
if cosfactpcosfactm:
 hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt(r_earth**2-cosfactm**2)
else:
 hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2)
 
 
   gridarea=2.*math.pi*r_earth*hzone*dxout/360.
   for ix in range(nx):
print nx, ix, iy
area[ix,iy]=gridarea 
  
  return area #returns numpy array of area
 
  
 
 Here's the traceback:
 
 ...
 
 360 357 9
 360 358 9
 360 359 9
 360 0 10
 OverflowError: long int too large to convert to int
 Traceback:
   File string, line 1, in ?
   File c:\07\Programming\Python\mod_fp\getfp.py, line 11, in ?
 H,fail=readheader(pathname,1,0)
   File c:\07\Programming\Python\mod_fp\mod_fp.py, line 170, in
 readheader
 H['area'] = gridarea(H)
   File c:\07\Programming\Python\mod_fp\mod_fp.py, line 332, in
 gridarea
 area[ix,iy]=gridarea
 
 
 
 
 -- 
 Configuration
 ``
 Plone 2.5.3-final,
 CMF-1.6.4,
 Zope (Zope 2.9.7-final, python 2.4.4, linux2),
 Five 1.4.1,
 Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 
 4.1.1-51)],
 PIL 1.1.6

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


Re: [Tutor] Class Inheritance

2007-09-13 Thread Eric Brunson
Lamonte Harris wrote:
 Okay

 class A:
def __init__(self,x,y):
  self.x = x
  self.y = y

def save(self,fn):
  f = open(fn,w)
  f.write(str(self.x)+ '\n') 
 # convert to a string and add newline
  f.write(str(self.y)+'\n')
  return f # for child objects to use

def restore(self, fn):
  f = open(fn)

  self.x = int(f.readline()) # convert back to original type
  self.y = int(f.readline())
  return f
  
 class B(A):
def __init__(self,x,y,z):
  A.__init__(self,x,y)

  self.z = z

def save(self,fn):
  f = A.save(self,fn)  # call parent save
  f.write(str(self.z)+'\n')
  return f # in case further children exist


def restore(self, fn):
  f = A.restore(self,fn)
  self.z = int(f.readline())
  return f
 In the class B,  I'm not understanding the A.__init(self,x,y) part.  
 So its initializing the class A, and basically you can use the A class 
 like normal?

Essentially, yes, but the way you've worded it is imprecise.  Any 
instance of B is a subclass of A, essentially an A:  Every boy is a 
male, but not all males are boys.  When you override a method in a 
subclass you have essentially turned off all behavior in the parent 
method, including magic methods like the constructor.  You have to 
call the parent constructor explicitly to get its benefits.

A method of an instance can be called like this:  instance.method() and 
python makes sure that a pointer to the instance is passed in as the 
first argument, generally self.  But a method of a class can be called 
without instantiating the class, but you have to supply self on you own.

The method you are using is valid,  yet depricated.  Using new style 
classes (which aren't actually that new) you'd write your code like this:

class A(object):
def __init__(self, a):
self.aye = a

class B(A):
def __init__(self, a, b):
self.bee = b
super( B, self ).__init__( a )

Notice that you don't have to supply self.

You can use any method of A in an instance of B that you haven't 
overridden in B without having to use super().

 Part im confused about is the self.z, does that belong to the class A 
 or class B?  

z is an attribute B only.

Hope that helps,
e.

 Else I think I'm understanding it correctly.
 

 ___
 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] evaluating AND

2007-09-13 Thread Orest Kozyar
Given a variable x that can either be None or a tuple of two floats [i.e.
(0.32, 4.2)], which syntax is considered most appropriate under Python
coding standards?

if x and x[0]  0:
pass

=OR=

if x:
if x[0]  0:
pass


In the first, I'm obviously making the assumption that if the first
condition evaluates to false, then the second condition won't be evaluated.
But, is this a good/valid assumption to make?  Is there a more appropriate
design pattern in Python?

Thanks!
Orest

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


Re: [Tutor] evaluating AND

2007-09-13 Thread Eric Brunson

The first is how I would code it.  Python guarantees that compound 
boolean statements are processed from left to right and also that the 
AND operator will short circuit the rest of the evaluation, since the 
rest of the line cannot change the falseness of the entire statement.

Orest Kozyar wrote:
 Given a variable x that can either be None or a tuple of two floats [i.e.
 (0.32, 4.2)], which syntax is considered most appropriate under Python
 coding standards?

 if x and x[0]  0:
   pass

 =OR=

 if x:
   if x[0]  0:
   pass


 In the first, I'm obviously making the assumption that if the first
 condition evaluates to false, then the second condition won't be evaluated.
 But, is this a good/valid assumption to make?  Is there a more appropriate
 design pattern in Python?

 Thanks!
 Orest

 ___
 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] evaluating AND

2007-09-13 Thread Terry Carroll
On Thu, 13 Sep 2007, Orest Kozyar wrote:

 Given a variable x that can either be None or a tuple of two floats [i.e.
 (0.32, 4.2)], which syntax is considered most appropriate under Python
 coding standards?
 
 if x and x[0]  0:
   pass
 
 =OR=
 
 if x:
   if x[0]  0:
   pass

I would like either one if instead of if x you used if x is not None; 
that seems a lot easier to me to read.  It's a bit jarring to see the same 
variable used in one expression as both a boolean and a list/tuple.

Besides, suppose somehow x got set to zero.  It would pass without error, 
something you wouldn't want to have happen.  Even if you've set things up 
so that it couldn't happen, it's not obvious from looking at this code 
that it couldn't happen.

If you really want to test for x being non-None, test for x being 
non-None.

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


[Tutor] Killing an instance

2007-09-13 Thread Ara Kooser
   I have two instances called and running. They interact with each
other and I would like one of the instances to cease to exist in the
second round based on a given condition. How do you kill an instance?

   The code is below. I have Red and Yellow as my instances and I want
them to die when life = 0 and not show up in the preceding rounds of
the game.

Thank you.
Ara




CODE HERE:
##
#Red and Yellow yeast model
#
#Both yeast start out cooperating.
#If the yeast detect that there is no ade or lys present they will defect
#but die.
##

import time

chemicals = []

#0 cooperates
#1 defects

class RedYeast:
#Needs adenine to grow, releases lysine
def __init__(self,name,group):
self.name = name
self.group = group
self.life = 1
self.hate_tolerance = 0
self.choice = 0

#METHODS
def lys_re(self,stuffa):
#release of lys in the environment
if self.choice == 0:
print self.name, -- Releasing lys
chemicals.append(stuffa)
elif self.choice == 1:
print self.name, -- Withholds lys

def ade_need(self,stuffb):

if stuffb != chemicals:
print self.name,is taking ade
self.life = self.life+1
chemicals.remove(stuffb)
print chemicals
print Life, self.life
else:
print No ade presents
self.life = self.life-1
self.choice = 1



class YellowYeast:
#Needs lysine to grow, releases adenine
def __init__(self,name,group):
self.name = name
self.group = group
self.life = 1
self.hate_tolerance = 0
self.choice = 0

#METHODS
def ade_re(self,stuffa):
#release of lys in the environment
if self.choice == 0:
print self.name, -- Releasing ade
chemicals.append(stuffa)
elif self.choice == 1:
print self.name, -- Withholds ade

def lys_need(self,stuffb):

if stuffb != chemicals:
print self.name, is taking ade
self.life = self.life+1
chemicals.remove(stuffb)
print chemicals

print Life,self.life
print
else:
print No ade presents
self.life = self.life-1
self.choice = 1


def death(self):



##
#Start of program
##

rounds = raw_input(How many rounds to you wish to play through?)
print Starting environment, chemicals
rounds =int(rounds)
count = 0

#Creates the instances for RedYeast and YellowYeast
one = RedYeast(Red,alpha)
two = YellowYeast(Yellow,alpha)

#Game logic

while count  rounds:
print ##
print

one.lys_re(lys)
two.ade_re(ade)

print
print Chemicals in the environment,chemicals
print

time.sleep(1)

one.ade_need(ade)
two.lys_need(lys)

print ##
print


count = count+1

print Ending environment, chemicals

-- 
Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis
an sub cardine glacialis ursae.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] evaluating AND

2007-09-13 Thread Kent Johnson
Orest Kozyar wrote:
 Given a variable x that can either be None or a tuple of two floats [i.e.
 (0.32, 4.2)], which syntax is considered most appropriate under Python
 coding standards?
 
 if x and x[0]  0:
   pass
 
 =OR=
 
 if x:
   if x[0]  0:
   pass

The first is fine.

 In the first, I'm obviously making the assumption that if the first
 condition evaluates to false, then the second condition won't be evaluated.
 But, is this a good/valid assumption to make?

Yes, this is guaranteed by the language.
http://docs.python.org/ref/Booleans.html

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


Re: [Tutor] evaluating AND

2007-09-13 Thread Adam Bark
On 13/09/2007, Terry Carroll [EMAIL PROTECTED] wrote:

 On Thu, 13 Sep 2007, Orest Kozyar wrote:

  Given a variable x that can either be None or a tuple of two floats [i.e
 .
  (0.32, 4.2)], which syntax is considered most appropriate under Python
  coding standards?
 
  if x and x[0]  0:
pass
 
  =OR=
 
  if x:
if x[0]  0:
pass

 I would like either one if instead of if x you used if x is not None;
 that seems a lot easier to me to read.  It's a bit jarring to see the same
 variable used in one expression as both a boolean and a list/tuple.

 Besides, suppose somehow x got set to zero.  It would pass without error,
 something you wouldn't want to have happen.  Even if you've set things up
 so that it couldn't happen, it's not obvious from looking at this code
 that it couldn't happen.

 If you really want to test for x being non-None, test for x being
 non-None.


The problem is what if it's an empty list or tuple? It would pass but have
not value
whereas if x would work fine.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] evaluating AND

2007-09-13 Thread Terry Carroll
On Thu, 13 Sep 2007, Adam Bark wrote:

 The problem is what if it's an empty list or tuple? It would pass but have
 not value
 whereas if x would work fine.

Exactly.  The poster stated that x is supposed to be either None or a 
tuple of two floats.

Just to put a bit of meat on the example, let's create a function whose 
job is to return x[1]/x[0], but only if x[0]  0.  Otherwise, it just 
falls off, i.e., returning None.

Here are two versions, one using if x is None; the other using just 
if x

 def test01(x):
...  if x is not None:
...   if x[0]0:
...return x[1]/x[0]
...
 def test02(x):
...  if x:
...   if x[0]0:
...return x[1]/x[0]


When x is None, both work:

 x = None
 print test01(x)
None
 print test02(x)
None

When x is, in fact, a tuple of two floats, both work:

 x = (2.0, 5.0)
 print test01(x)
2.5
 print test02(x)
2.5

Now... if x is an empty tuple:

 x = tuple()
 print test01(x)
Traceback (most recent call last):
  File stdin, line 1, in module
  File stdin, line 3, in test01
IndexError: tuple index out of range
 print test02(x)
None


The first one, which checks if x is None fails.  This is a good thing.  

The second one, which just checks if x and is satisfied with any false
value, including an empty tuple, does not raise the error condition, even
though the data is bad.  This is a bad thing.



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


Re: [Tutor] Suggested books for Agile Programming Testing

2007-09-13 Thread Alan Gauld

Shannon -jj Behrens [EMAIL PROTECTED] 
wrote

 Also, can anyone comment on the limits or caveats of agile 
 development?

I posted a longish response on this but it seems not to have made to
gmane! Here it is again:

===
Stephen McInerney
[EMAIL PROTECTED] wrote

 Can anyone recommend me the best single must-read book for Agile
 Programming?

One of the most widely cited is Robert Martin's Agile Software
Development. Personally I didn't like it much for agile but it is
quite good on OOD.

The original XP book by Kent Beck is good too, along with its sequel.

 Also Agile Testing.

Sorry I can't comment on any specific testing books.

 (If they compare Agile in general to the other methodologies,
 that would be great)

The best comparison book I can recommend is

Balancing Agility  Discipline by Barry Boehm.

 Also, can anyone comment on the limits or caveats of agile
 development?

I'm sure lots of people can but Agile is such a nebulous concept that
its difficult to get anything objective or useful. My own personal
experieces follow for what they are wrth:

Agile works well if:
1) You have very close contact with end users/requirement owners
2) Small, co-located teams - small = 20 or less people
3) The requirements are not clearly understood (even by the users).
4) You have an experienced, talented team

You need *all* of those to make it work significantly better than
traditional methods. If even one if missing you will be no better off.
You might not be any worse off, but you will be no better. If you have
only one of those items then traditional methods (NOT waterfall!)
will be better.

Dangers of agile:
1) Not good for building scaleable, resilient, long term flexible
structures
2) Very expensive due to the large proportion of time spent in
rework (aka refactoring)
3) Tendency to drift over budget as new featiures get thought up
and added to the original scope.
4) Not good for long term maintenance, the documentation
often being inadeqate for anyone outside of the original
project team

Note, All of these things can be addressed but it takes
specific, directed action to do so.

Some general comments:
1) Its easy for management to embrace agile by adopting
some bits that they like. Requirements become User Stories,
Progress meetings become Stand-Ups, Phased releases
become iterations. in fact its just a renaming exercise not
real Agile. Re-naming doesn't work, agile does (with the
caveats above)

2) Agile is very open to hype. Exaggerated claims and comparisons
with the waterfall method are common, even though the waterfall
method has not been widely used for years and methods like RUP
are more appropriate comparisons. If you compare a motorcycle to
a penny farthing cycle you will get an exaggerated idea of progress

3) Agile badly done is just as bad as traditional badly done.

4) finally, do you need to hire an architect to build a garden shed?

Agile is in some ways addressing an artificial problem. Software
engineeering was invented in the late 70's to deal with very large
projects. Most methodologies still tackle that problem. Many
software houses now work on much smaller problems that
only need small teams and can be completed in a few weeks.
If you apply traditional methodologies to those problems they
will be overkill. So Agile comes along. But on these very small
projects, usually all that's needed is some common sense and
experience - like building a garden shed!

My personal career jhas been based on large projects. On most
large projects there is a tools team who churn out little programs
used by the main development/test teams. The tools team
does not typically apply the main project methodology for
each tool written, they just get on with it. The tools team
will typically be 4-10 people. A tool will typically take 1-20 days
to write. In other words the small end of Agile, but they don't
use Agile, they don't use anything but common sense and
their experiece...

That's way more than I intended writing! I'm sure others will have
different views.

HTH,

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


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


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread Alan Gauld

John [EMAIL PROTECTED] wrote


 In all it's glory: I'm just a bit embarrassed because I'm sure it's 
 poor
 coding:


Thats what we're here for...

The first thing to note is that gridarea is here a function object.
So are you assigning the function  object  to area[x,y].
Is that what you intend?

 def gridarea(H):
  returns an array of area corresponding to each nx,ny,nz
 % input
 %   - H  : Header dict object with nx, ny, nz
 % output
 %   - Numpy array area corresponding to nx,ny,nz
 
 import math
 import numpy as N

It's traditional to put the imports outside the function, especially
if they will always be called.

 pih=math.pi/180.
 r_earth=6.371e6
 cosfunc = lambda y : math.cos(y*pih)*r_earth

You could use the more conventional

def cosfunc(y): return math.cos(y*pih)*r_earth


lambda is fine by me but some folks find them harder to read.


 nz=H['nz']
 nx=H['nx']
 ny=H['ny']
 outlat0=H['outlat0']
 dyout=H['dyout']
 dxout=H['dxout']
 area=N.zeros((nx,ny)) #creates numpy array

 for iy in range(ny):
   ylata=outlat0+(float(iy)+0.5)*dyout
   ylatp=ylata+0.5*dyout
   ylatm=ylata-0.5*dyout
   if (ylatm0 and ylatp0): hzone=dyout*r_earth*pih
   else:
 cosfact=cosfunc(ylata)
 cosfactp=cosfunc(ylatp)
 cosfactm=cosfunc(ylatm)
 if cosfactp  cosfactm: 
 hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt
(r_earth**2-cosfactm**2)
   else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt
 (r_earth**2-cosfactp**2)


More whitespace will help readability and avoid errors! please...

  gridarea=2.*math.pi*r_earth*hzone*dxout/360.

This is a bit iffy since you are creating a variable gridarea inside
a function gridarea. That effectively removes the possibility of
using recursion, although otherwise I don't *think* it should
cause a problem in itself.

  for ix in range(nx):
   print nx, ix, iy
   area[ix,iy]=gridarea

And here looks like we have the dodgy line because you are
assigning the internal variable not the function after all. So
gridarea is actually the result of that big calculation.

That is a float value and potentially big, I don't know.
Did you try printing the value of gridarea in your debug trace?
But that shouldn't cause the error since you aren't trying
to convert it to an int.

Very odd.

iy is set in the loop up to ny.  But how does it
compare to the original ny parameter you passed to
N.zeros at the top? Is this a numpy index error we
are actually seeing? I don't know how numpy's zeros
function works... I'm clutching at straws here...

 return area #returns numpy array of area

 Here's the traceback:

 ...

 360 357 9
 360 358 9
 360 359 9
 360 0 10

So this is where we loop all the way back to
the outer loop and then start the second loop again..
Can you add gridarea and ny to the debug data?

 OverflowError: long int too large to convert to int
 Traceback:
  File string, line 1, in ?
  File c:\07\Programming\Python\mod_fp\getfp.py, line 11, in ?
H,fail=readheader(pathname,1,0)
  File c:\07\Programming\Python\mod_fp\mod_fp.py, line 170, in 
 readheader
H['area'] = gridarea(H)
  File c:\07\Programming\Python\mod_fp\mod_fp.py, line 332, in 
 gridarea
area[ix,iy]=gridarea

Personally I'd change gridarea() to take the individiual parameters
rather than the dictionary. There is a shortcut way of doing that
using **kwords which means you canb pass the dictionary but
the unpacking will be done for you by Python...

But most of my comments are stylistic, I have no real idea whats going
wrong here. Sorry.


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


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


Re: [Tutor] Killing an instance

2007-09-13 Thread Alan Gauld
Ara Kooser [EMAIL PROTECTED] wrote

   I have two instances called and running. They interact with each
 other and I would like one of the instances to cease to exist in the
 second round based on a given condition. How do you kill an 
 instance?

Either set the variable to something else or explicitly with del()

class C: pass

c = C()  # create a C instance

c = 42   # the C instance gets garbage collected

or

c -= C()  # another instance

del(c)   # delete it.

HTH,


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


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


Re: [Tutor] Killing an instance

2007-09-13 Thread Alan Gauld

Ara Kooser [EMAIL PROTECTED] wrote

   The code is below. I have Red and Yellow as my instances and I 
 want
 them to die when life = 0 and not show up in the preceding rounds of
 the game.

I'm not sure I understand this last bit. Won't they already have shown
up in the preceding bits of the game. Setting to zero won't affect the
preceding rounds unless you only display all of the rounds at the end
and keep the records in memory. In which case you could go back
and retrospectively change the earlier displays. It sounds a bit odd 
tho'
can you elaborate?

Alan G. 


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


[Tutor] deleting one line in multiple files

2007-09-13 Thread bhaaluu
Greetings,
I'm running Python 2.4.3 on a GNU/Linux box.

This question is about using 'fileinput.'

I have a directory of files, and I've created a file list
of the files I want to work on:

$ ls  file.list

Each file in file.list needs to have a line removed,
leaving the rest of the file intact.

I found this snippet on the Net, and it works fine for one file:

# the lines with 'script type' are deleted.
import fileinput

for line in fileinput.input(file0001.html, inplace=1):
line = line.strip()
if not 'script type'in line:
print line

The docs say:
This iterates over the lines of all files listed in sys.argv[1:]...
I'm not sure how to implement the argv stuff.

However, the documentation also states:
To specify an alternative list of filenames,
pass it as the first argument to input().
A single file name is also allowed.

So, when I replace file0001.html with file.list (the alternative list
of filenames, nothing happens.

# the lines with 'script type' are deleted.
import fileinput

for line in fileinput.input(file.list, inplace=1):
line = line.strip()
if not 'script type'in line:
print line

file.list has one filename on each line, ending with a newline.
file0001.html
file0002.html
:::
:::
file0175.html

Have I interpreted the documentation wrong?
The goal is to delete the line that has 'script type' in it.
I can supply more information if needed.
TIA.
-- 
bhaaluu at gmail dot com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] deleting one line in multiple files

2007-09-13 Thread wormwood_3
I think the problem is that the original script you borrowed looks at the file 
passed to input, and iterates over the lines in that file, removing them if 
they match your pattern. What you actually want to be doing is iterating over 
the lines of your list file, and for each line (which represents a file), you 
want to open *that* file, do the check for your pattern, and delete 
appropriately.

Hope I am not completely off:-)

If I am right so far, you want to do something like:

import fileinput

for file in fileinput.input(filelist.list, inplace=1):
curfile = file.open()
for line in curfile:
line = line.strip()
if not 'script type'in line:
print line

BUT, fileinput was made (if I understand the documentation) to avoid having to 
do this. This is where the sys.argv[1:] values come in. The example on this 
page (look under Processing Each Line of One or More Files:
The fileinput Module) helped clarify it to me: 
http://www.oreilly.com/catalog/lpython/chapter/ch09.html. If you do:

% python myscript.py script type `ls`
This should pass in all the items in the folder you run this in (be sure it 
only contains the files you want to edit!), looking for script type. 
Continuing with the O'Reilly example:

import fileinput, sys, string
# take the first argument out of sys.argv and assign it to searchterm
searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:]
for line in fileinput.input():
   num_matches = string.count(line, searchterm)
   if num_matches: # a nonzero count means there was a match
   print found '%s' %d times in %s on line %d. % (searchterm, 
num_matches, 
   fileinput.filename(), fileinput.filelineno())

To test this, I put the above code block in mygrep.py, then made a file 
test.txt in the same folder, with some trash lines, and 1 line with the 
string you said you want to match on. Then I did:

[EMAIL PROTECTED]:~$ python mygrep.py script type test.txt 
found 'script type' 1 times in test.txt on line 3.

So you could use the above block, and edit the print line to also edit the file 
as you want, maybe leaving the print to confirm it did what you expect.

Hope this helps!
-Sam

_
I have a directory of files, and I've created a file list
of the files I want to work on:

$ ls  file.list

Each file in file.list needs to have a line removed,
leaving the rest of the file intact.

I found this snippet on the Net, and it works fine for one file:

# the lines with 'script type' are deleted.
import fileinput

for line in fileinput.input(file0001.html, inplace=1):
line = line.strip()
if not 'script type'in line:
print line

The docs say:
This iterates over the lines of all files listed in sys.argv[1:]...
I'm not sure how to implement the argv stuff.

However, the documentation also states:
To specify an alternative list of filenames,
pass it as the first argument to input().
A single file name is also allowed.

So, when I replace file0001.html with file.list (the alternative list
of filenames, nothing happens.

# the lines with 'script type' are deleted.
import fileinput

for line in fileinput.input(file.list, inplace=1):
line = line.strip()
if not 'script type'in line:
print line

file.list has one filename on each line, ending with a newline.
file0001.html
file0002.html
:::
:::
file0175.html

Have I interpreted the documentation wrong?
The goal is to delete the line that has 'script type' in it.
I can supply more information if needed.
TIA.
-- 
bhaaluu at gmail dot 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


[Tutor] How can I extend my vocabulary that fits well with python.

2007-09-13 Thread Lamonte Harris
See theres a lot of words that I know and some that I don't know, how can I
extend and improve my python vocabulary so I can interpret information in a
faster manor.  Makes things easier to understand if you actually understand
the things the people are saying in tutorials,etc..
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] evaluating AND

2007-09-13 Thread Rikard Bosnjakovic
On 14/09/2007, Terry Carroll [EMAIL PROTECTED] wrote:

 The second one, which just checks if x and is satisfied with any false
 value, including an empty tuple, does not raise the error condition, even
 though the data is bad.  This is a bad thing.

For me, if x would be enough. If you think it's a bad thing when x
is of the wrong data, then you really should check that it contains
*correct* data as well.

Using the the two function of yours, setting x to an integer:

 x = 2
 print test01(x)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/tmp/python-3716vZq, line 3, in test01
TypeError: unsubscriptable object
 print test02(x)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/tmp/python-3716vZq, line 8, in test02
TypeError: unsubscriptable object


Rewriting your test01-function into this:

def test01(x):
 if (type(x) == type((0,)) and
 (x is not None) and
 (length(x) == 2)):
  if x[0]0:
   return x[1]/x[0]

and testing again:

 x = 2
 print test01(x)
None


My point is that if you think it's bad for a function to receive
incorrect data you should do exhaustive checks for the input to make
sure it is of correct type, size and whatever the requirements might
be, not just check if it's a tuple or not.

-- 
- Rikard - http://bos.hack.org/cv/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is this a vista issue

2007-09-13 Thread Rikard Bosnjakovic
On 13/09/2007, sacha rook [EMAIL PROTECTED] wrote:

  [CODE]

  from BeautifulSoup import BeautifulSoup
 doc = ['htmlheadtitlePage title/title/head',
'bodyp id=firstpara align=centerThis is paragraph
 bone/b.',
'p id=secondpara align=blahThis is paragraph btwo/b.',
'a href=http://www.google.co.uk;/a',
'a href=http://www.bbc.co.uk;/a',
'a href=http://www.amazon.co.uk;/a',
'a href=http://www.redhat.co.uk;/a',
'/html']
 soup = BeautifulSoup(''.join(doc))
 blist = soup.findAll('a')
 print blist
  import urlparse
 for a in blist:
 href = a['href']
 print urlparse.urlparse(href)[1]

  [/CODE]

Works fine for me:

 ## working on region in file python-tmp-371673F...
[a href=http://www.google.co.uk;/a, a
href=http://www.bbc.co.uk;/a, a
href=http://www.amazon.co.uk;/a, a
href=http://www.redhat.co.uk;/a]
www.google.co.uk
www.bbc.co.uk
www.amazon.co.uk
www.redhat.co.uk

But as Kent wrote; show the whole traceback, not just the last line.


-- 
- Rikard - http://bos.hack.org/cv/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] evaluating AND

2007-09-13 Thread John Fouhy
On 14/09/2007, Rikard Bosnjakovic [EMAIL PROTECTED] wrote:
 On 14/09/2007, Terry Carroll [EMAIL PROTECTED] wrote:
  The second one, which just checks if x and is satisfied with any false
  value, including an empty tuple, does not raise the error condition, even
  though the data is bad.  This is a bad thing.
 My point is that if you think it's bad for a function to receive
 incorrect data you should do exhaustive checks for the input to make
 sure it is of correct type, size and whatever the requirements might
 be, not just check if it's a tuple or not.

I think Terry's viewpoint is that a function should raise an exception
if it receives bad data.  You don't need to do exhaustive
isinstance()/type() tests; just use the data as if it is what you're
expecting and let errors happen if the data is wrong.

What's important is that the function should not return valid output
when given invalid input.  That's what could happen with Terry's
hypothetical test02() if you give it an empty list.

OTOH, if you give either function an integer, both will raise
exceptions, which is fine.

You could change the function like this, though, to ensure the list
length is correct:

 def test01(x):
...  if x is not None:
...   assert len(x)==2
...   if x[0]0:
...return x[1]/x[0]
...

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


Re: [Tutor] deleting one line in multiple files

2007-09-13 Thread wormwood_3
Thought I would do some more testing and get you a more finalized form this 
time.

So I took the mygrep.py script, and put it in a folder with 3 test files with 
content like this:
I am some
lines of text
yep I love text
435345
345345345
script type=text/javascript /

Then I ran:

[EMAIL PROTECTED]:~/test$ python mygrep.py script type `ls`
found 'script type' 1 times in test1.txt on line 6.
found 'script type' 1 times in test2.txt on line 6.
found 'script type' 1 times in test3.txt on line 6.

This will work in your case quite well I think. Now for doing the actual 
delete... I could not find a way to succinctly delete a single line from the 
files in Python, but I am almost there. Sorry, it was late:-) 

import fileinput, sys, string
# take the first argument out of sys.argv and assign it to searchterm
searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:]
for line in fileinput.input():
   num_matches = string.count(line, searchterm)
   if num_matches: # a nonzero count means there was a match
   print found '%s' %d times in %s on line %d. % (searchterm, num_matches,
   fileinput.filename(), fileinput.filelineno())
   thisfile = open(fileinput.filename(), r)
   linelist = thisfile.readlines()
   del linelist[(fileinput.filelineno() -1)]
   print linelist
   thisfile.close()
   print Deleted %s line(s) containing pattern in %s % (num_matches, 
fileinput.filename())

So this will do the search on the file you specify at runtime, look for the 
pattern you specify, and print out a list of the lines with the matching line 
removed. Now I need to write these lines back to the original file. Don't have 
that part yet...:-(

-Sam
___
- Original Message 
From: wormwood_3 [EMAIL PROTECTED]
To: Python Tutorlist tutor@python.org
Sent: Thursday, September 13, 2007 11:33:48 PM
Subject: [Tutor]  deleting one line in multiple files

I think the problem is that the original script you borrowed looks at the file 
passed to input, and iterates over the lines in that file, removing them if 
they match your pattern. What you actually want to be doing is iterating over 
the lines of your list file, and for each line (which represents a file), you 
want to open *that* file, do the check for your pattern, and delete 
appropriately.

Hope I am not completely off:-)

If I am right so far, you want to do something like:

import fileinput

for file in fileinput.input(filelist.list, inplace=1):
curfile = file.open()
for line in curfile:
line = line.strip()
if not 'script type'in line:
print line

BUT, fileinput was made (if I understand the documentation) to avoid having to 
do this. This is where the sys.argv[1:] values come in. The example on this 
page (look under Processing Each Line of One or More Files:
The fileinput Module) helped clarify it to me: 
http://www.oreilly.com/catalog/lpython/chapter/ch09.html. If you do:

% python myscript.py script type `ls`
This should pass in all the items in the folder you run this in (be sure it 
only contains the files you want to edit!), looking for script type. 
Continuing with the O'Reilly example:

import fileinput, sys, string
# take the first argument out of sys.argv and assign it to searchterm
searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:]
for line in fileinput.input():
   num_matches = string.count(line, searchterm)
   if num_matches: # a nonzero count means there was a match
   print found '%s' %d times in %s on line %d. % (searchterm, 
num_matches, 
   fileinput.filename(), fileinput.filelineno())

To test this, I put the above code block in mygrep.py, then made a file 
test.txt in the same folder, with some trash lines, and 1 line with the 
string you said you want to match on. Then I did:

[EMAIL PROTECTED]:~$ python mygrep.py script type test.txt 
found 'script type' 1 times in test.txt on line 3.

So you could use the above block, and edit the print line to also edit the file 
as you want, maybe leaving the print to confirm it did what you expect.

Hope this helps!
-Sam

_
I have a directory of files, and I've created a file list
of the files I want to work on:

$ ls  file.list

Each file in file.list needs to have a line removed,
leaving the rest of the file intact.

I found this snippet on the Net, and it works fine for one file:

# the lines with 'script type' are deleted.
import fileinput

for line in fileinput.input(file0001.html, inplace=1):
line = line.strip()
if not 'script type'in line:
print line

The docs say:
This iterates over the lines of all files listed in sys.argv[1:]...
I'm not sure how to implement the argv stuff.

However, the documentation also states:
To specify an alternative list of filenames,
pass it as the first argument to input().
A single file name is also allowed.

So, when I replace file0001.html with file.list (the