Skip To Content

Export a model to Python

Exporting a model to a Python script can help you learn how tools and environments are used in Python. , To export a model to Python, click the Export button on the ModelBuilder ribbon and choose one of the following options:

  • Export To Python File
  • Sending To Python Window

After editing and completing the script, you can add it to a toolbox or model as a script tool and run it as any other geoprocessing tool, or you can use it as a stand-alone Python script.

Edit an exported Python script

You may find that your exported Python code needs to be edited. Consider the following when exporting a model to a script:

  • If you will be overwriting data, set the arcpy.env.overwriteOutput property to True.
  • If your model uses layers or table views that weren't created in the original model, you'll need to create those layers or table views in the script using tools such as Make Feature Layer and Make Table View.
  • Data elements from your model are converted directly into variables in the exported script. Avoid naming data elements that will be incompatible in Python (for example, class, global, and return). For a full list of reserved keywords, use the Python keyword module.
    import keyword
    print keyword.kwlist
  • If your model used any inline variable substitution, such as %workspace%, %scratchworkspace%, %n%, %i%, or %variable name%, you'll need to replace those with the correct value.
  • Only the environment settings that have been changed from the default value will be exported to a model.
  • If your model used a model Iterators, Utilities, or Logical tool, the tool will not run in Python. You must implement the equivalent Python functionality that these tools provide. For example, you will need to use if/else logic to do branching in your script.
  • If your model included submodels, the contents of those submodels will not be exported. Instead, you'll need to reference the toolbox and call the model tool in the script.
  • Preconditions and feedbacks are not translated into the script flow.