2013-08-26 34 views
1

我剛開始使用ArcPy通過ArcGIS分析地理數據。分析有不同的步驟,它們將一個接一個地執行。如何用多個分析步驟組織一個Python GIS項目?

下面是一些僞代碼:

import arcpy 

# create a masking variable 
mask1 = "mask.shp"  

# create a list of raster files 
files_to_process = ["raster1.tif", "raster2.tif", "raster3.tif"] 

# step 1 (e.g. clipping of each raster to study extent) 
for index, item in enumerate(files_to_process): 
     raster_i = "temp/ras_tem_" + str(index) + ".tif" 
     arcpy.Clip_management(item, '#', raster_i, mask1) 

# step 2 (e.g. change projection of raster files) 
... 

# step 3 (e.g. calculate some statistics for each raster) 
... 

etc. 

此代碼工作得非常好爲止。但是,光柵文件很大,並且某些步驟需要很長時間才能執行(5-60分鐘)。因此,我只想在輸入柵格數據發生變化時才執行這些步驟。從GIS工作流的角度來看,這不應該成爲一個問題,因爲每一步都會在硬盤上保存一個物理結果,然後在下一步中用作輸入。

我想如果我想暫時禁用例如第1步,我可以簡單地把#放在這一步的每一行前面。但是,在實際分析中,每一步可能有很多代碼行,因此我寧願將每個步驟的代碼外包到單獨的文件中(例如「step1.py」,「step2.py」,.. 。),然後執行每個文件。

我用execfile(step1.py)進行了實驗,但收到錯誤NameError: global name 'files_to_process' is not defined。似乎主腳本中定義的變量不會自動傳遞給由execfile調用的腳本。

我也試過this,但我收到了與上面相同的錯誤。

我是一個Python新手(正如您可能已經發現錯誤使用任何與Python相關的表達式一樣),我將非常感謝任何關於如何組織這樣一個GIS項目的建議。

回答

1

我認爲你想要做的是將每一步構建到一個函數中。這些函數可以存儲在同一個腳本文件中,也可以存儲在自己的模塊中,該模塊使用import語句加載(就像arcpy一樣)。僞代碼將是這樣的:

#file 1: steps.py 
def step1(input_files): 
    # step 1 code goes here 
    print 'step 1 complete' 
    return 

def step2(input_files): 
    # step 2 code goes here 
    print 'step 2 complete' 
    return output # optionally return a derivative here 

#...and so on 

然後在同一目錄中的第二個文件,你可以導入並調用傳遞柵格作爲輸入的功能。

#file 2: analyze.py 
import steps 
files_to_process = ["raster1.tif", "raster2.tif", "raster3.tif"] 

steps.step1(files_to_process) 

#steps.step2(files_to_process) # uncomment this when you're ready for step 2 

現在你可以選擇調用代碼的不同步驟,只需要評論/不包括一條線,而不是代碼whle塊。希望我正確理解你的問題。

+0

這正是我想要做的,而且工作得很好。謝謝! –

相關問題