Excellent, thank you and yes I need to work on how to catch and handle exceptions Thanks again!
On Wed, Sep 28, 2011 at 4:13 PM, bob gailer <bgai...@gmail.com> wrote: > On 9/27/2011 11:18 PM, questions anon wrote: > > I would like to use user_input() to decide how to slice a list. > This works fine until I try to leave it blank to try and select the whole > list [:] > I have posted the section of interest below and the error I get when I try > to press enter. Further below that is the entire code. > Any feedback will be greatly appreciated. > * > section of code of interest:* > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > endperiod=int(raw_input("End slice (e.g. 2): ")) > skipperiod=int(raw_input("skip slice (e.g. 1): ")) > > if startperiod=="" and endperiod=="" and skipperiod=="": > startperiod="" > endperiod="" > skipperiod="" > > > int() expects a character representation of an integer. An empty string > will raise the exception you reported. > > startperiod will NEVER == "", as it will be an integer. > > The entire if statement does nothing! Discard it. > > Defer applying int(). > > Then you can check startperiod etc for equality to "". > > if startperiod == "": > startperiod = None > else: > startperiod = int(startperiod) > if endperiod == "": > > endperiod = None > else: > endperiod = int(endperiod) > if skipperiod == "": > skipperiod = None > else: > skipperiod= int(skipperiod) > > AND BE PREPARED to catch & handle exceptions in case user enters a > non-integer value. > > > 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') > > variable=ncfile.variables[ncvariablename][:] > TIME=ncfile.variables['time'][:] > > fillvalue=ncfile.variables[ncvariablename]._FillValue > ncfile.close() > > for variable, TIME in > zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): > > > *the error:* > > Traceback (most recent call last): > File "<pyshell#27>", line 1, in <module> > plotrawdata('TSFC') > File "D:\My Dropbox\Python_code\functions.py", line 39, in plotrawdata > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > ValueError: invalid literal for int() with base 10: '' > > > *THE WHOLE PROGRAM:* > from netCDF4 import Dataset > import numpy as N > import matplotlib.pyplot as plt > from numpy import ma as MA > from mpl_toolkits.basemap import Basemap > from netcdftime import utime > from datetime import datetime > import os > import matplotlib.colors as mc > import matplotlib.colorbar as c > > OutputFolder=r"D:/DSE_work/temp_samples2/" > MainFolder=r"D:/DSE_work/temp_samples2/" > > > def plotrawdata(variable): > if variable=='TSFC': > ncvariablename='T_SFC' > MainFolder=r"D:/DSE_work/temp_samples2/" > ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] > Title='Surface Temperature' > > elif variable=='RHSFC': > ncvariablename='RH_SFC' > > MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/temp_samples6/" > ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 101] > Title='Surface RH' > > > fileforlatlon=Dataset("D:/DSE_work/temp_samples2/2020/01/IDZ00026_VIC_ADFD_T_SFC.nc", > 'r+', 'NETCDF4') > LAT=fileforlatlon.variables['latitude'][:] > LON=fileforlatlon.variables['longitude'][:] > > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > endperiod=int(raw_input("End slice (e.g. 2): ")) > skipperiod=int(raw_input("skip slice (e.g. 1): ")) > > if startperiod=="" and endperiod=="" and skipperiod=="": > startperiod=str("") > endperiod=str("") > skipperiod=str("") > > > 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') > > variable=ncfile.variables[ncvariablename][:] > TIME=ncfile.variables['time'][:] > > fillvalue=ncfile.variables[ncvariablename]._FillValue > ncfile.close() > > for variable, TIME in > zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): > #for variable, TIME in > zip((variable[sliceperiod]),(TIME[sliceperiod])): > > 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') > #Set up basemap using mercator > projection > http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html > 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(Title+' %s > UTC'%ncfiletime) > > CS = map.contourf(x,y,variable, > 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) > > #save map as *.png and plot > netcdf file > > plt.savefig((os.path.join(OutputFolder, > ncvariablename+date_string+'UTC.png'))) > plt.show() > plt.close() # must use > plt.close() so that colorbar works! > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription > options:http://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer919-636-4239 > Chapel Hill NC > >
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor