1. 程式人生 > 實用技巧 >13章程式碼

13章程式碼

13.1 獲得mxd中圖層資訊

#coding=utf8
import arcpy

import os
import sys
import math

def getDataFrameinfo(df):
    arcpy.AddMessage("{0:<20s}{1}".format("credits:",df.credits))
    arcpy.AddMessage("{0:<20s}{1}".format("description:",df.description))
    arcpy.AddMessage("{0:<20s}{1}".format("displayUnits:
",df.displayUnits)) arcpy.AddMessage("{0:<20s}{1}".format("elementHeight:",df.elementHeight)) arcpy.AddMessage("{0:<20s}{1}".format("elementPositionX:",df.elementPositionX)) arcpy.AddMessage("{0:<20s}{1}".format("elementPositionY: ",df.elementPositionY)) arcpy.AddMessage("{0:<20s}{1}
".format("elementWidth: ",df.elementWidth)) pextent=df.extent #範圍資訊 arcpy.AddMessage("Extent:\n XMin: {0}, XMax: {1}, YMin: {2}, YMax: {3}".format( pextent.XMin, pextent.XMax, pextent.YMin, pextent.YMax)) arcpy.AddMessage("{0:<20s}{1}".format("geographicTransformations: ",df.geographicTransformations)) arcpy.AddMessage(
"{0:<20s}{1}".format("mapUnits: ",df.mapUnits)) arcpy.AddMessage("{0:<20s}{1}".format("name: ",df.name)) arcpy.AddMessage("{0:<20s}{1}".format("referenceScale: ",df.referenceScale)) arcpy.AddMessage("{0:<20s}{1}".format("rotation: ",df.rotation)) if hasattr(df,"scale"): arcpy.AddMessage("{0:<20s}{1}".format("scale: ",df.scale)) arcpy.AddMessage("{0:<20s}{1}".format("time: ",df.time)) arcpy.AddMessage("{0:<20s}{1}".format("type: ",df.type)) def getmxdinfo(mxd): arcpy.AddMessage("{0:<20s}{1}".format("activeView: ",mxd.activeView)) arcpy.AddMessage("{0:<20s}{1}".format("author: ",mxd.author)) arcpy.AddMessage("{0:<20s}{1}".format("credits: ",mxd.credits)) arcpy.AddMessage("{0:<20s}{1}".format("dateExported: ",mxd.dateExported)) arcpy.AddMessage("{0:<20s}{1}".format("datePrinted: ",mxd.datePrinted)) arcpy.AddMessage("{0:<20s}{1}".format("dateSaved: ",mxd.dateSaved)) arcpy.AddMessage("{0:<20s}{1}".format("description: ",mxd.description)) arcpy.AddMessage("{0:<20s}{1}".format("filePath: ",mxd.filePath)) arcpy.AddMessage("{0:<20s}{1}".format("hyperlinkBase: ",mxd.hyperlinkBase)) arcpy.AddMessage("{0:<20s}{1}".format("isDDPEnabled: ",mxd.isDDPEnabled)) arcpy.AddMessage("{0:<20s}{1}".format("relativePaths: ",mxd.relativePaths)) arcpy.AddMessage("{0:<20s}{1}".format("summary: ",mxd.summary)) pageWidth, pageHeight = mxd.pageSize arcpy.AddMessage("{0:<20s}{1}".format("pageWidth: ",pageWidth)) arcpy.AddMessage("{0:<20s}{1}".format("pageHeight: ",pageHeight)) for df in arcpy.mapping.ListDataFrames(mxd): getDataFrameinfo(df) def Main(): if mxdfile=="": mxd = arcpy.mapping.MapDocument("CURRENT") else: mxd = arcpy.mapping.MapDocument(mxdfile) arcpy.AddMessage(mxdfile) getmxdinfo(mxd) mxdfile=arcpy.GetParameterAsText(0) Main()

13.2 獲得mxd資訊( 資料框和頁面資訊)

#coding=utf8
import arcpy

import os
import sys
import math

def getDataFrameinfo(df):
    arcpy.AddMessage("{0:<20s}{1}".format("credits:",df.credits))
    arcpy.AddMessage("{0:<20s}{1}".format("description:",df.description))
    arcpy.AddMessage("{0:<20s}{1}".format("displayUnits:",df.displayUnits))
    arcpy.AddMessage("{0:<20s}{1}".format("elementHeight:",df.elementHeight))
    arcpy.AddMessage("{0:<20s}{1}".format("elementPositionX:",df.elementPositionX))
    arcpy.AddMessage("{0:<20s}{1}".format("elementPositionY: ",df.elementPositionY))

    arcpy.AddMessage("{0:<20s}{1}".format("elementWidth: ",df.elementWidth))
    pextent=df.extent
    #範圍資訊
    arcpy.AddMessage("Extent:\n  XMin: {0}, XMax: {1}, YMin: {2}, YMax: {3}".format(
    pextent.XMin, pextent.XMax, pextent.YMin, pextent.YMax))
    arcpy.AddMessage("{0:<20s}{1}".format("geographicTransformations: ",df.geographicTransformations))
    arcpy.AddMessage("{0:<20s}{1}".format("mapUnits: ",df.mapUnits))
    arcpy.AddMessage("{0:<20s}{1}".format("name: ",df.name))
    arcpy.AddMessage("{0:<20s}{1}".format("referenceScale: ",df.referenceScale))
    arcpy.AddMessage("{0:<20s}{1}".format("rotation: ",df.rotation))
    if hasattr(df,"scale"):
        arcpy.AddMessage("{0:<20s}{1}".format("scale: ",df.scale))
    arcpy.AddMessage("{0:<20s}{1}".format("time: ",df.time))
    arcpy.AddMessage("{0:<20s}{1}".format("type: ",df.type))
def getGRADUATED_COLORS(lyr):
    arcpy.AddMessage("{0:<20s}{1}".format("valueField:",lyr.symbology.valueField))
    arcpy.AddMessage("{0:<20s}{1}".format("numClasses:",lyr.symbology.numClasses))

    BreakValues=lyr.symbology.classBreakValues
    for BreakValue in  BreakValues:
        arcpy.AddMessage("{0:<20s}{1}".format("BreakValue:",BreakValue))
def getUNIQUE_VALUES(lyr):
    arcpy.AddMessage("{0:<20s}{1}".format("valueField:",lyr.symbology.valueField))

    classValues=lyr.symbology.classValues
    for classValue in  classValues:
        arcpy.AddMessage("{0:<20s}{1}".format("classValue:",classValue))
def getlabel(lyr):
    for lblClass in lyr.labelClasses:
        if lblClass.showClassLabels:
            arcpy.AddMessage("{0:<20s}{1}".format("   Class Name:  ",lblClass.className))
            arcpy.AddMessage("{0:<20s}{1}".format("    Expression: ",lblClass.expression))
            arcpy.AddMessage("{0:<20s}{1}".format("    SQL Query:  ", lblClass.SQLQuery))

#刪除一個表的所有欄位
def delAllField(inFeature):
    try:

        fieldList = arcpy.ListFields(inFeature)
        for field in fieldList:
              if not (field.type=="Geometry" or field.type=="OID" or not field.editable):
                  arcpy.DeleteField_management(inFeature,field.name)
    except:
        pass


def getmxdinfo(mxd):
    arcpy.AddMessage("{0:<20s}{1}".format("activeView:       ",mxd.activeView))
    arcpy.AddMessage("{0:<20s}{1}".format("author:       ",mxd.author))
    arcpy.AddMessage("{0:<20s}{1}".format("credits:       ",mxd.credits))
    arcpy.AddMessage("{0:<20s}{1}".format("dateExported:       ",mxd.dateExported))
    arcpy.AddMessage("{0:<20s}{1}".format("datePrinted:       ",mxd.datePrinted))
    arcpy.AddMessage("{0:<20s}{1}".format("dateSaved:       ",mxd.dateSaved))
    arcpy.AddMessage("{0:<20s}{1}".format("description:       ",mxd.description))
    arcpy.AddMessage("{0:<20s}{1}".format("filePath:       ",mxd.filePath))
    arcpy.AddMessage("{0:<20s}{1}".format("hyperlinkBase:       ",mxd.hyperlinkBase))
    arcpy.AddMessage("{0:<20s}{1}".format("isDDPEnabled:       ",mxd.isDDPEnabled))
    arcpy.AddMessage("{0:<20s}{1}".format("relativePaths:       ",mxd.relativePaths))
    arcpy.AddMessage("{0:<20s}{1}".format("summary:       ",mxd.summary))
    pageWidth, pageHeight = mxd.pageSize
    arcpy.AddMessage("{0:<20s}{1}".format("pageWidth:       ",pageWidth))
    arcpy.AddMessage("{0:<20s}{1}".format("pageHeight:       ",pageHeight))
    for df in arcpy.mapping.ListDataFrames(mxd):
        #getDataFrameinfo(df)
        arcpy.AddMessage("============{0:<20s}{1}============".format("name: ",df.name))
        for lyr in arcpy.mapping.ListLayers(mxd, "",df):
            arcpy.AddMessage("{0:<20s}{1}".format("name:",lyr.name))
            if not lyr.isBroken:#是否壞了
                if hasattr(lyr,"brightness"):
                    arcpy.AddMessage("{0:<20s}{1}".format("brightness:",lyr.brightness))
                if hasattr(lyr,"contrast"):
                    arcpy.AddMessage("{0:<20s}{1}".format("contrast:",lyr.contrast))
                if hasattr(lyr,"credits"):
                    arcpy.AddMessage("{0:<20s}{1}".format("contrast:",lyr.credits))
                if hasattr(lyr,"datasetName"):
                    arcpy.AddMessage("{0:<20s}{1}".format("datasetName:",lyr.datasetName))
                if hasattr(lyr,"dataSource"):
                    arcpy.AddMessage("{0:<20s}{1}".format("dataSource:",lyr.dataSource))

                if hasattr(lyr,"definitionQuery"):
                    arcpy.AddMessage("{0:<20s}{1}".format("definitionQuery:",lyr.definitionQuery))
                if hasattr(lyr,"description"):
                    arcpy.AddMessage("{0:<20s}{1}".format("description:",lyr.description))
                if hasattr(lyr,"isFeatureLayer"):
                    arcpy.AddMessage("{0:<20s}{1}".format("isFeatureLayer:",lyr.isFeatureLayer))
                    if lyr.isFeatureLayer:
                        pass
                        #delAllField(lyr)

                if hasattr(lyr,"isGroupLayer"):
                    arcpy.AddMessage("{0:<20s}{1}".format("isGroupLayer:",lyr.isGroupLayer))
                if hasattr(lyr,"isRasterLayer"):
                    arcpy.AddMessage("{0:<20s}{1}".format("isRasterLayer:",lyr.isRasterLayer))
                if hasattr(lyr,"longName"):
                    arcpy.AddMessage("{0:<20s}{1}".format("longName:",lyr.longName))
                if hasattr(lyr,"maxScale"):
                    arcpy.AddMessage("{0:<20s}{1}".format("maxScale:",lyr.maxScale))

                if hasattr(lyr,"minScale"):
                    arcpy.AddMessage("{0:<20s}{1}".format("minScale:",lyr.minScale))
                if hasattr(lyr,"isRasterLayer"):
                    arcpy.AddMessage("{0:<20s}{1}".format("isRasterLayer:",lyr.isRasterLayer))
                if hasattr(lyr,"showLabels"):
                    arcpy.AddMessage("{0:<20s}{1}".format("showLabels:",lyr.showLabels))
                    if lyr.showLabels:
                        getlabel(lyr)

                if hasattr(lyr,"transparency"):
                    arcpy.AddMessage("{0:<20s}{1}".format("transparency:",lyr.transparency))
                if hasattr(lyr,"visible"):
                    arcpy.AddMessage("{0:<20s}{1}".format("visible:",lyr.visible))
                if hasattr(lyr,"workspacePath"):
                    arcpy.AddMessage("{0:<20s}{1}".format("workspacePath:",lyr.workspacePath))
                if hasattr(lyr,"symbologyType"):
                    arcpy.AddMessage("{0:<20s}{1}".format("symbologyType:",lyr.symbologyType))
                    if lyr.symbologyType=="GRADUATED_COLORS":
                        getGRADUATED_COLORS(lyr)
                    elif lyr.symbologyType=="UNIQUE_VALUES":
                        getUNIQUE_VALUES(lyr)

def Main():

    if mxdfile=="":
        mxd = arcpy.mapping.MapDocument("CURRENT")
    else:
        mxd = arcpy.mapping.MapDocument(mxdfile)


    arcpy.AddMessage(mxdfile)
    getmxdinfo(mxd)
mxdfile=arcpy.GetParameterAsText(0)

Main()

13.4 批量mxd匯出圖片

import arcpy
import os
import re

from os.path import join, getsize

def getFile(filepath,ext):
    arcpy.env.workspace = filepath
    return arcpy.ListFiles("*"+ext)
def getmxdfile(workspace,ext):#獲得一個資料夾只能副檔名的所有檔案
    FileList=[]
    for dirpath, dirnames, filenames in os.walk(workspace):#獲得所有的子資料夾
        for filename in filenames:
            #arcpy.AddMessage("filename=="+filename)

            if filename.lower().endswith(ext):
                fullfile=os.path.join(dirpath, filename)
                arcpy.AddMessage(fullfile)
                FileList.append(fullfile)
    return FileList

inpath  = arcpy.GetParameterAsText(0)
outfile = arcpy.GetParameterAsText(1).upper()
mydpi =   arcpy.GetParameter(2)
mydir = inpath
a=getmxdfile(mydir,".mxd")

for b in a:
    arcpy.AddMessage(b)
    mxd = arcpy.mapping.MapDocument(b)
    #arcpy.AddMessage("mxd="+str(mxd))
    jpg=b.replace('.mxd',outfile)
    arcpy.AddMessage("pic:"+jpg)
    try:
          if outfile==".JPG":
            arcpy.mapping.ExportToJPEG(mxd, jpg,resolution=mydpi)
          elif outfile==".TIF":
            arcpy.mapping.ExportToTIFF(mxd, jpg,resolution=mydpi)
          elif outfile==".PDF":
            arcpy.mapping.ExportToPDF(mxd, jpg,resolution=mydpi,convert_markers=True)
          elif outfile==".PNG":
            arcpy.mapping.ExportToPNG(mxd, jpg,resolution=mydpi)
          elif outfile==".EMF":
            arcpy.mapping.ExportToEMF(mxd, jpg,resolution=mydpi)
          else:
            arcpy.mapping.ExportToPDF(mxd, jpg,resolution=mydpi)
    except Exception as e:
          print e.message
          arcpy.AddError(e.message)
    del mxd

13.5 地圖視窗轉到XY

#coding=utf8

import arcpy
import os
import types
import string

def getCount(inFeature):
    result = arcpy.GetCount_management(inFeature)
    count= int(result.getOutput(0))
    return count
def getwhereCount(inFeature,wherestr):
    my_temp="my_temp" #臨時資料

    arcpy.MakeFeatureLayer_management(inFeature,my_temp,wherestr)
    return getCount(my_temp)
def FieldExists(TableName,FieldName):
    desc = arcpy.Describe(TableName)
    for field in desc.fields:
        if field.Name.upper() ==FieldName:
            return True
            break
    return False

def getOIDField(jfb_Select):
    desc = arcpy.Describe(jfb_Select)
    OIDField=desc.OIDFieldName
    return OIDField

def initProgress(hint,num):
    arcpy.SetProgressor("step", u"正在"+hint,0,num,1)
def step():
    arcpy.SetProgressorLabel(u"正在進行....")
    arcpy.SetProgressorPosition()
def freeProgress():
    arcpy.ResetProgressor()
def is_number(str):
    try:
        # 因為使用float有一個例外是'NaN'
        if str=='NaN':
            return False
        float(str)
        return True
    except ValueError:
        return False

#必須是u型別==================u====================
def dmstod(dms):
    #arcpy.AddMessage("================================="+dms+"==============================")
    try:
        p = dms.find('°')
        if p<0:
            return str(dms)
        #arcpy.AddMessage("p="+str(p))
        d=string.atof(dms[0:p].strip())
        #arcpy.AddMessage("d="+str(d))
        p1=dms.find('')
        #arcpy.AddMessage("p1="+str(p1))
        if p1<0:
             p1=dms.find("'")

        f=0 #
        if p1>0:
            f=string.atof(dms[p+1:p1].strip())
        else:
            p1=p
        #arcpy.AddMessage("f="+str(f))

        p2=dms.find('')
        if p2<0:
             p2=dms.find('"')
        #arcpy.AddMessage("p2="+str(p2))

        s=0 #
        if p2>0:
            s=string.atof(dms[p1+1:p2].strip())
        #arcpy.AddMessage("s="+str(s))

        return d+f/60+s/3600
    except ValueError:
        return None
#獲得一個點的投影座標系
def getpjxy(gx,gy,sr,GCSsr):
    point = arcpy.Point()
    point.X = gx
    point.Y = gy

    pointGeometry = arcpy.PointGeometry(point,GCSsr)
    newpointgeo=  pointGeometry.projectAs(sr)
    p1=newpointgeo.firstPoint
    return p1.X,p1.Y
def main():
    isdms=False
    if is_number(x):
        xd= float(x)
    else:
        isdms=True
        xd=dmstod(u""+x)
        if xd==None:
            arcpy.AddError(u"輸入x={0}不是有效的數字".format(x))
            return
        if xd>180 or xd<-180:
            arcpy.AddError(u"輸入x={0}不是有效的數字".format(x))
            return


    if is_number(y):
        yd= float(y)
    else:
        isdms=True
        yd=dmstod(u""+y)
        if yd==None:
            arcpy.AddError(u"輸入y={0}不是有效的數字".format(y))
            return
        if yd>90 or y<-90:
            arcpy.AddError(u"輸入y={0}不是有效的數字".format(y))
            return

    mxd = arcpy.mapping.MapDocument("CURRENT")
    df=mxd.activeDataFrame
    if df.scale!=scale:
        df.scale=scale
        arcpy.RefreshActiveView()

    sr=df.spatialReference
    if sr.name == "Unknown":
        arcpy.AddError("資料框請"+"定義座標系,沒有定義座標!")
        return

    pextent=df.extent
    h=pextent.height
    w=pextent.width
    GCSsr=sr.GCS
    if GCSsr.factoryCode!=sr.factoryCode: #不是地理座標系
        if isdms==True:#是度分秒
            xd,yd=getpjxy(xd,yd,sr,GCSsr)
        elif xd>-180 and xd<180 and yd>-90 and yd<90:
            xd,yd=getpjxy(xd,yd,sr,GCSsr)
   #定義範圍
    pextent.XMin, pextent.YMin = xd-w/2, yd-h/2
    pextent.XMax, pextent.YMax =  xd+w/2, yd+h/2
    df.extent = pextent

    arcpy.RefreshActiveView()

x = arcpy.GetParameterAsText(0) #x
y= arcpy.GetParameterAsText(1) #y
scale=arcpy.GetParameter(2)

main()

13.6 固定比例尺列印

#coding=utf8
import arcpy

import os
import sys
import math

def getmxdinfo(mxd):
    pageWidth, pageHeight = mxd.pageSize
    aDataFrame=mxd.activeDataFrame
    aDataFrame.elementPositionX=0
    aDataFrame.elementPositionY=0
    aDataFrame.elementHeight=pageHeight
    aDataFrame.elementWidth=pageWidth
    lyr = arcpy.mapping.ListLayers(mxd, "dltb", aDataFrame)[0]
    desc = arcpy.Describe(lyr)
    aDataFrame.panToExtent(desc.extent)
    aDataFrame.scale=10000  #固定1:10000比例尺
    arcpy.RefreshActiveView()
    mxd.saveACopy(outfile)

def Main():

    if mxdfile=="":
        mxd = arcpy.mapping.MapDocument("CURRENT")
    else:
        mxd = arcpy.mapping.MapDocument(mxdfile)
    arcpy.AddMessage(mxdfile)

    getmxdinfo(mxd)
mxdfile=arcpy.GetParameterAsText(0)
outfile=arcpy.GetParameterAsText(1)

Main()

13.7 mxd文件相對路徑和無效資料檢查

import arcpy
import os
import re

from os.path import join, getsize
def initProgress(hint,num):
    arcpy.SetProgressor("step", u"正在"+hint,0,num,1)
def step():
    arcpy.SetProgressorLabel(u"正在進行....")
    arcpy.SetProgressorPosition()
def freeProgress():
    arcpy.ResetProgressor()
def getmxdfile(workspace,ext):
    FileList=[]
    for dirpath, dirnames, filenames in os.walk(workspace):
        for filename in filenames:
            #arcpy.AddMessage("filename=="+filename)

            if filename.lower().endswith(ext.lower()):
                fullfile=os.path.join(dirpath, filename)
                arcpy.AddMessage(fullfile)
                FileList.append(fullfile)
    return FileList

inpath  = arcpy.GetParameterAsText(0)
setrel  = arcpy.GetParameter(1) #相對路徑設定
mydir = inpath
a= getmxdfile(mydir,".mxd")
num=len(a)

initProgress(u"檢查",num)
for b in a:
      step()
      arcpy.AddMessage(b)
      try:
          mxd = arcpy.mapping.MapDocument(b)
          if mxd is None:
              arcpy.AddMessage(u"mxd="+b+u",版本太高,無法開啟")
              continue
          if not mxd.relativePaths:#不是相對路徑
            arcpy.AddMessage(u"mxd="+b+u",不是相對路徑")
            if setrel:#儲存相對路徑
                mxd.save()
          for df in arcpy.mapping.ListDataFrames(mxd):
                for lyr in arcpy.mapping.ListLayers(mxd,"",df):
                      if hasattr(lyr, 'dataSource'):
                            dataSource=lyr.dataSource
                            if lyr.isBroken:#是否損壞
                                arcpy.AddMessage(u"圖層"+lyr.name+",壞了")
                                
                            if not arcpy.Exists(dataSource):#是否存在
                                  arcpy.AddMessage(u"圖層"+lyr.name+u"對應的資料來源:'"+dataSource+u"'無效")

                            print lyr.name
          if mxd:
                del mxd
      except Exception as e:
          print e.message
          # If using this code within a script tool, AddError can be used to return messages
          #   back to a script tool.  If not, AddError will have no effect.
          arcpy.AddError(e.message)
freeProgress()