当我执行以下代码时,它在“ finally”语句上失败。它指示在分配之前已引用“ os”。但是,一旦os确认代码文件为 main ,就会在代码的开头导入。我不明白为什么它认为“ os”未被引用。任何帮助将不胜感激。
#----------------------------------------------------------------------------
# Name: ESAR Data Extract
# Purpose: To download the esar data and reformat it into a structure
# that can be converted into a featureclass or SHP file.
#
# Author: shawn.keizer
#
# Created: 28/07/2015
# Modified: 14/06/2019
# Copyright: (c) Government of Alberta 2019
#------------------------------------------------------------------------
def wrtprj(location, name, text):
"""Requires a location to store and the name of the file, also requires the text to write to the file."""
txt = open(location + os.sep + name + ".prj", "w")
txt.write(text)
txt.close()
def email(txt, toaddrs = ['shawn.keizer@gov.ab.ca']):
"""Emails the string in 'txt' to the list of email addresses in 'toaddrs'.
Currently setup for error reporting."""
import smtplib
fromaddr = 'yourerrorreports@gmail.com'
msg = 'Subject: %s\n\n%s' % ("Error Report on: " + os.path.basename(__file__) , txt)
username = 'yourerrorreports@gmail.com'
password = 'Alberta01'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
for add in toaddrs:
server.sendmail(fromaddr, add, msg)
server.quit()
def prt(string):
"""Takes a string value as an input."""
print "... " + string + "\n"
def timer():
"""returns current time in seconds"""
import time
return time.time()
def main():
try:
#setting up environment settings and variables
env.overwriteOutput = True
env.workspace = os.path.dirname(os.path.realpath(__file__))
ws = env.workspace
x=0
dict={}
#Downloading the ESAR file from the FTP
prt("Downloading the ESAR Data from the FTP site")
testfile = urllib.URLopener()
testfile.retrieve('ftp://ftp.gov.ab.ca/env/ESAR/CompleteEsaSiteList.csv', 'CompleteEsaSiteList.csv')
#Reading Esar Data from the CSV File and writing to a dictionary
with open('CompleteEsaSiteList.csv', 'rb') as f:
reader = csv.reader(f)
prt("Reading Esar Data from the CSV File")
next(reader)
next(reader)
for row in reader:
lst = row[-1].split(" ")
if len(lst) > 1:
for i in range(0,len(lst)):
x+=1
if len(lst[i].split(',')) == 2:
est = lst[i].split(',')[0]
nth = lst[i].split(',')[1]
else:
prt("... ESRD # " + row[0].replace('"','') + " has invalid cooridnates associated with it.")
pass
dict[x] = row[0].replace('"',''), row[1].replace('"',''), row[2].replace('"',''), row[3].replace('"',''), row[4].replace('"',''), row[5].replace('"','').split(" ")[0], float(est.replace('"','')), float(nth.replace('"',''))
else:
x+=1
for l in lst:
dict[x] = row[0].replace('"',''), row[1].replace('"',''), row[2].replace('"',''), row[3].replace('"',''), row[4].replace('"',''), row[5].replace('"','').split(" ")[0], float(l.split(',')[0].replace('"','')), float(l.split(',')[1].replace('"',''))
#writing to a new csv with proper formatting
prt("writing to a new csv")
with open(os.path.dirname(os.path.realpath(__file__)) + os.sep + 'dict.csv', 'wb') as csvFile:
writer = csv.writer(csvFile)
header = ['ESRD File Number','Operation Name','File Classification','LLD','Documents in File','LINC','pointX','pointY']
writer.writerow(header)
for key, value in dict.iteritems():
writer.writerow(value)
##creating the required projection files
prjtxtresource = """PROJCS["NAD_1983_10TM_AEP_Resource",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-115.0],PARAMETER["Scale_Factor",0.9992],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]"""
prjtxtforest = """PROJCS["NAD_1983_10TM_AEP_Forest",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-115.0],PARAMETER["Scale_Factor",0.9992],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]"""
wrtprj(ws,"Projection_Resource",prjtxtresource)
wrtprj(ws,"Projection_Forest",prjtxtforest)
##Creating a xy event layer from the 10tm coordinates
prt('executing MakeXYEventLayer_management')
lyr = arcpy.MakeXYEventLayer_management(ws + os.sep + 'dict.csv','pointX','pointY', 'Layer', ws + os.sep + 'Projection_Resource.prj')
## Converting the temp layer file to a shape file
prt('executing CopyFeatures_management')
arcpy.CopyFeatures_management('Layer', ws + os.sep + 'esarDataExtract.shp')
## Projectiing the shape file from 10TM Resource Projection to 10TM Forest projection
prt('executing Project_management')
arcpy.Project_management(ws + os.sep + 'esarDataExtract.shp', ws + os.sep + 'esarDataExtract_Projected.shp', ws + os.sep + 'Projection_Forest.prj')
## Notifiy the user the process is finished
prt('Finished converting the ESAR Data from a CSV file to a Shape file')
except:
prt('---------------------------------------------------')
prt('exception raised')
prt('---------------------------------------------------')
prt('')
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = 'Error orignated from: \n\tcomputer: ' + str(socket.gethostname()) + '\n\tuser: ' + str(getpass.getuser())\
+ '\n\nPYTHON ERRORS:\nTraceback info:\n' + tbinfo + '\nError Info:\n' + str(sys.exc_info()[1])
# Print Python error messages for use in Python / Python Window
arcpy.AddWarning('\n... An unexpected error has occured. \n\n... An email with the error details has been sent to the Tool Administrator.\n\n... Contact a member of your local RIU for assistance.\n')
prt(pymsg)
email(pymsg)
finally:
# Print the elapsed time and perform any cleanup
prt(os.path.basename(__file__) + " Ended at " + time.strftime('%H:%M:%S', time.localtime(timer())))
prt("Elapsed time: " + time.strftime('%H:%M:%S', time.gmtime(timer() - start_time)))
try:
del os, arcpy, sys, csv, traceback, time, urllib, smtplib
except NameError:
pass
if __name__ == '__main__':
prt("Importing the required modules")
# Import the required modules
import time
import os
start_time = timer()
prt(os.path.basename(__file__) + " Started at " + time.strftime('%H:%M:%S', time.localtime(start_time)))
import arcpy
import sys
import socket
import getpass
import traceback
import csv
import urllib
import smtplib
from arcpy import env
env.overwriteOutput = True
main()
prt("Elapsed time: " + time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time)))