[GIS] Seeking Python script for creating .mxd files

arcgis-serverarcpymap-service

I am new to both ArcGIS and Python. My requirement is to automate the below MANUAL process:

  1. Creating a layer in ArcGIS for Desktop. To put it in another words, creating an ArcMap document (.mxd).
  2. Publishing the created ArcMap document (in Step 1) as a service to ArcGIS Server.

Currently we are doing this manually. I have come across scripts to automate step 2 using Python.

How can I automate step 1 and step 2?

Best Answer

This isn't really a standalone answer, more of an addition to @PolyGeo's answer as it addresses the 'mxd creation from scratch' in python issue.

You can create MXD's from scratch in python if you access ArcObjects. You will need the comtypes package and if using ArcGIS 10.1, you need to make a small change to automation.py. See ArcObjects + comtypes at 10.1

Below is some code to create an MXD from scratch in python:

import arcpy
import comtypes,os

def CreateMXD(path):
    GetModule('esriCarto.olb')
    import comtypes.gen.esriCarto as esriCarto
    pMapDocument = CreateObject(esriCarto.MapDocument, esriCarto.IMapDocument)
    pMapDocument.New(path)
    pMapDocument.Save() #probably not required...

def GetLibPath():
    """ Get the ArcObjects library path

        It would be nice to just load the module directly instead of needing the path,
        they are registered after all... But I just don't know enough about COM to do this

    """
    compath=os.path.join(arcpy.GetInstallInfo()['InstallDir'],'com')
    return compath

def GetModule(sModuleName):
    """ Generate (if not already done) wrappers for COM modules
    """
    from comtypes.client import GetModule
    sLibPath = GetLibPath()
    GetModule(os.path.join(sLibPath,sModuleName))

def CreateObject(COMClass, COMInterface):
    """ Creates a new comtypes POINTER object where
        COMClass is the class to be instantiated,
        COMInterface is the interface to be assigned
    """
    ptr = comtypes.client.CreateObject(COMClass, interface=COMInterface)
    return ptr

if __name__=='__main__':
    #testing...
    arcpy.SetProduct('arcview')
    filepath='c:/temp/testing123.mxd'
    if os.path.exists(filepath):os.unlink(filepath)
    CreateMXD(filepath)