Help Center

Write a script

Define a script’s inputs and outputs in the editor, read project data in your code, save result files and check the script before you run it.

A script is your own analysis: code that takes project data and a few settings as inputs and saves files as results. This article covers the script editor, where you define the inputs and outputs and write the code between them. The examples are in Python. To create a script and add it to a project, see Run an analysis.

Open the editor

A new script opens in the editor as soon as you create it. To come back to one later, open Analytics Tools, click the script, then click Edit.

The panel on the left has three tabs: Inputs, Outputs and Rules. The code is on the right. Update Script at the top saves your work.


The script editor with the Inputs tab on the left and Python code on the right

Define the inputs

Inputs are what the Run dialog asks for before a run starts. On the Inputs tab, click Add and fill in:

  • Variable Name: the name your code reads the value by. Keep it short, with no spaces.

  • Label: the name people see in the Run dialog.

  • Field Type: the kind of value, from the table below.

  • Show tooltip information: a hint shown beside the field in the Run dialog.

  • Required: a run cannot start without this value.

Click Save. To change or remove an input later, open the menu on its row and choose Edit or Delete. You can leave Non-interactive and Use in run name unticked for a script you run on its own.


The input form with Variable Name, Label, Field Type, tooltip and the Required option

The field types are:

Field Type

What the Run dialog asks for

String, Numeric

A text or a number. You can set a default.

Select Input

One choice from the options you list.

Boolean

A checkbox.

Resource

One of the project’s resources. Tick Allow multiple to accept several.

Resource Collection

A collection from the project’s resources.

Resource Url

A project resource, passed to the code as a link instead of a file.

Point, Extent Rectangle, Extent Polygon

A place or an area drawn on a map.

Path

A path typed in by hand.

Static Asset

Nothing. You upload a file with the script and every run gets it.

Define the outputs

Outputs are what a run hands back. On the Outputs tab, click Add, enter a Variable Name and a Label, and choose the Output Type:

  • Path: a folder for result files. Every file your code saves in it appears on the execution’s Output tab.

  • String or Numeric: a single value. Assign it to a variable with the output’s name.

Write the code

Each input and output reaches your code as an environment variable named after its Variable Name:

  • A Resource input holds a short record such as {'type': 'PATH', 'value': '/…/units.fgb'}. The value is the path of a copy of the file made for this run.

  • A Path output holds the path of its folder.

A layer uploaded as GeoJSON is stored as FlatGeobuf, so it arrives as an .fgb file. GDAL opens it directly.

This script reads a layer of thinning units, measures each polygon and saves the areas as a CSV table. It has one Resource input named units and one Path output named summary:

import ast
import csv
import os

from osgeo import ogr, osr

# Input "units" is a project resource. The run passes a short record
# that holds the path of the file.
units = ast.literal_eval(os.environ["units"])
units_file = units["value"]

# Output "summary" is a folder. Every file saved in it becomes a result.
summary = os.environ["summary"]
os.makedirs(summary, exist_ok=True)

source = ogr.Open(units_file)
layer = source.GetLayer()

# Measure in an equal-area projection so the areas are true on the ground.
equal_area = osr.SpatialReference()
equal_area.ImportFromEPSG(6933)
to_equal_area = osr.CoordinateTransformation(layer.GetSpatialRef(), equal_area)

SQUARE_METERS_PER_ACRE = 4046.8564224
rows = []
for feature in layer:
    shape = feature.GetGeometryRef().Clone()
    shape.Transform(to_equal_area)
    acres = round(shape.GetArea() / SQUARE_METERS_PER_ACRE, 2)
    rows.append([feature.GetField("unit"), acres])

rows.sort()
for name, acres in rows:
    print(f"{name}: {acres} acres")
total = round(sum(acres for name, acres in rows), 2)
rows.append(["Total", total])

with open(os.path.join(summary, "area_summary.csv"), "w", newline="") as table:
    writer = csv.writer(table)
    writer.writerow(["unit", "area_acres"])
    writer.writerows(rows)
print(f"{len(rows) - 1} units, {total} acres in total")
import ast
import csv
import os

from osgeo import ogr, osr

# Input "units" is a project resource. The run passes a short record
# that holds the path of the file.
units = ast.literal_eval(os.environ["units"])
units_file = units["value"]

# Output "summary" is a folder. Every file saved in it becomes a result.
summary = os.environ["summary"]
os.makedirs(summary, exist_ok=True)

source = ogr.Open(units_file)
layer = source.GetLayer()

# Measure in an equal-area projection so the areas are true on the ground.
equal_area = osr.SpatialReference()
equal_area.ImportFromEPSG(6933)
to_equal_area = osr.CoordinateTransformation(layer.GetSpatialRef(), equal_area)

SQUARE_METERS_PER_ACRE = 4046.8564224
rows = []
for feature in layer:
    shape = feature.GetGeometryRef().Clone()
    shape.Transform(to_equal_area)
    acres = round(shape.GetArea() / SQUARE_METERS_PER_ACRE, 2)
    rows.append([feature.GetField("unit"), acres])

rows.sort()
for name, acres in rows:
    print(f"{name}: {acres} acres")
total = round(sum(acres for name, acres in rows), 2)
rows.append(["Total", total])

with open(os.path.join(summary, "area_summary.csv"), "w", newline="") as table:
    writer = csv.writer(table)
    writer.writerow(["unit", "area_acres"])
    writer.writerows(rows)
print(f"{len(rows) - 1} units, {total} acres in total")
import ast
import csv
import os

from osgeo import ogr, osr

# Input "units" is a project resource. The run passes a short record
# that holds the path of the file.
units = ast.literal_eval(os.environ["units"])
units_file = units["value"]

# Output "summary" is a folder. Every file saved in it becomes a result.
summary = os.environ["summary"]
os.makedirs(summary, exist_ok=True)

source = ogr.Open(units_file)
layer = source.GetLayer()

# Measure in an equal-area projection so the areas are true on the ground.
equal_area = osr.SpatialReference()
equal_area.ImportFromEPSG(6933)
to_equal_area = osr.CoordinateTransformation(layer.GetSpatialRef(), equal_area)

SQUARE_METERS_PER_ACRE = 4046.8564224
rows = []
for feature in layer:
    shape = feature.GetGeometryRef().Clone()
    shape.Transform(to_equal_area)
    acres = round(shape.GetArea() / SQUARE_METERS_PER_ACRE, 2)
    rows.append([feature.GetField("unit"), acres])

rows.sort()
for name, acres in rows:
    print(f"{name}: {acres} acres")
total = round(sum(acres for name, acres in rows), 2)
rows.append(["Total", total])

with open(os.path.join(summary, "area_summary.csv"), "w", newline="") as table:
    writer = csv.writer(table)
    writer.writerow(["unit", "area_acres"])
    writer.writerows(rows)
print(f"{len(rows) - 1} units, {total} acres in total")

Anything the code prints goes to the execution’s log. The log also shows the values the run passed in, which helps when a script cannot find its data:


An execution log with the values passed for the units input and the summary output, followed by the lines the script printed

Python scripts can use the standard library and the geospatial libraries installed for runs, including GDAL, GeoPandas, Shapely, pyproj, Rasterio, PDAL, NumPy, pandas and SciPy.

Check and save

The editor checks the code as you type and underlines problems in red. Click Update Script to save. If problems remain, the editor asks “Code contains errors. Do you want to continue?” Click Submit to save anyway, or Cancel to go back and fix them.

Two more buttons help while you work:

  • Script difference shows the saved version and your current code side by side.

  • Prompt lets you describe a change in plain words. Click Generate and AI updates the current script. Read the result before you save it.

A saved script still has to be Active before a project can use it: click the gear, set Status to Active and click Update. The same settings set the CPU and memory that runs get by default.

Hide inputs with rules

A rule hides an input in the Run dialog depending on another input. On the Rules tab, click Add, name the rule, pick the Target field to hide, the Source field to watch and the Condition, then click Save.

Try it out

Add the script to a project and run it on real data, as described in Run an analysis. To read the log and keep the files, see Review an execution and save results.

Still need help?

Contact our team for support.