2014-04-03 138 views
0

我的代碼中的全局變量有問題。在SCRIPT1.py中,我使用了很多變量,這些變量只包含我在代碼的其他模塊中需要的變量。但是當運行我的SCRIPT1.py時,我得到一個錯誤(錯誤)。我不知道爲什麼它不能與config(變量的名稱)一起工作...我發現這個解決方案讓您的所有模塊中的變量都堆棧溢出,並獲得了很多好評。我究竟做錯了什麼?全局變量問題((python))

首先,我的代碼包含了config.costSurfaceA而不是costSurfaceArray(對於def defPath中的ex),但是當使用此變量運行它時,由於'config.costSurfaceA'中的點,它給了我一個語法錯誤。我用'costSurfaceArray'替換了它,並在if語句'config.costSurfaceA = costSurfaceArray'中做了這個,只是爲了將它作爲一個變量。但我有這種感覺,這是多麼的沒有任何工作..

感謝avance幫助我!我知道這是一個很大的代碼,但我認爲這是所有認識的重要..

SCRIPT1.py

from osgeo import gdal, osr 
from skimage.graph import route_through_array 
import numpy as np 
import Save_Array_To_Excel_01 
import config 

def ask_costsurfacepath_path(): 
    config.costsurfacepath = input('please enter the system path where to find the cost-surface-IMG file (ex: /Users/PeterVanvoorden/Documents/GroepT/Thesis/Branched_Testfile.img): ') 

def ask_outputpath_path(): 
    config.outputpath = input('please enter the system path where to save the outputpath IMG file (ex: /Users/PeterVanvoorden/Documents/GroepT/Thesis/Branched_Testfile.img): ') 


def raster2array(rasterfn): 
    print 'raster2array' 
    raster = gdal.Open(rasterfn) 
    band = raster.GetRasterBand(1) 
    array = band.ReadAsArray() 
    return array 

def coord2pixelOffset(rasterfn,x,y): 
    print 'coord2pixelOffset' 
    raster = gdal.Open(rasterfn) 
    geotransform = raster.GetGeoTransform() 
    originX = geotransform[0] # East/West location of Upper Left corner 
    originY = geotransform[3] # North/South location of Upper Left corner 
    pixelWidth = geotransform[1] # X pixel size 
    pixelHeight = geotransform[5] # Y pixel size 
    xOffset = int((x - originX)/pixelWidth) 
    yOffset = int((y - originY)/pixelHeight) 
    return xOffset,yOffset 

def createPath(CostSurfacefn,costSurfaceArray,startCoord,stopCoord): 
    print 'creatpath' 
    # coordinates to array index 
    startCoordX = startCoord[0] 
    startCoordY = startCoord[1] 
    startIndexX,startIndexY = coord2pixelOffset(CostSurfacefn,startCoordX,startCoordY) 

    stopCoordX = stopCoord[0] 
    stopCoordY = stopCoord[1] 
    stopIndexX,stopIndexY = coord2pixelOffset(CostSurfacefn,stopCoordX,stopCoordY) 

    # create path 
    indices, weight = route_through_array(costSurfaceArray, (startIndexY,startIndexX), (stopIndexY,stopIndexX),geometric=True,fully_connected=True) 
    indices = np.array(indices).T 
    path = np.zeros_like(costSurfaceArray) 
    path[indices[0], indices[1]] = 1 
    return path 

def array2raster(newRasterfn,rasterfn,array): 
    print 'array2raster' 
    raster = gdal.Open(rasterfn) 
    geotransform = raster.GetGeoTransform() 
    originX = geotransform[0] # East/West location of Upper Left corner 
    originY = geotransform[3] # North/South location of Upper Left corner 
    pixelWidth = geotransform[1] # X pixel size 
    pixelHeight = geotransform[5] # Y pixel size 
    cols = array.shape[1] 
    rows = array.shape[0] 

    driver = gdal.GetDriverByName('GTiff') 
    outRaster = driver.Create(newRasterfn, cols, rows, gdal.GDT_Byte) 
    outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight)) 
    outband = outRaster.GetRasterBand(1) 
    outband.WriteArray(array) 
    outRasterSRS = osr.SpatialReference() 
    outRasterSRS.ImportFromWkt(raster.GetProjectionRef()) 
    outRaster.SetProjection(outRasterSRS.ExportToWkt()) 
    outband.FlushCache()  

def main(CostSurfacefn,outputPathfn,startCoord,stopCoord): 

    print 'main' 

    costSurfaceArray = raster2array(CostSurfacefn) # creates array from cost surface raster 

    config.costSurfaceA = costSurfaceArray 

    config.pathArray = createPath(CostSurfacefn,costSurfaceArray,startCoord,stopCoord) # creates path array 

    Save_Array_To_Excel_01.Save_Array(config.pathArray) # Save Array to csv file 

    array2raster(outputPathfn,CostSurfacefn,config.pathArray) # converts path array to raster 


if __name__ == "__main__": 

    ask_costsurfacepath_path() 
    ask_outputpath_path() 
    CostSurfacefn = config.costsurfacepath 
    print config.costsurfacepath 
    startCoord = (config.startX,config.startY) 
    stopCoord = (config.stopX,config.stopY) 
    outputPathfn = config.outputpath 

    main(CostSurfacefn,outputPathfn,startCoord,stopCoord) 

config.py

# Configuration file with all global variables 

# number of properties 
number = None 

# different permutations of properties 
permutations = list() 

# properties array containing: 
# * first column = ID first property [0] 
# * second column = ID second property [1] 
# * third column = distance between two properties [2] 
# * forth column = estimated cost [3] 
properties_array = None 

# lowest price until now 
lowest_price = 10**10000 

# path with this lowest price 
lowest_path = None 

# current price (needs to be compared with lowest price) 
current_price = 0 

# current path (needs to be compared with lowest path) 
current_path = [1] 

# path to place where to save properties list 
plist_path = None 

# Array of the path 
pathArray = None 

# Array of the map 
costSurfaceA = None 

# current start X coordinate 
startX = 0 

# current start Y coordinate 
startY = 0 

# current stop X coordinate 
stopX = 0 

# current stop Y coordinate 
stopY = 0 

# path to costsurface IMG file 
costsurfacepath = 0 

# path to output path from Least cost path analysis 
outputpath = 0 

ERROR

please enter the system path where to put the file as a STRING (ex: /Users/PeterVanvoorden/Documents/GroepT/Thesis/Branched_Testfile.csv): '/User/PeterVanvoorden/Desktop/Shell.csv' 

You entered: /User/PeterVanvoorden/Desktop/Shell.csv 

please enter the system path where to find the cost-surface-IMG file (ex: /Users/PeterVanvoorden/Documents/GroepT/Thesis/Branched_Testfile.img): '/User/PeterVanvoorden/Desktop/clipsmall.img' 
please enter the system path where to save the outputpath IMG file (ex: /Users/PeterVanvoorden/Documents/GroepT/Thesis/Branched_Testfile.img): '/User/PeterVanvoorden/Desktop/Shellimg.img' 
/User/PeterVanvoorden/Desktop/clipsmall.img 
main 
raster2array 

Traceback (most recent call last): 
    File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/f_python_standalone/python_files/Working_Files/Least_cost_path_analysis_01_outputArray.py", line 97, in <module> 
    main(CostSurfacefn,outputPathfn,startCoord,stopCoord) 
    File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/f_python_standalone/python_files/Working_Files/Least_cost_path_analysis_01_outputArray.py", line 76, in main 
    costSurfaceArray = raster2array(CostSurfacefn) # creates array from cost surface raster 
    File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/f_python_standalone/python_files/Working_Files/Least_cost_path_analysis_01_outputArray.py", line 17, in raster2array 
    band = raster.GetRasterBand(1) 
AttributeError: 'NoneType' object has no attribute 'GetRasterBand' 
+0

此後柵格的價值是什麼? raster = gdal.Open(rasterfn) – adarsh

+0

柵格值爲None。 –

+0

你確定'CostSurfacefn'應該是0嗎? (從配置)從名稱來說,它聽起來像一個函數或lambda。另外我不認爲這個命名約定適用於Python。我們只在Python中使用camel-case來獲取類名。變量名稱和方法/函數名稱通常是蛇形的 – adarsh

回答

0

你可以像這樣傳遞。

def ask_costsurfacepath_path(): 
    costsurfacepath = input('please enter ...') 
    return costsurfacepath 

... in __name__ == '__main__' 
CostSurfacefn = ask_costsurfacepath_path() 
... 
+0

,但是這樣,是否有可能在另一個文件中使用costurfacepath的值?例如在一個名爲SCRIPT2.py的文件中?因爲這就是爲什麼我使用配置文件...不要在同一個文件中的不同功能中使用它,而是爲了在另一個文件中輕鬆使用它。 –

+0

例如,如果您在導入的第二個文件中調用了某個函數,例如'from SCRIPT2 import some_func',那麼當然可以將該變量作爲參數傳遞給'some_func' – adarsh

+0

但是我的意思是,我該如何做到這一點?我想在SCRIPS2中使用這個變量VAR。我想在這個變量中使用這個變量VAR。PY 我應該做比: SCRIPT2.py '進口SCRIPT1' ???? 我只想得到變量的值,而不是像這樣: SCRIPT2.py '進口SCRIPT1 BLI = SCRIPT1.function1()' ,因爲比我會在再次代替運行此腳本只是使用已經存在的VAR值,因爲SCRIPT1.py已經被執行了。 –