陪伴本人反复实战的python(2.7和3.9版本均可用)及arcpy包组织编程脚本模板,包含:
1)程序除错调试与异常处理;
2)文件读取与目录组织管理;
3)列表与元组,函数设计。
头部说明及目录组织,logging包的使用,可按需取消注释,第18、19行修改为自己新建的保存信息txt路径:
# -*- coding:utf-8 -*-
# ---------------------------------------------------------------------------
# Author: LGZ
# Created on:
# Reference:
# coding:cp936 or coding:utf-8
# ---------------------------------------------------------------------------
import logging, os, pprint
import pandas as pd
import numpy as np
# import arcpy
# arcpy.env.overwriteOutput = True
# import itertools, random, math
# 修改为自己新建的保存信息txt路径
errfile = r"C:\ArcGISPro\bin\Python\ErrorRecord\ex.txt"
loggingfile = r"C:\ArcGISPro\bin\Python\ErrorRecord\lg.txt"
# logging.disable(logging.CRITICAL) #禁用CRITICAL级别以下的日志记录
# 按此格式显示DEBUG级别以上的日志记录
# logging.basicConfig(filename=loggingfile, level=logging.DEBUG, format="%(asctime)s-%(levelname)s-%(message)s")
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s-%(levelname)s-%(message)s")
# pprint.pformat函数只能输入一个参数,logprint(*shape)中*shape为元组,将元组放进pprint.pformat
def logprint(*shape):
return logging.debug(pprint.pformat(shape))
# file =
# if os.path.isfile(file): # 判断文件是否已存在,已存在则删除
# os.unlink(file)
# if os.path.dirname(file) == "" : # 判断是否没有完整路径
# file = os.getcwd()+"//"+file # 如没有则连接工作目录制造完整路径
# file_list=os.listdir(file) # 根据需要的文件类型获取目录下文件名列表
# file_list=[i for i in file_list if i.endswith("xlsx") and \
# not i.startswith("~$")]
# save_fold =
# os.makedirs(save_fold, exist_ok=True) # 根据文件夹是否已存在制造文件夹
尾部运行程序(单独使用时)及断言设计、程序除错与异常处理,在# TODO行下编写自己的内容块,第23、24、29行为arcgpy信息块,可根据需要取消注释:
if __name__ == '__main__':
"""脚本单独使用时运行以下内容"""
"""----------------------------------------------"""
"""---------------------PARA---------------------"""
try:
logprint("start of program")
# TODO
# assert a != 0, "a不能为0"
# raise Exception("XX")
except Exception as ex:
# If an error occurred, print line number and error message
import traceback
import sys
tb = sys.exc_info()[2]
print(u"捕获到的异常信息是:{}".format(ex)) # 或者使用print("捕获到的异常信息是:",ex.args[0]或者str(ex)或者直接ex);3.9版本ex.message已不可用)
print(u"捕获到的异常代码行号是:Line {0}".format(tb.tb_lineno))
print(traceback.format_exc()) # 显示完整错误路径
with open(errfile, "a") as err:
err.write(traceback.format_exc())
print(u"将traceback信息写入文件成功")
# except arcpy.ExecuteError:
# print(arcpy.GetMessages())
# 无错误运行else后代码
else:
logprint("program success")
# arcpy.AddMessage("program success")
# 有没有错误均运行finally后代码
finally:
pass
总体:
# -*- coding:utf-8 -*-
# ---------------------------------------------------------------------------
# Author: LGZ
# Created on:
# Reference:
# coding:cp936 or coding:utf-8
# ---------------------------------------------------------------------------
import logging, os, pprint
import pandas as pd
import numpy as np
# import arcpy
# arcpy.env.overwriteOutput = True
# import itertools, random, math
# 修改为自己新建的保存信息txt路径
errfile = r"C:\ArcGISPro\bin\Python\ErrorRecord\ex.txt"
loggingfile = r"C:\ArcGISPro\bin\Python\ErrorRecord\lg.txt"
# logging.disable(logging.CRITICAL) #禁用CRITICAL级别以下的日志记录
# 按此格式显示DEBUG级别以上的日志记录
# logging.basicConfig(filename=loggingfile, level=logging.DEBUG, format="%(asctime)s-%(levelname)s-%(message)s")
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s-%(levelname)s-%(message)s")
# pprint.pformat函数只能输入一个参数,logprint(*shape)中*shape为元组,将元组放进pprint.pformat
def logprint(*shape):
return logging.debug(pprint.pformat(shape))
# file =
# if os.path.isfile(file): # 判断文件是否已存在,已存在则删除
# os.unlink(file)
# if os.path.dirname(file) == "" : # 判断是否没有完整路径
# file = os.getcwd()+"//"+file # 如没有则连接工作目录制造完整路径
# file_list=os.listdir(file) # 根据需要的文件类型获取目录下文件名列表
# file_list=[i for i in file_list if i.endswith("xlsx") and \
# not i.startswith("~$")]
# save_fold =
# os.makedirs(save_fold, exist_ok=True) # 根据文件夹是否已存在制造文件夹
if __name__ == '__main__':
"""脚本单独使用时运行以下内容"""
"""----------------------------------------------"""
"""---------------------PARA---------------------"""
try:
logprint("start of program")
# TODO
# assert a != 0, "a不能为0"
# raise Exception("XX")
except Exception as ex:
# If an error occurred, print line number and error message
import traceback
import sys
tb = sys.exc_info()[2]
print(u"捕获到的异常信息是:{}".format(ex)) # 或者使用print("捕获到的异常信息是:",ex.args[0]或者str(ex)或者直接ex);3.9版本ex.message已不可用)
print(u"捕获到的异常代码行号是:Line {0}".format(tb.tb_lineno))
print(traceback.format_exc()) # 显示完整错误路径
with open(errfile, "a") as err:
err.write(traceback.format_exc())
print(u"将traceback信息写入文件成功")
# except arcpy.ExecuteError:
# print(arcpy.GetMessages())
# 无错误运行else后代码
else:
logprint("program success")
# arcpy.AddMessage("program success")
# 有没有错误均运行finally后代码
finally:
pass
欢迎使用,如发现问题欢迎指正,评论,需求和交流扣775915005