0

我已经浏览了尽可能多的关于这个主题的答案,并且都认为这是一场全球 - 本地冲突。我看不出这将如何适用于我的情况,但请解释一下。这是错误:

“分配前引用的局部变量‘CompletelyUniqueName’”

这是代码,我从另一个脚本调用的函数:

def geopixsum(filename):
    # register all of the GDAL drivers
    gdal.AllRegister()
    # Check file type (in this case Geotiff)
    if filename.endswith('.tif'):
        # open the image
        try:
            inDs = gdal.Open(filename)
        except:
          print 'Could not open ',file,'\n'
        # get image size
        rows = inDs.RasterYSize
        cols = inDs.RasterXSize
        # read band 1 into data
        band1 = inDs.GetRasterBand(1)
        data = band1.ReadAsArray(0,0,cols,rows)
        # get nodata value
        nandat = band1.GetNoDataValue()
        sumvals = data[np.where(np.logical_not(data == nandat))]
        CompletelyUniqueName = sumvals.sum()
        print 'sum = ',CompletelyUniqueName
    inDs = None
    return CompletelyUniqueName

这段代码在不是一个函数而只是一个脚本时才起作用。再一次,我知道这会使它看起来像是一个全局 - 本地问题,但鉴于我已经分配了变量的名称,我认为我已经竭尽全力避免冲突。

4

2 回答 2

1

您应该为CompletelyUniqueName(for case if filename.endswith('.tif') == False)定义默认值

def geopixsum(filename):
    CompletelyUniqueName = 0 
    if filename.endswith('.tif'):
        ...
        CompletelyUniqueName = sumvals.sum()
    return CompletelyUniqueName

或返回内部if语句

def geopixsum(filename):
    if filename.endswith('.tif'):
        ...
        CompletelyUniqueName = sumvals.sum()
        return CompletelyUniqueName
于 2013-10-29T13:04:43.397 回答
0

最简单的修复:

def geopixsum(filename):
    CompletelyUniqueName = 0    # or None, or anything you want to return 
                                # if the file is not a tif
    # register all of the GDAL drivers
    gdal.AllRegister()
    # Check file type (in this case Geotiff)
    if filename.endswith('.tif'):
        # open the image
        try:
            inDs = gdal.Open(filename)
        except:
          print 'Could not open ',file,'\n'
        # get image size
        rows = inDs.RasterYSize
        cols = inDs.RasterXSize
        # read band 1 into data
        band1 = inDs.GetRasterBand(1)
        data = band1.ReadAsArray(0,0,cols,rows)
        # get nodata value
        nandat = band1.GetNoDataValue()
        sumvals = data[np.where(np.logical_not(data == nandat))]
        CompletelyUniqueName = sumvals.sum()
        print 'sum = ',CompletelyUniqueName
    inDs = None
    return CompletelyUniqueName
于 2013-10-29T12:55:10.813 回答