[Tutor] Funtions, modules & global variables
questions anon
questions.anon at gmail.com
Mon Sep 26 01:21:27 CEST 2011
Hi All,
I am trying to move from writing one long script each time I need to do a
new thing but I do not quite understand how functions work, even after
reading many manuals.
My first attempt is to create a python file where I have defined a number of
functions that get data in various ways.
I have also made another python file where I want to plot the data in
different ways. but I am having trouble getting that data to run in my
python plotting file.
I have made the variable I require 'global' but that doesn't seem to be
working. I keep receiving:
*
UnboundLocalError: local variable 'TSFC' referenced before assignment*
Below is a some of the script for both folder, just note that their will be
many functions in each folder
Any help will be greatly appreciated!!!
#selectdata.py
def selectalldata():
for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print dir
path=path+'/'
for ncfile in files:
if ncfile[-3:]=='.nc':
print "dealing with ncfiles:", path+ncfile
ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 'NETCDF4')
global TSFC
TSFC=ncfile.variables['T_SFC'][:,:,:]
LAT=ncfile.variables['latitude'][:]
LON=ncfile.variables['longitude'][:]
TIME=ncfile.variables['time'][:]
fillvalue=ncfile.variables['T_SFC']._FillValue
ncfile.close()
#plotdata.py
from selectdata import selectalldata
selectalldata()
def plotncfilewithtime():
for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])):
#convert time from numbers to date and prepare it to have no symbols for
saving to filename
cdftime=utime('seconds since 1970-01-01 00:00:00')
ncfiletime=cdftime.num2date(TIME)
print ncfiletime
timestr=str(ncfiletime)
d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
date_string = d.strftime('%Y%m%d_%H%M')
map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,
llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i')
x,y=map(*N.meshgrid(LON,LAT))
map.drawcoastlines(linewidth=0.5)
map.readshapefile(shapefile1, 'DSE_REGIONS')
map.drawstates()
plt.title('Surface temperature at %s UTC'%ncfiletime)
ticks=[-5,0,5,10,15,20,25,30,35,40,45,50]
CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet)
l,b,w,h =0.1,0.1,0.8,0.8
cax = plt.axes([l+w+0.025, b, 0.025, h], )
cbar=plt.colorbar(CS, cax=cax, drawedges=True)
plt.savefig((os.path.join(outputfolder,
'TSFC'+date_string+'UTC.png')))
plt.close() # must use plt.close() so that colorbar works!
print "end of processing"
plotncfilewithtime()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/147f0480/attachment.html>
More information about the Tutor
mailing list