It's also better to include the specific error type you're expecting so you don't end up passing unexpected errors too. I don't know what type of error this is supposed to produce but here's an example.
<SPAN class="keyword token">try</SPAN><SPAN class="punctuation token">:</SPAN> Abstract <SPAN class="operator token">=</SPAN> tree<SPAN class="punctuation token">.</SPAN>find<SPAN class="punctuation token">(</SPAN><SPAN class="string token">"idinfo/descript/abstract"</SPAN><SPAN class="punctuation token">)</SPAN><SPAN class="punctuation token">.</SPAN>text <SPAN class="keyword token">except</SPAN> AttributeError<SPAN class="punctuation token">:</SPAN> Abstract <SPAN class="operator token">=</SPAN> <SPAN class="string token">"No abstract"</SPAN> <SPAN class="keyword token">except</SPAN><SPAN class="punctuation token">:</SPAN> <SPAN class="comment token"># Catch for all other unhandled exceptions</SPAN> <SPAN class="keyword token">raise</SPAN><SPAN class="line-numbers-rows"><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN></SPAN>
I believe the first way with the if else is similar to Duck Typing and the "look before you leap" lbyl non-pythonic methods.
As Curtis said, the latter with the try/except is pythonic:
https://www.youtube.com/watch?v=x3v9zMX1s4s
relevant resources:
What is the Metadata module—ArcGIS Pro | Documentation
arcpy-metadata · PyPI
GitHub - ucd-cws/arcpy_metadata: Python metadata editing classes for ArcGIS feature classes
using arcpy.da.walk to inventory data and export metadata to csv
Python Errors in IDLE when processing metadata
arcpy - Creating table containing all filenames (and possibly metadata) in File Geodatabase? - Geographic Information Sy…
Access and update map and layer metadata (arcpy.mp)
python - updating metadata for feature classes programatically using arcpy - Stack Overflow
Edit metadata for many ArcGIS items—ArcMap | Documentation
# Create the Geoprocessor object import arcpy, sys, os from xml.etree.ElementTree import ElementTree from arcpy import env # Get input parameters ##env.workspace = arcpy.GetParameterAsText(0) ##xmlfile = arcpy.GetParameterAsText(1) ##outfile = arcpy.GetParameterAsText(2) env.overwriteOutput = True ##AGSHOME = arcpy.GetInstallInfo("Desktop")["InstallDir"] ##translatorpath = AGSHOME + r"Metadata\Translator\ARCGIS2FGDC.xml" #Output file ##outfile=open(outfile,'w') #Dataset list function # list any standalone feature classes env.workspace = r"C:\projects\Vicinity.gdb" AGSHOME = arcpy.GetInstallInfo("Desktop")["InstallDir"] translatorpath = AGSHOME + r"Metadata\Translator\ARCGIS2FGDC.xml" fcList = arcpy.ListFeatureClasses() fcList.sort() for fc in fcList: fcname = str(fc) ## outfile.write(fcname + "\n" + ",") print fc xmlfile = r"C:\projects\Testing\ " + fcname + ".xml" arcpy.UpgradeMetadata_conversion (fc, "ESRIISO_TO_ARCGIS") arcpy.ExportMetadata_conversion(fc, translatorpath, xmlfile) tree = ElementTree() tree.parse(xmlfile) spot = tree.find("abstract") if spot: # if spot is True (not None) print spot.text else: print "No Abstract" spot = tree.find("purpose") if spot: # if spot is True (not None) print spot.text else: print "No Summary" spot = tree.find("datacred") if spot: # if spot is True (not None) print spot.text else: print "No Credits" # list feature datasets datasetList = arcpy.ListDatasets("","Feature") datasetList.sort() for dataset in datasetList: print dataset # list feature classes inside the dataset arcpy.env.workspace = dataset fcList = arcpy.ListFeatureClasses() fcList.sort() for fc in fcList: print " " + fc arcpy.ExportMetadata_conversion(fc, translatorpath, xmlfile) tree = ElementTree() tree.parse(xmlfile) spot = tree.find("descript/abstract") if spot: # if spot is True (not None) print " " + spot.text else: print " No abstract"
[/noparse] block,[/post] but I think you're missing an indent. Hopefully these fixes address both bugs [post=124021]noted above:[/post] if the name of your feature class has the same name as the feature dataset it resides in, it will cause the script to fail. (ex. - Data.gbd>Contours>Contours) Will also terminate if no text is found in the metadata component it is looking for. See changes below in red import arcpy, sys from xml.etree.ElementTree import ElementTree from arcpy import env env.overwriteOutput = True env.workspace = r"G:\sdeConnections\win_auth\sde_published.sde" AGSHOME = arcpy.GetInstallInfo("Desktop")["InstallDir"] translatorpath = AGSHOME + r"Metadata\Translator\ARCGIS2FGDC.xml" xmlfile = r"C:\Users\mtenold\Downloads\test.xml" # list any standalone feature classes fcList = arcpy.ListFeatureClasses() fcList.sort() for fc in fcList: print fc arcpy.ExportMetadata_conversion(fc, translatorpath, xmlfile) tree = ElementTree() tree.parse(xmlfile) spot = tree.find("idinfo/descript/abstract") if spot: # if spot is True (not None) print spot.text else: print "No abstract" # list feature datasets datasetList = arcpy.ListDatasets("","Feature") datasetList.sort() for dataset in datasetList: print dataset # list feature classes inside the dataset arcpy.env.workspace = dataset fcList = arcpy.ListFeatureClasses() fcList.sort() for fc in fcList: print " " + fc arcpy.ExportMetadata_conversion(fc, translatorpath, xmlfile) tree = ElementTree() tree.parse(xmlfile) spot = tree.find("idinfo/descript/abstract") if spot: # if spot is True (not None) print " " + spot.text else: print " No abstract"
The thing is I keep getting an error since about half of the feature classes do not have text in the description field, if I add a description then the script continues. Here is the error I receive when it finds a feature class with no text in the description of the metadata. Runtime error <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'text' Isn't there a way to add an if else statement?
spot = tree.find("idinfo/descript/abstract") if spot: # if spot is True (not None) print spot.text else: print "No abstract"
try: Abstract = tree.find("idinfo/descript/abstract").text except: Abstract = "No abstract"
if arcpy.Exists(existing_xml): # do the conversion arcpy.ESRITranslator_conversion (existing_xml, translator, r'\\export\outputfile.xml') # this fails if the MD is pre ArcGIS10
import os import arcpy from arcpy import conversion as CV # get translator path InstallDir = arcpy.GetInstallInfo("Desktop")["InstallDir"] translator = os.path.join(InstallDir,r"\Metadata\Translator", "ESRI_ISO2ISO19139.xml") # input and output docThing = r"C:\work\myfile.gdb\featureclass" outXML = os.path.join(r"\\export",os.path.basename(docThing)) + ".xml" try: CV.ESRITranslator(docThing, translator, outXML) except: # export failed try: # perhaps this metadata just needs upgrade? print "upgrading %s to 10..." % docThing CV.UpgradeMetadata(docThing,"ESRIISO_TO_ARCGIS") finally: # in any case, if upgrade fails or not, create or update # metadata off the dataset properties CV.SynchronizeMetadata(docThing,"ALWAYS") try: # one more time try to export CV.ESRITranslator(docThing, translator, outXML) except: print "Metadata export failed for " + docThing
import arcpy, sys from xml.etree.ElementTree import ElementTree from arcpy import env env.overwriteOutput = True env.workspace = r"D:\Lakeland_GIS\GDB\Lakeland\Lakeland.gdb\AddPoints" AGSHOME = arcpy.GetInstallInfo("Desktop")["InstallDir"] translatorpath = AGSHOME + r"Metadata\Translator\ARCGIS2FGDC.xml" xmlfile = r"U:\my docs\GIS Projects\Python\Scripts\List Metadata\working_test.xml" # list any standalone feature classes fcList = arcpy.ListFeatureClasses() fcList.sort() for fc in fcList: arcpy.ExportMetadata_conversion(fc, translatorpath, xmlfile) tree = ElementTree() tree.parse(xmlfile) spot = tree.find("idinfo/descript/purpose") print fc print spot.text # list feature datasets datasetList = arcpy.ListDatasets() datasetList.sort() for dataset in datasetList: print dataset # list feature classes inside the dataset fcList = arcpy.ListFeatureClasses("","",dataset) fcList.sort() for fc in fcList: arcpy.ExportMetadata_conversion(fc, translatorpath, xmlfile) tree = ElementTree() tree.parse(xmlfile) spot = tree.find("idinfo/descript/purpose") print " " + fc print " " + spot.text
import sys, os, arcpy def getMetadataText(Dataset,Element="dataIdInfo/idPurp"): """Extracts metadata contents from ArcGIS metadata arguments Dataset - Path to an ArcGIS dataset Element - XML path in ArcGIS metadata. Default: "metadata/dataIDInfo/idPurp" ("Summary") """ from xml.etree.ElementTree import ElementTree try: # Get arcgis to fgdc translator path ARCGISHOME = arcpy.GetInstallInfo("desktop")["InstallDir"] XSLT = os.path.normpath(os.path.join( ARCGISHOME, "Metadata/Stylesheets/gpTools/exact copy of.xslt")) xmlTemp = os.path.join(os.environ["TEMP"],"xyz_xmltemp.xml") # export the metadata to xml arcpy.env.overwriteOutput = True arcpy.XSLTransform_conversion(Dataset,XSLT,xmlTemp) # parse out Description element from ArcGIS 10 metadata tree = ElementTree() # make an ElementTree object tree.parse(xmlTemp) # read the xml into the ElementTree Data = tree.find(Element) # find whatever tag you want del tree arcpy.Delete_management(xmlTemp) return Data.text # return the contents as text except Exception, xmsg: raise Exception, str(xmsg) # You could put a loop here around this to print out Summary for a list of datasets dataset = r"E:\work\work.gdb\BeetleSprayArea.shp" text = getMetadataText(dataset) arcpy.AddMessage(text)
I tried today to use the XSLTransform_conversion tool to just extract out everything (avoiding a transform) but I am getting an error message that appears to be a bug in tool validation (which I sent to ESRI support).
import arcpy, sys from xml.etree.ElementTree import ElementTree from arcpy import env env.overwriteOutput = True env.workspace = r"D:\GIS\GDB\Lakeland\Lakeland.gdb\AddPoints" # set the workspace for use in ListFeatureClasses fcList = arcpy.ListFeatureClasses() # lists all feature classes from inside env.workspace translatorpath = r"C:\Program Files (x86)\ArcGIS\Desktop10.0\Metadata\Translator\ARCGIS2FGDC.xml" # the translator file to use xmlfile = r"D:\GIS\metadata\test.xml" # the output xml file for fc in fcList: arcpy.ExportMetadata_conversion(fc, translatorpath, xmlfile) # export the current fc's metadata to xml tree = ElementTree() # make an ElementTree object tree.parse(xmlfile) # read the xml into the ElementTree spot = tree.find("idinfo/descript/abstract") # find whatever tag you want print spot.text # print the text between the tags
I am able to list the "Description" portion of the metadata for an individual feature class.
It works fine as is, I suppose because there were no characters to be escaped...?
>>> "a\z" # "\z" is not a special string literal, so OK 'a\\z' >>> "a\t" # this is "a" followed by <tab> 'a\t' >>>
Membros conectados podem postar, seguir atualizações e mais. Novo aqui? Registre uma conta gratuita.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.