所用软件:Enterprise 10.7.1 ArcMap10.7.1 JS API:4.12
前期准备:
许可:Network Analyst许可
数据:Server自带样例数据,位于 <ArcGIS Server 安装目录>\help\samples\data\network_analyst\SanFrancisco.gdb
工程文件:ArcMap用mxd文档
用Python脚本发网络分析服务(ArcMap版)
注:因为Network属于扩展模块,因此在python代码中需要有检查许可、借出许可,归还许可的步骤,同时,server也需要具备Network Analyst才能发布成功。详见代码
# -*- coding: utf-8 -*-
#!/usr/bin/python
import arcpy
from arcpy import env
import xml.dom.minidom as DOM
import os
# 检查许可
import arcpy
class LicenseError(Exception):
pass
try:
if arcpy.CheckExtension("Network") == "Available":
arcpy.CheckOutExtension("Network") #如果许可存在,则需要借出许可
else:
raise LicenseError
env.workspace = "E:/07blog/networkAnalyst/"
wrkspc = "E:/07blog/networkAnalyst/"
out_name = 'arcgis on aj.enterprise.cn_6443 (admin).ags'
# 将mxd文档变为服务定义草稿(.sddraft)文件,服务定义草稿文件会在服务定义文件(sd)后自动删除
mapDoc = arcpy.mapping.MapDocument(wrkspc + 'newwork.mxd')
service_name = 'networkAnalystFromPython'
sddraft = wrkspc + service_name + '.sddraft'
sd = wrkspc + service_name + '.sd'
summary = 'blog use sd'
tags = 'networkAnalyst,map,sd'
con = wrkspc + out_name
print("准备生成服务定义……")
analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service_name, 'ARCGIS_SERVER',
con, True, 'blog', summary, tags)
# 用DOM读取以xml的形式读取sddraft文件
doc = DOM.parse(sddraft)
print("准备修改服务定义草稿文件内容……")
# 关闭KmlServer
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
if typeName.firstChild.data == 'KmlServer':
extension = typeName.parentNode
for extElement in extension.childNodes:
if extElement.tagName == 'Enabled':
extElement.firstChild.data = 'false'
print("KmlServer已关闭……")
natypeNames = doc.getElementsByTagName('TypeName')
for natypeName in natypeNames:
if natypeName.firstChild.data == 'NAServer':
naextension = natypeName.parentNode
for naextElement in naextension.childNodes:
if naextElement.tagName == 'Enabled':
naextElement.firstChild.data = 'true'
print ("NAServer已开启")
# 重新生成服务定义草稿文件
outXml = wrkspc + service_name + '.sddraft'
if os.path.exists(outXml):
os.remove(outXml)
newFile = open(outXml, 'w')
doc.writexml(newFile)
newFile.close()
analysis = arcpy.mapping.AnalyzeForSD(outXml)
print ("重新分析……")
for key in ('messages', 'warnings', 'errors'):
print "----" + key.upper() + "-----"
vars = analysis[key]
for ((message, code), layerlist) in vars.iteritems():
print " ", message, " (CODE %i)" % code
print " applies to:",
for layer in layerlist:
print layer.name
del newFile, doc, mapDoc
# 分析完成,没有错误,准备发服务
if analysis['errors'] == {}:
arcpy.StageService_server(outXml, sd)
arcpy.UploadServiceDefinition_server(sd, con)
arcpy.SignOutFromPortal_server()
else:
print analysis['errors']
arcpy.CheckInExtension("Network") #用完要记得及时归还许可
except LicenseError:
print("Network Analyst license is unavailable")
except arcpy.ExecuteError:
print(arcpy.GetMessages(2))
用Python脚本发网络分析服务(ArcGIS Pro版)