Python installation

Overview

The Earth Engine Python API facilitates interacting with Earth Engine servers using the Python programming language. It is available as a Python package that can be installed locally or within the cloud, and accessed from a command-line interpreter or within a Jupyter notebook.

Differences between the Earth Engine Python and JavaScript APIs are small, mostly related to variation in defining functions and variables, capitalization of logical operators, and language-specific client-side object characteristics.

The Python API provides a programmatic and flexible interface to Earth Engine. It allows for automating batch processing tasks, piping Earth Engine processed data to Python packages for post-processing, and leveraging the power of the command line. Additionally, the Jupyter notebook interface (Figure 1) of the Google Colaboratory platform (Colab) delivers a highly interactive and collaborative experience, and as a hosted service, is without the burden of local system setup and management.

The following sections describe how to deploy and work with the Earth Engine Python API.

Colab notebook
Figure 1. Google Colaboratory notebook interface.

Environments

Working with the Python API benefits from a development environment that includes:

  • A Python installation.
  • A Python package manager.
  • The Earth Engine Python API package.
  • Python data science packages.

In addition to these requirements, it is often helpful to be able to easily replicate a development environment for purposes of collaborating and debugging. The following table presents two options for working with the Python API that satisfy all of these criteria. Click option links for information on getting started.

Option 1:
Running a Google Colab notebook

Earth Engine is accessed through a hosted Jupyter notebook service connected to a virtual machine running Python and the Earth Engine Python API. You access the service from a local browser.

Advantages
  • No need to install any software on your local machine.
  • Easily share and save notebooks.
  • Seamless integration with Python data science libraries.
Disadvantages
  • No access to local files. (Files must be first uploaded to the Colab virtual machine.)
  • Execution is tied to a virtual machine (VM) which is recycled after being idle for a while or after a maximum lifetime.
Option 2:
Running a local conda install

The Earth Engine Python API runs locally from a conda environment.

Advantages
  • Access to local files and the ability to upload local files as Earth Engine assets.
  • Access to the system command line to run scripts and automate tasks.
  • Access to local development tools, such as code editors and version control tools.
Disadvantages
  • A higher level of technical skill may be required to successfully create a working environment.
  • Collaboration on scripts and projects may be more challenging.

Syntax

Both the Python and JavaScript APIs access the same server-side functionality, but client-side expression setup can vary because of language syntax differences. The following table and code block includes a list of the common syntax differences you'll encounter when working with the Python API relative to the JavaScript API.

Common syntax difference between JavaScript and Python
Property JavaScript Python
Function definition function myFun(){}
...or...
var myFun = function(){}
def myFun():
Anonymous function mapping map(function(x){
  return x
})
map(lambda x: x)
Variable definition var myVar = "var" myVar = "var"
Logical operators and()
or()
not()
And()
Or()
Not()
Multi-line method chain myReally()
  .reallyLong()
  .methodChain()
myReally() \
  .reallyLong() \
  .methodChain()
Dictionary keys {“key”: “value”}
...or...
{key: “value”}
{“key”: ”value”}
Dictionary object access dict.key
...or...
dict["key"]
dict["key"]
Function argument definition In order or by dictionary key-value pairs In order, by name, or dictionary key-value pairs
Boolean true
false
True
False
Null values null None
comment // #
A demonstration of JavaScript and Python syntax differences:

JavaScript

// Define a function
function myFun(img){
  return img;
}

var myFun = function(img){
  return img;
};

// Anonymous function mapping
var result = collection.map(function(img){
  return img;
});

// Define a variable
var myVar = "var";

// Logical operators
var match = this.and(that);
var match = this.or(that);
var match = this.not(that);

// Multi-line method chain
var foo = myReally()
  .reallyLong()
  .methodChain();

// Dictionary keys
var dictOption1 = {“key”: “value”};
var dictOption2 = {key: “value”};

// Dictionary object access
var value = dict.key;
var value = dict["key"];

// Function argument definition
var img = myFun(arg1, arg2, arg3); // in order, unbroken
var img = myFun({arg1:arg1, arg3:arg3}); // dictionary key-value pairs

// Boolean
var t = true;
var f = false;

// Null values
var na = null;

Python

# define a function
def myFun(img):
  return(img)

# Anonymous function mapping
result = collection.map(lambda img: img)

# Define a variable
myVar = "var"

# Logical operators
match = this.And(that)
match = this.Or(that)
match = this.Not(that)

# Multi-line method chain
foo = myReally() \
  .reallyLong() \
  .methodChain()

# Dictionary keys
dict = {“key”: “value”}

# Dictionary object access
value = dict["key"]

# Function argument definition
img = myFun(arg1, arg2, arg3) # in order, unbroken
img = myFun({"arg1":arg1, "arg3":arg3}) # dictionary key-value pairs
img = myFun(arg2=arg2, arg3=arg3) # by parameter name

# Boolean
t = True
f = False

# Null values
na = None

Package import

The Python API package is called ee. It must be imported into every new Python session and script.

import ee

It must also be initialized for every new session and script.

ee.Initialize()

Initialization requires authentication credentials, which provide your Google account access to the Earth Engine servers. The authentication process is described in the install instructions linked to in the above Environments section.

Exporting data

Exporting data with the Python API requires the use of the ee.batch module, which accepts arguments differently than the JavaScript Export module. Specifically, it does not accept an argument dictionary and the region parameter cannot be an ee.Geometry object. Use named arguments and GeoJSON geometry coordinates instead. Additionally, export tasks must be started by calling the start() method on a defined export task. Started task status can be queried by calling the status() method on the task.

Create an export task

task = ee.batch.Export.image.toDrive(image=myImg,
                                     region=myRegion.getInfo()['coordinates'],
                                     description='myDescription',
                                     folder='myGDriveFolder',
                                     fileNamePrefix='myFilePrefix',
                                     scale=myScale,
                                     crs=myCRS)

Start an export task

task.start()

Check export task status

task.status()

Printing objects

It is necessary to call getInfo() to print object information when using the Python API. If getInfo() is not called, the serialized request instructions are printed instead. Also use getInfo() to save array and dictionary expression results as variables accessible to client-side operations.

# Load a Landsat image
img = ee.Image('LANDSAT/LT05/C01/T1_SR/LT05_034033_20000913')

# Print image object WITHOUT call to getInfo(); prints serialized request instructions
print(img)

# Print image object WITH call to getInfo(); prints image metadata
print(img.getInfo())

UI objects

The Earth Engine ui module is not included in the Python API. This means that widgets, Map, and Chart features are not available. Please see the Earth Engine Colab install for suggestions on displaying maps and charts with the Python API.

Enviar comentarios sobre…

Google Earth Engine API