Combination of GIS and Python

Author : admin   2023-03-29 13:47:45 Browse: 912

Abstract: 1.Common GIS packages in Python The first is the commonly used GIS packages in Python, which mainly include the following categori...

1.Common GIS packages in Python

The first is the commonly used GIS packages in Python, which mainly include the following categories:

Order number
Name
Function
1
GDAL
Basic package for vector and raster data processing, worthy of the name N0.1
2
GeoPandas
Added excuses for manipulating geospatial data based on Pandas
3
Pyproj
Projection transformation
4
Pysal
Spatial Analysis Function Library
5
Rasterio
Spatial Grid Library Based on GDAL
6
Cartopy
Map Drawing Package
7
Rtree
Spatial index
8
ArcPy
A python package that requires ArcGIS licensing, a python package that can solve most GIS problems, and a nearly omnipotent package

2.Python in ArcGIS

Python in ArcGIS mainly includes ArcPy and ArcGIS API for Python. ArcPy mainly operates ArcMap or ArcGIS Pro desktop processing tools through Python, providing many functions and classes for processing and querying GIS data. There are both 2. x and 3. x versions in the ArcGIS system. The ArcGIS API for Python is mainly used to manage and use spatial resources on the Web side, and to achieve GIS data visualization and analysis, spatial data management, user management, etc. on the Web side.

Here, ArcPy is mainly used:

(1)Arcpy core module

  • ArcPy Main Module: It is mainly used to provide basic geographical objects, operate GP tools, and perform basic geographical operations, such as obtaining attributes, listing data, etc.

  • Data Access Module: Arcpy.da, used for basic data access and editing, provides cursor functions, and so on.

  • Drawing module: Arcpy.mapping or arcpy.mp for drawing

  • Spatial Analysis Extension Module: Arcpy.sa, using the GP tool in the spatial analysis extension module

  • Network Analysis Extension Module: Arcpy.na, used to use GP tools in the network analysis extension module

(2)Common Classes

Common Classes

(3)Common Functions

  • Cursor: SearchCursor、InsertCursor、UpdateCursor

  • Describe: Description data, which can return multiple attributes, such as data type, field, projection information, etc

  • ListXXX: Traversing data such as feature classes and grids

  • Calling the GP tool: Calling existing GP tools, such as overlay analysis, clipping, and buffering, results in different function names.

3.Usage

  • Field Calculator

  • Geographic processing column

Geographic Processing Bar

  • Standalone scripts .py format, running directly through the python compiler.

  • GP Tools

Packaging Python scripts as GeoProcessing tools.

GP Tools

4.Example

(1)SDE automatic backup

 1# -*- coding: utf-8 -*-
 2import arcpy
 3from arcpy import env
 4import datetime
 5import re 
 6env.overwriteOutput = True
 7
 8
 9import sys
10reload(sys)
11sys.setdefaultencoding('utf-8')                                             #Solution Coding problem
12
13
14def copy_feature(out_path):                                         #Copy the feature dataset into gdb
15  for fc in featureclasses:
16    if re.match("SDE", str(fc)):
17      print  "Copy Feature Class:{0}".format(str(fc))
18      arcpy.FeatureClassToFeatureClass_conversion(fc, out_path, str(fc).split(".")[-1])
19    else:
20      print str(fc) + "Not a feature class"
21
22if __name__ == '__main__':
23  in_path = "F:\\192.168.1.200.sde"                      #sde Connection file
24  out_path = "F:\\backup\\backup.gdb"                    # route
25
26  env.workspace = in_path
27  print "Start traversing the database:{0}".format(arcpy.env.workspace.split("\\")[-1])   #Start traversing the database
28  featureclasses = arcpy.ListFeatureClasses()                #Traversing feature classes
29  copy_feature(out_path)                          #Copy Feature Class
30
31  datasets = arcpy.ListDatasets("", "Feature")              #Feature Datasets
32  for ds in datasets:
33    print "Start traversing the dataset:{0}".format(str(ds))
34    desc_ds = arcpy.Describe(ds)
35    dataset_out_name = str(ds).split(".")[-1]              #Get the name of the feature dataset
36    sr = desc_ds.SpatialReference                    #Obtain the reference system of the original feature dataset
37    out_path2 = out_path + "\\" + dataset_out_name  
38    print "Creating Feature Datasets:{0}".format(dataset_out_name)
39    arcpy.CreateFeatureDataset_management(out_path, dataset_out_name, sr)
40                                      #Creating Feature Datasets
41    featureclasses = arcpy.ListFeatureClasses(feature_dataset = ds)    #Reading Feature Classes in a Feature Dataset
42    copy_feature(out_path2)
43
44
45  print "Backup ended......"

(2)Batch cutting

 1import sys,string,os 
 2import arcpy
 3dir="E:/raster/clip"
 4files = os.listdir(dir)
 5for f in files:
 6    if os.path.splitext(f)[1]==".tif":
 7         Input_raster_file = dir + os.sep + f
 8         maskdata = "E:/raster/clip/shp/cd.shp"
 9         Raster_Format = "TIFF"
10         basename = os.path.splitext(f)[0]
11         workspace = "E:/raster/clip/results"
12         Output_raster = workspace + os.sep + basename +"_clip" + ".tif"         
13         arcpy.Clip_management(Input_raster_file, None, Output_raster, maskdata, None, 'ClippingGeometry', 'MAINTAIN_EXTENT')
14         print (Output_raster)

(3)Batch Publishing Service

 1# -*- coding: utf-8 -*-  
 2import arcpy
 3import os
 4
 5import sys
 6reload(sys)
 7sys.setdefaultencoding('utf-8')                                             #Resolve coding issues
 8
 9
10#mxd Folder Path
11wrkspc = "C:\\Users\\wbg\\Desktop\\mxd"
12#An .ags file connected to a GIS server
13con = "C:\\Users\\wbg\\AppData\\Roaming\\ESRI\\Desktop10.6\\ArcCatalog\\arcgis on 192.168.1.200_6443 (system administrator).ags"
14#The folder name of the publishing server, such as publishing to root, is empty
15folder_name = "test" 
16
17def PublishAll(wrkspc):  
18    print "Check folder path……"  
19    if os.path.isdir(wrkspc) == False:  
20        print "The folder path entered is invalid!"  
21        return  
22    print "traverse folder……"  
23    files = os.listdir(wrkspc)  
24    for f in files:  
25        if f.endswith(".mxd"):  
26            mxdPath = os.path.join(wrkspc, f)  
27            sddraft=f.split(".")[0]
28            print "publishing: " + mxdPath  
29            Createmapsddraft(sddraft, mxdPath)  
30        else:  
31            continue  
def Createmapsddraft(sddraft,mxdPath):
35
36    mapDoc = arcpy.mapping.MapDocument(mxdPath)
37    out_sddraft = wrkspc + sddraft + '.sddraft'
38    sd = wrkspc + sddraft + '.sd'
39    summary = sddraft
40    #tags = 'snadiao, erdiao'
41    # create service definition draft
42    if folder_name:
43        arcpy.mapping.CreateMapSDDraft(mapDoc, out_sddraft, sddraft, 'ARCGIS_SERVER', 
44                                                  con, False, folder_name, summary, None)
45    else:
46
47        arcpy.mapping.CreateMapSDDraft(mapDoc, out_sddraft, sddraft, 'ARCGIS_SERVER', 
48                                              con, False, None, summary, None)
49
50
51    analysis = arcpy.mapping.AnalyzeForSD(out_sddraft)
52    # stage and upload the service if the out_sddraft analysis did not contain errors
53    if analysis['errors'] == {}:
54
55        if os.path.exists(sd): os.remove(sd)
56        # Execute StageService
57        arcpy.StageService_server(out_sddraft, sd)
58        # Execute UploadServiceDefinition
59        arcpy.UploadServiceDefinition_server(sd, con)
60    else: 
61        # if the sddraft analysis contained errors, display them
62        print analysis['errors']        
63
64
65PublishAll(wrkspc)
66

(4)ArcPy + Rest API

 1# -*- coding: utf-8 -*-
 2#Statistical Service Request Information
 3
 4import httplib, urllib, urllib2, json
 5import time, uuid
 6import sys, os
 7import getpass
 8import csv
 9
10def main(argv = None):
11  print "Statistics of site service request information......"
12
13  userName = raw_input("Enter user name:")
14  password = getpass.getpass("Enter password:")
15
16  serverName = raw_input("Enter server name (IP):")
17  serverPort = 6080   #10.7Starting from the default, 6443 port is enabled, which needs to be set, and supports both 443 and 80 ports
18
19  fromTime = 0
20  while fromTime == 0:
21    fromTime =raw_input("Start date of total requests in YYYY-MM-DD HH:MM format (e.g. 2014-05-10 14:00): ")
22    try:
23      fromTime = int(time.mktime(time.strptime(fromTime, '%Y-%m-%d %H:%M'))*1000)
24    except:
25      print ("Unable to parse input. Ensure date and time is in YYYY-MM-DD HH:MM format.")
26      fromTime = 0
27
28  toTime = 0
29  while toTime == 0:
30    toTime = raw_input("End date of total requests in YYYY-MM-DD HH:MM format (e.g. 2014-05-10 18:00): ")
31    try:
32      toTime = int(time.mktime(time.strptime(toTime, '%Y-%m-%d %H:%M'))*1000)
33    except:
34      print("Unable to parse input. Ensure date and time is in YYYY-MM-DD HH:MM format.")
35      toTime = 0
Label :
    Sign in for comments!
Comment list (0)

Powered by TorCMS (https://github.com/bukun/TorCMS).