2013-10-29 105 views
0

我已經查看了很多關於此主題的答案,因爲我可以找到並且所有提示它是全局 - 本地衝突。我不明白這是如何適用於我的情況,但請解釋一下。這裏的錯誤:在分配之前引用的局部變量'CompletelyUniqueName'

「局部變量‘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 

此代碼工作時,不是一個函數而僅僅是一個腳本。再次,我知道這會使它看起來像是一個全球性的本地問題,但考慮到我給這個變量賦予的名字,我認爲我已經盡力避免衝突了。

+0

'如果文件名.endswith('。tif'):'如果這個條件失敗,那麼'return Co mpletelyUniqueName'會引發這個錯誤。 –

+0

沒錯,我會解決這個問題,但它已經收到了tif。回到那ASAP – mercergeoinfo

+0

是的,就是這樣。在將文件名傳遞給函數之前,調用函數的腳本將.tif關閉。儘管如此,我現在正在if循環運行之前爲變量分配一個錯誤消息。我被鎖定在不需要在Python中啓動變量我忘記了可能有其他原因導致失敗:我的愚蠢。謝謝您的幫助。 – mercergeoinfo

回答

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 
1

您應該定義默認值CompletelyUniqueName(對於情況下,如果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 
相關問題