How do I run a Python script inside ArcMap to change datasources

2610
5
06-11-2018 04:32 AM
JoseSanchez
Occasional Contributor III

Hello everyone,

I need to run the python script below that changes layer datasources inside ArcMap when the mxd  is open.

How do I run the script with ArcMap Open?

import arcpy
from arcpy import env
from arcpy import mapping

newDataSource = r"Database Connections\NewSDEConnection.sde"
mapdoc = arcpy.mapping.MapDocument("CURRENT")
#mapdoc.findAndReplaceWorkspacePaths("<the directory you are changing from>" , newDataSource)

for df in mapping.ListDataFrames(mapdoc, "*"):
                    for lyr in mapping.ListLayers(mapdoc, "*", df):
                     
                        try:
                            if lyr.supports("DATASOURCE"):
                                theData = lyr.dataSource
                                print "the Data " + theData
                                theWorkspacePath = lyr.workspacePath
                                print  theWorkspacePath

                                if theData.find(".ImageServer") == -1:
                                    if  ".sde" in theWorkspacePath.lower():
                                        mxd.findAndReplaceWorkspacePaths(theWorkspacePath,newDataSource,False)
                                 
                               
                        except Exception as e:
                            print "The following error has occured:"
                            print e.message

                        except AttributeError:
                            pass

mapdoc.save()
del mapdoc

0 Kudos
5 Replies
DanPatterson_Retired
MVP Esteemed Contributor

Code Formatting the basics... to rule some apparent indentation errors.

Did you open the python window in arcmap and try to run it from there?

0 Kudos
MichaelVolz
Esteemed Contributor

Are you doing this one mxd at a time?  If not, why not use ArcCatalog Set Data Sources tool?

0 Kudos
JoseSanchez
Occasional Contributor III

Michael, it does not work with ArcCatalog Change Datasource because maps are using a Modling extension and when we tried to change the datasource in ArcMap it reset the model, and the user looses everything. So I am gdoing this one mxd at a time for some specific users.

Where is the Python window in ArcMap?  Can I load a python script?

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor
Luke_Pinner
MVP Regular Contributor

You should be able to use `execfile('path/to/script.py')` to run your script from the python window in ArcMap.

0 Kudos