The bulk of the code used in my script for reading this is from @RHB located here. His block of code runs fine with a current map open. Need it to open without an ArcMap session open. I tried as suggested shifting the parameters instead of “CURRENT” using a filepath for the mxd, at which point it fails to output the layer/file. Thought maybe I needed to add mxd.save() within the function in order to find the layer, but to no avail.
def load_feature_layer(fc_path, layer_name):
# loads a feature layer into the active data frame in the current map
# using a feature class path and a layer name string.
# returns a layer object.
mxd = arcpy.mapping.MapDocument("C:\temp\parser.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
layerfile = os.path.join(arcpy.env.scratchFolder, layer_name + ".lyr")
arcpy.MakeFeatureLayer_management(fc_path, layer_name)
arcpy.SaveToLayerFile_management(layer_name, layerfile, "CURRENT")
add_layer = arcpy.mapping.Layer(layerfile)
arcpy.mapping.AddLayer(df, add_layer)
arcpy.RefreshTOC()
l = get_layer_by_name(layer_name)
return l
mxd.save()
def get_layer_by_name(name_string):
'''Finds a layer in the current MXD in active data frame by name.'''
mxd = arcpy.mapping.MapDocument("C:\temp\parser.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
layer_list = arcpy.mapping.ListLayers(mxd, "*", df)
desired_layer = None
for l in layer_list:
if l.name.lower() == name_string.lower():
desired_layer = l
if l.isGroupLayer:
for sub_layer in l:
if sub_layer.name.lower() == name_string.lower():
desired_layer = sub_layer
return desired_layer
if __name__ == "__main__":
import arcpy, traceback, sys, os
try:
outShp = arcpy.GetParameterAsText(0) # Shapefile
outName = arcpy.GetParameterAsText(1) # String
outLpk = arcpy.GetParameterAsText(2) # File .lpk
#...<the beginning of your code>...
layer1 = load_feature_layer(outShp, outName)
layer1.description = outName
arcpy.PackageLayer_management(layer1, outLpk, "PRESERVE", "CONVERT_ARCSDE", "", "ALL", "ALL", "ALL", "", "Footprint", "Bounding")
except:
# PRINT ERROR MESSAGES
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
pymsg = tbinfo + "n" + str(sys.exc_type)+ ": " + str(sys.exc_value)
arcpy.AddError("Python Messages: " + pymsg + " GP Messages: " + arcpy.GetMessages(2))
There are no errors when running it, it just fails to generate any output when pointing to the mxd.