Select to view content in your preferred language

arcpy.mapping.MapDocument("CURRENT")

2218
5
07-29-2011 11:17 AM
MichaelGartrell
Emerging Contributor
MapDocument("CURRENT") returns an error "cannot open map document" if it is not run within an ArcMap session and I understand why.  However, I need to be able to add a layer to the ArcMap TOC from outside the ArcMap application.  How do I best approach that?  Can it be done somehow from python outside an ArcMap session?

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
lyr = arcpy.mapping.Layer(os.path.join(sPath,sFile))
arcpy.mapping.AddLayer(df, lyr, "AUTO_ARRANGE")
Tags (2)
0 Kudos
5 Replies
JasonScheirer
Esri Alum
Can't be done from Python.
0 Kudos
JakeSkinner
Esri Esteemed Contributor
You will just need to specify the path to mxd rather than "CURRENT":

mxd = arcpy.mapping.MapDocument(r"C:\data\Philadelphia.mxd")


After your code, be sure to save your mxd with:

mxd.save()
0 Kudos
MichaelGartrell
Emerging Contributor
Can't be done from Python.

OK, I half expected that.  Any pointers to how it could be done?
0 Kudos
JakeSkinner
Esri Esteemed Contributor
Here is an example:

import arcpy
from arcpy import env
from arcpy import mapping
env.workspace = r"C:\temp\python"

mxd = mapping.MapDocument(r"C:\temp\python\Airports.mxd")

for df in mapping.ListDataFrames(mxd, "*"):
    lyr = mapping.Layer(r"C:\temp\python\Airports.lyr")
    addLayer = mapping.AddLayer(df, lyr)

mxd.save()
del mxd
0 Kudos
MichaelGartrell
Emerging Contributor
Here is an example:

import arcpy
from arcpy import env
...
mxd.save()
del mxd


Thanks JSkinn3 but that will modify an existing document, not the live, maybe unsaved document in a current session.  I need a pointer on how to do that.
0 Kudos