Arcpy 通过mxd模版生成专题图

GISutil.createJPEG(mxdPath, outputPath, outTIFPath, issue, cycle)

###################下面代码新建文件命名为 GISutil ###############
# -*- coding: utf-8 -*-
import arcpy 
import os,sys
import datetime
import time
from arcpy import env
from arcpy.sa import *
import arcpy.mapping as mapping
import string
from _server_admin.utils import date

def outpathCheck(outPath):
    try:
        if outPath[-1]=="\\" or outPath[-1]=="/":
            outPath=outPath
        else:
            outPath=outPath+"\\"    
        if not os.path.exists(outPath): 
            os.makedirs(outPath)
    except Exception,ex:
        print Exception,":",ex
        return False
    else:
        return outPath

''' 遍历分割文件目录,对栅格数据进行剪裁,
    参数一:栅格数据位置
    参数二:分割文件的文件路径
    参数三:输出路径
    参数四:期号
'''
def SplitRaster(sourceData,splitPath,outPath,strTime,period):
    #测试ID
    #proID="4028813442b61acd0142b6200e6f0002"
    arcpy.env.overwriteOutput =True
    arcpy.CheckOutExtension("spatial")
    env.workspace = splitPath
    
    short_name=sourceData.split("\\")[-1].split(".")[0] 
    fcList =arcpy.ListFeatureClasses()
    arcpy.AddMessage(fcList)
    for fc in fcList:
        outputPath=CreateProductPath(strTime,outPath,os.path.splitext(fc)[0],period)
        #outputPath= outputPath.encode('gbk').decode('utf-8')
        if outputPath[-1] == "\\":
            # Execute ExtractByMask
            outExtractByMask = ExtractByMask(sourceData, fc)

            # Save the output 
            out_name = outputPath +"\\"+short_name + "_" + os.path.splitext(fc)[0] +".tif"
            outExtractByMask.save(out_name)

            #arcpy.gp.ExtractByMask_sa(sourceData, fc,outputPath+ strTime+".img")
            arcpy.AddMessage( out_name +"     OK")
        else:
            # Execute ExtractByMask
            outExtractByMask = ExtractByMask(sourceData, fc)

            # Save the output 
            out_name = outputPath +"\\"+short_name + "_" + os.path.splitext(fc)[0] +".tif"
            outExtractByMask.save(out_name)

            #arcpy.gp.ExtractByMask_sa(sourceData, fc,outputPath+"\\"+ strTime+".img")
            arcpy.AddMessage( out_name +"     OK")
        

#dissolve实现
def shpDissolve(inFeatures,dissolveFields):
    # Set local variables
    outFeatureClass = "C:/temp/fcs_dissolved" + str(int(time.time()))+".shp"
     
    # Execute Dissolve
    arcpy.Dissolve_management(inFeatures, outFeatureClass, dissolveFields, "", 
                              "SINGLE_PART", "DISSOLVE_LINES")
    
    return outFeatureClass


#消除破碎多边形
def shpEliminate(inFeatures,expression):
    # Set local variables
    inFeatures = inFeatures
    tempLayer = "c:\\temp\\eliminate_temp" + str(int(time.time()))+".shp"
    expression = '"F_AREA" < 200*1000000 and "GRIDCODE" = 0 '
    eliminate_polygons = "C:\\temp\\eliminate" + str(int(time.time()))+".shp"
    #exclusionExpression = '"OBJECTID" = 9'
 
    # Execute MakeFeatureLayer
    arcpy.MakeFeatureLayer_management(inFeatures, tempLayer)
 
    # Execute SelectLayerByAttribute to define features to be eliminated
    arcpy.SelectLayerByAttribute_management(tempLayer, "NEW_SELECTION", expression)
    
    # Execute Eliminate
    arcpy.Eliminate_management(tempLayer, eliminate_polygons, "AREA")
    arcpy.AddMessage( "cal Eliminate_management OK")
    
    data_type=""
    # Execute Delete
    arcpy.Delete_management(tempLayer, data_type)
    
    return eliminate_polygons
                   
#根据表达式删除属性表中纪录                  
def delByExp(inData,expression):
    if not arcpy.Exists(inData):
        return;
    try:
        tempTableView = "tempTableView"
        arcpy.MakeTableView_management(inData, tempTableView)
        arcpy.SelectLayerByAttribute_management (tempTableView, "NEW_SELECTION", expression)
        if int(arcpy.GetCount_management(tempTableView).getOutput(0)) > 0:
            arcpy.DeleteRows_management(tempTableView)
    except Exception as err:
        print(err.args[0])  
		
#存储shp到gdb中
def shp2gdb(shpPath,gdbPath,layerName):
    try:
        arcpy.env.overwriteOutput =True
        arcpy.CheckOutExtension("spatial")
        
        gdbFolderPath = os.path.split(gdbPath)[0]
        gdbName = os.path.split(gdbPath)[1]
        dstFeaturePath =gdbPath+"\\"+layerName

        if not  arcpy.Exists(gdbPath):
            arcpy.CreateFileGDB_management(gdbFolderPath,gdbName)
            print gdbPath+"  CreateFileGDB_management ok"
            arcpy.CopyFeatures_management(shpPath,dstFeaturePath,"", "0", "0", "0")
            arcpy.AddMessage( "Append OK")
        else:
            if not arcpy.Exists(dstFeaturePath):              
                arcpy.CopyFeatures_management(shpPath,dstFeaturePath,"", "0", "0", "0")
                print dstFeaturePath+" CopyFeatures_management ok"
                arcpy.AddMessage( "Append OK")
            else:              
                arcpy.Append_management(shpPath, dstFeaturePath, "NO_TEST", "", "")
                arcpy.AddMessage( "Append OK")
        print("shp2gdb OK")
    except Exception,e: 
        arcpy.AddError(e.message)

#mxd导出为jpg
def mxd2jpg(MxdPath,strTime,picPath):
    #替换工作目录,保证mxd能够打开
    #ReplaceWorkspace(mxdPath,srcDataPath,outputPath,outMxdPath)
    ChangeTitle(MxdPath,strTime)
    #导出图片,现在只支持.jpg格式
    ExportMap(MxdPath,picPath)
    print "Export Map OK"
    
#将mxd导出为图片
def ExportMap(mxdPath,picPath):
    if not os.path.exists(mxdPath):
        return
    mxd = mapping.MapDocument(mxdPath)
    mapping.ExportToJPEG(mxd,picPath)
    del mxd

#复制mxd目录下文件
def CopyFiles(sourceDir,  targetDir):
    arcpy.AddMessage( targetDir)
    if not os.path.exists(targetDir):
        os.makedirs(targetDir)
        arcpy.AddMessage(targetDir)
    if not os.path.exists(sourceDir):
        return
    for file in os.listdir(sourceDir): 
        sourceFile = os.path.join(sourceDir,file) 
        targetFile = os.path.join(targetDir,file) 
        if os.path.isfile(sourceFile): 
            if not os.path.exists(targetDir):  
                os.makedirs(targetDir)  
            if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
                if not os.path.splitext(sourceFile)[1] == '.mxd' and not sourceFile[-5:]=='.lock' :
                    open(targetFile, "wb").write(open(sourceFile, "rb").read()) 
        if os.path.isdir(sourceFile): 
            First_Directory = False 
            CopyFiles(sourceFile, targetFile)

    
#替换mxd工程的工作空间'''
def ReplaceWorkspace(mxdPath,srcWorkspace, dstWorkspace,dstMxdPath,lyrRasterName):

    if not os.path.exists(mxdPath):
        return
    mxdBasePath  = os.path.split(dstMxdPath)[0]
    mxdname = os.path.split(dstMxdPath)[1]
    #lyrname = mxdname.split('.')[0]
    if not os.path.exists(mxdBasePath):
        os.makedirs(mxdBasePath)
    mxd = arcpy.mapping.MapDocument(mxdPath)
    mxd.findAndReplaceWorkspacePaths(srcWorkspace,dstWorkspace)
    for lyr in arcpy.mapping.ListBrokenDataSources(mxd):
            if lyr.supports("DATASOURCE") :
                #修改矢量数据源
                #lyr.replaceDataSource( dstWorkspace,"SHAPEFILE_WORKSPACE",lyrRasterName)
                #修改栅格数据源     
                lyr.replaceDataSource( dstWorkspace,"RASTER_WORKSPACE",lyrRasterName)     
                                        
    mxd.saveACopy(dstMxdPath)

    del mxd
    
    
def Time2Str(strTime):
    day = string.atoi(strTime[6:8])
    strXun =""
    if day <11 :
        strXun =u"上"
    elif day<21:
        strXun =u"中"
    else:
        strXun = u"下"
    return strXun

def  ChangeTitle(mxdPath,strTime):
    if not os.path.exists(mxdPath):
        return
    mxd = arcpy.mapping.MapDocument(mxdPath)
    for textElement in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        if textElement.name == "title" or textElement.name == "date":
            txt =textElement.text 
            txt = txt.replace("yyyy",strTime[0:4])
            txt = txt.replace("MM",strTime[4:6])
            txt = txt.replace("dd",strTime[6:8])
            txt = txt.replace("XX",Time2Str(strTime))
            txt = txt.replace("HH",strTime[8:10])
            textElement.text = txt
    mxd.save()
    del mxd


def getAllNames(Path):
    nameList={'lyrRasterName':'',
              'lyrRasterName':'',
              'jpgName':'',
              'excelName':'',
              'txtName':''
              }
    fileList = os.listdir(Path)
    for file in fileList:
        if file.endswith('.tif'):
            nameList['lyrRasterName'] = file #栅格文件名
            nameList['lyrShpName'] = file.replace(file[0:10], file[0:9]+'V').replace('tif','shp') #shp图
            nameList['jpgName'] = file.replace(file[0:10], file[0:9]+'Z').replace('tif','jpg') #专题图
            nameList['excelName'] = file.replace(file[0:10], file[0:9]+'S').replace('tif','xls') #统计excel
            nameList['txtName'] = file.replace(file[0:10], file[0:9]+'T').replace('tif','txt') #txt
    
    return nameList



'''
            全省mxd路径,被拆分数据 ,拆分文件夹,输出根目录,时间
'''
def DistributeProduct(mxdPath, sourceData,splitPath,RootPath,strTime,period):
    try:
        arcpy.env.overwriteOutput =True
        arcpy.CheckOutExtension("spatial")
        env.workspace = splitPath    
        fcList =arcpy.ListFeatureClasses()    
        oldRegionID =u"QHS"
    
        for fc in fcList:
            regionID =fc.split(".")[0]
            mxdPath =mxdPath.replace(oldRegionID,regionID)
            oldRegionID=regionID
            mxdName = os.path.split(mxdPath)[1]
            arcpy.AddMessage(mxdName)
            
            outputPath=CreateProductPath(strTime,RootPath,regionID,period)
            #栅格图层名(如牧草产量栅格)
            allName = getAllNames(outputPath)
            lyrRasterName = allName.get('lyrRasterName')
            if lyrRasterName =="" :
                break
            
            srcDataPath = os.path.split(mxdPath)[0]        
            outMxdPath=os.path.join(outputPath,mxdName)
            
            #按行政区拆分shp数据,业务图层
            shpName=allName.get('lyrShpName')
            outShpPath =os.path.join(outputPath,shpName)
            arcpy.Clip_analysis(sourceData, fc,outShpPath)
            arcpy.AddMessage("clip OK")
            
            #复制源mxd目录下数据到目标目录下,以供下载,
            arcpy.AddMessage(srcDataPath+outputPath)
            CopyFiles(srcDataPath,outputPath)
            arcpy.AddMessage(" Copy Files OK")
            
            #替换工作目录,保证mxd能够打开
            ReplaceWorkspace(mxdPath,srcDataPath,outputPath,outMxdPath,lyrRasterName)
            ChangeTitle(outMxdPath,strTime)
            arcpy.AddMessage("Replace Workspace OK")
            
            #导出图片jpg格式
            jpgName=allName.get('jpgName')
            outPicPath =os.path.join( outputPath,jpgName)
            ExportMap(outMxdPath,outPicPath)
            arcpy.AddMessage("Export Map OK")    
    except Exception,e: 
        arcpy.AddError(e.message)
        return
    
# 直接使用datetime的格式转换功能得到结果
def converse_mod13q1_time_format(year, month, day,hh):
    date = datetime.date(year, month, day)
    date_str = date.strftime('%j')
    mod13q1_product_day = int(date_str)
    return mod13q1_product_day

def converse_day_to_time(year, day):
    fir_day = datetime.datetime(year,1,1)
    zone = datetime.timedelta(days=day-1)
    return datetime.datetime.strftime(fir_day + zone, "%Y%m%d")


# 判断是上半月还是下半月
def convrse_mod13q1_day_to_half_month(day):
    product_month = day/32 + 1
    if day%16 == 0:
        if (day/16)%2 == 0:
            product_month_label = u"上"
        else:
            product_month_label = u"下"
    else:
        product_month_label = ''
    return [product_month, product_month_label]


def changeTitleTxt(textElement,rasterFileName,region,strTime,cycle):
    year = int(strTime[0:4])
    month = int(strTime[4:6])
    day = int(strTime[6:8])
    hh = int(strTime[8:10])
    #product_day = converse_mod13q1_time_format(year, month, day,hh)
    # product_day += 15
    # strTime2 = converse_day_to_time(year, product_day)
#     year2 = int(strTime2[0:4])
#     month2 = int(strTime2[4:6])
#     day2 = int(strTime2[6:8])
    print(textElement.name)
    if textElement.name == "COOH" and cycle == "COOH":
        inTxt = textElement.text
        inTxt = inTxt.replace("yyyy", strTime[0:4])
        inTxt = inTxt.replace("MM", strTime[4:6])
        inTxt = inTxt.replace("dd", strTime[6:8])
        inTxt = inTxt.replace("hh", strTime[8:10])
        inTxt = inTxt.replace("mm", strTime[10:12])
        textElement.text = inTxt
    elif textElement.name == "COAM" and cycle == "COAM":
        inTxt = textElement.text
        inTxt = inTxt.replace("yyyy", strTime[0:4])
        inTxt = inTxt.replace("MM", strTime[4:6])
        textElement.text = inTxt
    elif textElement.name == "COAQ" and cycle == "COAQ":
        inTxt = textElement.text
        inTxt = inTxt.replace("yyyy", strTime[0:4])
        num = int(strTime[4:6]) // 4 + 1
        print num
        inTxt = inTxt.replace("dd", num + '')
        textElement.text = inTxt
    elif textElement.name == "COAY" and cycle == "COAY":
        inTxt = textElement.text
        inTxt = inTxt.replace("yyyy", strTime[0:4])
        textElement.text = inTxt
    elif textElement.name == 'COOD' and cycle == "COOD":
        inTxt = textElement.text
        inTxt = inTxt.replace("yyyy", strTime[0:4])
        inTxt = inTxt.replace("MM", strTime[4:6])
        inTxt = inTxt.replace("dd", strTime[6:8])
        textElement.text = inTxt
        #print 'is not title or date'  

#专题图生成并导出
def exportJPEG(mxdPath,outpath,rasterPath,issue,cycle):
    dstWorkspace = os.path.dirname(rasterPath)
    lyrRasterName = os.path.basename(rasterPath)
    print rasterPath
    mxd = arcpy.mapping.MapDocument(mxdPath)
    
    for lyr in arcpy.mapping.ListBrokenDataSources(mxd):
        if lyr.supports("DATASOURCE") :
            fileType = lyrRasterName.split(".")[1].lower()         
            if ((fileType == 'shp')):
                #修改矢量数据源
                lyrShpName = os.path.basename(rasterPath)[:-4]
                lyr.replaceDataSource( dstWorkspace,"SHAPEFILE_WORKSPACE",lyrShpName)
            if ((fileType == 'tif')):   
                #修改栅格数据源     
                lyr.replaceDataSource( dstWorkspace,"RASTER_WORKSPACE",lyrRasterName)
                #lyr.replaceDataSource( dstWorkspace,"RASTER_WORKSPACE",lyrfirstname)
   
    for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
        mxd.dataDrivenPages.currentPageID = pageNum
        if mxdPath.find('sheng') != -1 :
            region = "河北省"
            regionCode = "130000000000"
        elif mxdPath.find('shi') != -1:
            region = mxd.dataDrivenPages.pageRow.CNAME
            #print region
            regionCode = mxd.dataDrivenPages.pageRow.CID
            #print regionCode
        elif mxdPath.find('xian')!= -1 :
            region = mxd.dataDrivenPages.pageRow.Xname
            regionCode = mxd.dataDrivenPages.pageRow.XID
        else :
            arcpy.AddMessage("There is no map template")
        
        #修改标题
        for textElement in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
            changeTitleTxt(textElement,lyrRasterName,region,issue,cycle)
        
        #获取文件名和路径
        file_old = os.path.basename(rasterPath)
        print file_old
        file_Type = file_old.split(".")[1].lower()
        
        if ((file_Type == 'shp')):
            file = file_old.replace(file_old[0:10], file_old[0:9]+'Z').replace('shp','png') #专题图
            filePath = outpath + "\\" + file            
        elif((file_Type == 'tif')):  
            file = file_old.split('.')[0] + "_" + regionCode + "." + file_old.split('.')[1]
            #file = file.replace('RCUR', 'ZCUR').replace('tif','png') #专题图
            file = file.replace('tif', 'png')  # 专题图
            #file = file.replace('tif','jpg')
            regionPath = outpath + "\\" + regionCode
            if not os.path.exists(regionPath):
                os.makedirs(regionPath)
            filePath = regionPath + "\\" + file
            print filePath
        
        
        #导出专题图
        print "Exporting page {0} of {1}".format(str(mxd.dataDrivenPages.currentPageID), str(mxd.dataDrivenPages.pageCount))
        arcpy.mapping.ExportToPNG(mxd, filePath)
        
    del mxd


#根据专题图模板生成省市县三级专题图                
def createJPEG(sourceDir,outpath,rasterPath,issue,cycle):
    #1.遍历模板文件夹,获取mxd
    if not os.path.exists(sourceDir):
        return
    mxdList = ['']
    for file in os.listdir(sourceDir): 
        sourceFile = os.path.join(sourceDir,file) 
        if os.path.isfile(sourceFile): 
            if  os.path.splitext(sourceFile)[1] == '.mxd':
                if string.find(sourceFile,cycle) == -1:
                    continue
                mxdList.append(sourceFile)
    if  len(mxdList) <=1 :
        print sourceDir+'has no mxd files'
        sys.exit()          
    
    #2.根据专题图模板生成jpg
    for mxdPath in mxdList:
        if mxdPath !='' :
            exportJPEG(mxdPath,outpath,rasterPath,issue,cycle)
            
            
            
'''
            全省mxd路径,被拆分数据 ,拆分文件夹,输出根目录,时间
'''
def splitProductAll(sourceData,rasterData,splitPath,RootPath,strTime,period):
    try:
        arcpy.env.overwriteOutput =True
        arcpy.CheckOutExtension("spatial")
        env.workspace = splitPath    
        fcList =arcpy.ListFeatureClasses()    
        
        for fc in fcList:
            regionID =fc.split(".")[0]
            outputPath=CreateProductPath(strTime,RootPath,regionID,period)
            allName = getAllNames(RootPath)
            #矢量数据裁剪
            shpName = allName.get('lyrShpName')[:-4]+'_'+regionID+'.shp'
            outShpPath =os.path.join(outputPath,shpName)
            arcpy.Clip_analysis(sourceData, fc,outShpPath)
            #栅格数据裁剪
            rasterName = allName.get('lyrRasterName')[:-4]+'_'+regionID+'.tif'
            outRasterPath = os.path.join(outputPath,rasterName)
            tifExtractByMask = ExtractByMask (rasterData, fc)
            tifExtractByMask.save(outRasterPath)
            arcpy.AddMessage(regionID+ " clip OK")
    except Exception,e: 
        arcpy.AddError(e.message)
        return

'''
            全省mxd路径,被拆分数据 ,拆分文件夹,输出根目录,时间
'''
def splitProduct(mxdPath, sourceData,splitPath,RootPath,strTime,period):
    try:
        arcpy.env.overwriteOutput =True
        arcpy.CheckOutExtension("spatial")
        env.workspace = splitPath    
        fcList =arcpy.ListFeatureClasses()    
        oldRegionID =u"LNS"
    
        for fc in fcList:
            regionID =fc.split(".")[0]
            mxdPath =mxdPath.replace(oldRegionID,regionID)
            oldRegionID=regionID
            mxdName = os.path.split(mxdPath)[1]
            arcpy.AddMessage(mxdName)
            
            outputPath=CreateProductPath(strTime,RootPath,regionID,period)
            #栅格图层名(如牧草产量栅格)
            allName = getAllNames(outputPath)
            lyrRasterName = allName.get('lyrRasterName')
            if lyrRasterName =="" :
                break
            
            srcDataPath = os.path.split(mxdPath)[0]        
            outMxdPath=os.path.join(outputPath,mxdName)
            
            #按行政区拆分shp数据,业务图层
            shpName=allName.get('lyrShpName')
            outShpPath =os.path.join(outputPath,shpName)
            arcpy.Clip_analysis(sourceData, fc,outShpPath)
            arcpy.AddMessage("clip OK")
            
            #复制源mxd目录下数据到目标目录下,以供下载
            #1.遍历模板文件夹,复制mxd和shp到临时目录
            #2.临时目录中,更新栅格数据源
            #3.修改标题、日期等
            #4.拼路径和文件名,输出专题图
            #===================================================================
            # arcpy.AddMessage(srcDataPath+outputPath)
            # CopyFiles(srcDataPath,outputPath)
            # arcpy.AddMessage(" Copy Files OK")
            # 
            # #替换工作目录,保证mxd能够打开
            # ReplaceWorkspace(mxdPath,srcDataPath,outputPath,outMxdPath,lyrRasterName)
            # ChangeTitle(outMxdPath,strTime)
            # arcpy.AddMessage("Replace Workspace OK")
            # 
            # #导出图片jpg格式
            # jpgName=allName.get('jpgName')
            # outPicPath =os.path.join( outputPath,jpgName)
            # ExportMap(outMxdPath,outPicPath)
            # arcpy.AddMessage("Export Map OK")    
            #===================================================================
    except Exception,e: 
        arcpy.AddError(e.message)
        return






''' 用于对栅格数据进行剪裁,
    参数一:栅格数据位置
    参数二:分割文件的文件路径
    参数三:输出路径'''
def SplitRasterProduct(sourceData,splitPath,RootPath,strTime=time.strftime(u"%Y%m%d%H",time.localtime()),proID="4028813442b61acd0142b6200e6f0002"):
    #测试ID
    #proID="4028813442b61acd0142b6200e6f0002"
    arcpy.env.overwriteOutput =True
    arcpy.CheckOutExtension("spatial")
    env.workspace = splitPath
    productType=sourceData.split("\\")[-1].split(".")[0] 
    fcList =arcpy.ListFeatureClasses()
    for fc in fcList:
        outputPath=CreateProductPath(strTime,RootPath,os.path.splitext(fc)[0])
        #outputPath= outputPath.encode('gbk').decode('utf-8')
        if outputPath[-1] == "\\":
            arcpy.gp.ExtractByMask_sa(sourceData, fc,outputPath+ strTime+".img")
            #Insert2ProductDB(os.path.splitext(fc)[0],proID,strTime,outputPath+ strTime+".img","","")
            arcpy.AddMessage( outputPath+os.path.splitext(fc)[0] +"_"+ strTime+".img" +"     OK")
        else:
           arcpy.gp.ExtractByMask_sa(sourceData, fc,outputPath+"\\"+ strTime+".img")
           #Insert2ProductDB(os.path.splitext(fc)[0],proID,strTime,outputPath+"\\"+ strTime+".img","","")
           arcpy.AddMessage( outputPath+os.path.splitext(fc)[0] +"_"+ strTime+".img" +"     OK")
    return True

''' 用于对矢量数据进行剪裁,
    参数一:矢量数据位置
    参数二:分割文件的文件路径
    参数三:输出路径'''
def SplitVectorProduct(sourceData,splitPath,RootPath,strTime,period):
    arcpy.env.overwriteOutput =True
    arcpy.CheckOutExtension("spatial")
    env.workspace = splitPath
    productType=sourceData.split("\\")[-1].split(".")[0] 
    fcList =arcpy.ListFeatureClasses()
    for fc in fcList:
        outputPath=CreateProductPath(strTime,RootPath,os.path.splitext(fc)[0],period)
        if not outputPath[-1] == "\\":
            outputPath =outputPath+"\\"
        arcpy.Clip_analysis(sourceData, fc,outputPath+ strTime+".shp","")
        arcpy.AddMessage( outputPath+ strTime+".shp"+"     OK")
        
    return True

'''
创建产品路径
strTime:产品时间,格式为yyyymmddhh24
RootPath:产品根目录
RegionID:行政编码
period:产品周期
 创建的目录不已   "\\"   结尾
'''
def CreateProductPath(strTime,RootPath,RegionID,period):
    if RootPath[-1] =="\\" or  RootPath[-1]=="/":
        productRootPath =str(RootPath)+"\\"+RegionID
    else:
        productRootPath =str(RootPath) +"\\"+ "\\"+RegionID
    if not os.path.exists(productRootPath):
        os.makedirs(productRootPath)
    return productRootPath

def DataStatis(rec_img,idtentityData,strTime,dstDBSource):
    if not os.path.exists("c:\\temp"):
        os.makedirs("c:\\temp")
    R2V="c:\\temp\\r2v.shp"
    identityResult="c:\\temp\\identity.shp"
    areaShp="c:\\temp\\areashp.shp"
    #转为polygon
    arcpy.RasterToPolygon_conversion(rec_img, R2V, "NO_SIMPLIFY", "VALUE")    
    arcpy.AddMessage( "Convert2Polygon  OK")
    #做identity
    arcpy.Identity_analysis(R2V, idtentityData, identityResult, "ALL", "", "NO_RELATIONSHIPS")
    arcpy.AddMessage( "Identity  OK")
    arcpy.CalculateAreas_stats(identityResult,areaShp)
    arcpy.AddMessage( "calculate area  OK")
    arcpy.AddField_management(areaShp, "ProTime", "TEXT", "", "", "12", "", "NON_NULLABLE", "NON_REQUIRED", "")
    arcpy.AddMessage( "Add Field OK")
    arcpy.CalculateField_management(areaShp, "ProTime", strTime, "PYTHON", "")
    arcpy.AddMessage( "cal product ID  OK")
    if arcpy.Exists(dstDBSource):
        arcpy.Append_management(areaShp, dstDBSource, "TEST", "", "")
    else:
        arcpy.AddMessage(u"目标数据库不存在!")
if __name__ == '__main__':
    #mxd存放根目录默认为d:\\gptools\\mxd
    mxdRootPath=arcpy.GetParameterAsText(0) 
    sourceData = arcpy.GetParameterAsText(1)
    splitPath =arcpy.GetParameterAsText(2)
    rootPath= arcpy.GetParameterAsText(3)
    strTime =arcpy.GetParameterAsText(4)
    if strTime =="" or strTime =="NONE":
        strTime =time.strftime(u"%Y%m%d%H",time.localtime())
    #mxdRootPath=u"D:\\GPTOOLS\\mxd\\150000\\11.mxd"
    #sourceData = r"D:\GPTOOLS\scratch\sdf1.shp"
    #splitPath =r"D:\GPTOOLS\ToolData\xzj"
    #rootPath=r"D:\GPTOOLS\Result\FireRating"
    #strTime="20141010"
    DistributeProduct(mxdRootPath,sourceData,splitPath,rootPath,strTime)
    

 

转载自:https://blog.csdn.net/qq_27690839/article/details/86639716

You may also like...

退出移动版