全局变量的问题((python))

时间:2014-04-03 19:57:53

标签: python-2.7 module global-variables

我的代码中的全局变量存在问题。在SCRIPT1.py中,我使用来自一个小文档config.py的许多变量,它只包含我在代码的其他模块中也需要的变量。但是在运行我的SCRIPT1.py时出现错误(错误)。我不知道为什么它不能使用config。(变量名称)...我发现这个解决方案让你的所有模块中的变量在堆栈溢出时有很多好的投票。我做错了什么?

首先我的代码包含config.costSurfaceA而不是costSurfaceArray(对于ex' def createPath')但是当使用此变量运行它时,由于&#39中的点,它给了我一个语法错误; config.costSurfaceA&#39 ;.我用' costSurfaceArray'取而代之。并在if语句中做了这个' config.costSurfaceA = costSurfaceArray'只是把它作为一个变量。但我觉得这一切都无济于事......

感谢您帮助我!我知道这是很多代码,但我认为这对理解很重要。

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'

1 个答案:

答案 0 :(得分:0)

你可以这样传球。

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

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