[Tutor] 'source' in python or preloading variables
John
washakie at gmail.com
Sun Nov 4 14:07:32 CET 2007
Does anyone know why the script below works fine (in regards to the 'source
function') but when I try to uncomment the line from mymod import source and
use it that way without defining the function in the script, I get an error
that N_id does not exist. It must have something to do with namespace and
global variables I don't understand...
#!/usr/bin/env python
from PyF import *
#from mymod import source
vList=['N_id','Nlat','Nlon','Nelv']
###### FUNCTION #########
def source(filename, vList):
""" Reads a filename, collects variabls in file, and returns
variables.
Usage: source(filename, vList) where vList is a list of variables.
"""
import re
# Read the file
fid=open(filename,'r')
lines = fid.readlines()
fid.close()
#how many variables
ns=len(lines)/len(vList)
#predefine the varibles
for v in vList:
exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))
# Make it python friendly: put all values in 'single quotes'
cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
lines])
exec(cmd)
for v in vList:
exec( "global %s ; %s = %s[1:]" % (v,v,v) )
source('sites_ALL',vList)
for s in N_id:
fw=stnWeb(s)
fw.mkStnBase()
fw.mkWebBase()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/cbaff03c/attachment.htm
More information about the Tutor
mailing list