I have a script that can currently run in ArcMap or ArcCatalog, by design.
However, if it is run in in ArcMap, I would like the two final output FC to be added to the map (Saving is optional at this point, so haven't added )
I was able to get this to work in ArcMap with the following addition code..
# my variables finalOutdd and finalOutProj are set to full paths of the output mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] ddLayer = arcpy.mapping.Layer(finalOutdd) projLayer = arcpy.mapping.Layer(finalOutProj) arcpy.mapping.AddLayer(df, ddLayer, "TOP") arcpy.mapping.AddLayer(df, projLayer, "TOP") # mxd.save()
My question is, how can I do a test to see if I'm running this in ArcMap? ArcCatalog and an external python window will basically work the same, i.e. not add the layers to anything. But if the code above is used, it will error out that there is no MapDocument
I've looked at the options for arcpy.GetInstallInfo()[""] and arcpy.ProductInfo() but so far, it sees both as "Desktop" (ProduceName from GetInstallInfo) and "ArcInfo" (from ProductInfo).
Anyone know a simple way to test for this?
Thanks.
(btw - Desktop 10.3.1)
Solved! Go to Solution.
You could use try-except statement put your above code inside it
You could use try-except statement put your above code inside it
Thanks Wes. That worked great. I didn't know whether I could have a try-except embedded in another try-except, but that did the trick.
So, although this is already within a try-except block, so my indentation isn't really showing it right, this is that code block now.
Sorry, formatting for python with this snippet was trying to make it a table.....so, snapshot..
Ahhh... the good old diaper pattern...
Just in case there's some other exceptions waiting to bite you, you could do something like:
try: mxd = arcpy.mapping.MapDocument("CURRENT") except RuntimeError: print('Not using ArcMap') else: df = arcpy.mapping.ListDataFrames(mxd)[0] ddLayer = arcpy.mapping.Layer(finalOutdd) projLayer = arcpy.mapping.Layer(finalOutProj) arcpy.mapping.AddLayer(df, ddLayer, "TOP") arcpy.mapping.AddLayer(df, projLayer, "TOP")
Luke,
yep.....I'm still not a very elegant programmer. But I like that, and took the advice. Tested with the change...works....s and it does look better. Thanks!
Oh neither am I
I didn't know that had a name until Dan Patterson posted How to make mistakes in Python... a useful link
I saw Dan's post.....on my reading list for this weekend. Looks like an interesting read.
Or, you could try this (from Jason Sheirer's entry in GIS Stack Exchange, http://gis.stackexchange.com/questions/64937/checking-if-python-script-is-run-from-arcgis-arcmap-or-... 😞
In the Python window (if you're in ArcMap):
>>> import sys
>>> sys.executable
'C:\\Program Files (x86)\\ArcGIS\\Desktop10.3\\bin\\ArcMap.exe'