Python Installation

Here is a short script that tests if you have working installation:

import ee
ee.Authenticate()
ee.Initialize()
print(ee.Image("NASA/NASADEM_HGT/001").get("title").getInfo())

Install options

If you are using Google Colab, the latest version of the Earth Engine Python client library has already been installed (via pip). Try the following notebook to get started with Earth Engine and Colab:

If you don't use Colab, the Earth Engine client library can be manually installed and updated on your system using conda (recommended) or pip:


Install the API to an arbitrary Python environment using pip. From a terminal or command prompt:

pip install earthengine-api

Once installed, you can import, authenticate and initialize the Earth Engine API as described here.

Update the API:

pip install earthengine-api --upgrade

Package import

The Python API package is called ee. It must be imported and initialized for each new Python session and script:

import ee

Authentication

Prior to using the Earth Engine Python client library, you need to authenticate (verify your identity) and use the resultant credentials to initialize the Python client. The following authentication flows may use Cloud projects to authenticate, and they're used for unpaid (free, noncommercial) use as well as paid use. See the Earth Engine Authentication and Initialization guide for troubleshooting and to learn more.

Colab or JupyterLab notebook

You can authenticate from within Colab or JupyterLab environments by executing the helper function ee.Authenticate() and following the instructions it generates.

Step-by-step instructions

  1. Browser: Notebook
    1. In a notebook code cell, run the following code to start an authentication flow using the "notebook" mode.
      import ee
      ee.Authenticate()
      Click on the link in the cell output to open a Notebook Authenticator page in a new tab.
  2. Browser: Notebook Authenticator
    1. Verify that the correct user account is listed.
    2. Select a Google Cloud Project to use for Authentication. If you need to create a new project, we recommend the naming convention "ee-xyz" where xyz is your usual Earth Engine user name. (If you cannot select or create a Cloud Project, see the troubleshooting section below.)
    3. Click Generate Token.
  3. Browser: Account Selection
    • You will be shown an account selection page. Click on the user account that you want to grant access from the notebook.
  4. Browser: Warning page
    • A warning page is presented, indicating that Google did not create the app (i.e. the Colab code in the notebook). Click Continue to acknowledge.
  5. Browser: Consent Screen
    • Indicate if you are willing to grant the requested scopes and click Continue.
  6. Browser: Authorization Code Screen
    • Copy the authorization verification code/token.
  7. Browser: Notebook
    • Switch back to the Colab tab, and paste the verification code/token into the code cell output.
    • The cell output should indicate "Successfully saved authorization token."
  8. Proceed with initialization.

Command line

You can authenticate from a command line by executing the command function earthengine authenticate and following the instructions it generates. This authentication flow requires installing the Google Cloud Command Line Interface (gcloud) on a machine that has a web browser.

Step-by-step instructions (local machine)

  1. Verify that gcloud is installed on the local machine.
    • In a terminal, run gcloud help. If gcloud is not installed, follow these instructions to install gcloud.
  2. Local Machine Terminal
    • In a terminal, run earthengine authenticate.
    • The command output will indicate that gcloud is being used to fetch credentials.
    • A browser window will open to an account selection page.
  3. Browser: Account Selection
    • Select the account you want to use for authentication.
  4. Browser: Consent Screen
    • Indicate if you are willing to grant the requested scopes and click "Allow".
  5. Browser: Confirmation Screen
    • The browser will show a page confirming that you are authenticated, and the earthengine authenticate command in your terminal window will report "Successfully saved authorization token."
  6. Proceed with initialization.

Step-by-step instructions (remote machine)

  1. Verify that gcloud is installed on the local machine and the remote machine.
    • In a terminal, run gcloud help. If gcloud is not installed, follow these instructions to install gcloud.
  2. Remote Machine Terminal
    • In a terminal, run earthengine authenticate.
    • The command output will indicate that gcloud is being used to fetch credentials.
    • A gcloud auth command will be presented. Copy the entire command. Do not click the URL which is part of the command.
  3. Local Machine Terminal
    • Paste and run the gcloud auth command.
    • Read the warning, and indicate that you want to proceed. This will open up a local browser window.
  4. Browser: Account Selection
    • Select the account you want to use for authentication.
  5. Browser: Consent Screen
    • Indicate if you are willing to grant the requested scopes and click "Allow".
  6. Browser: Confirmation Screen
    • The browser will show a page confirming that you are authenticated.
  7. Local Machine Terminal
    • Copy the URL beginning with https://localhost: that appeared in the terminal.
  8. Remote Machine Terminal
    • Paste the URL to answer the prompt "Enter the output of the above command:" and press enter.
    • The terminal will report "Successfully saved authorization token."
  9. Proceed with initialization.

With a service account

If you are authenticating Python code that will run unattended, you may want to authenticate with a service account rather than a user account. See these docs for using service accounts with Earth Engine.

Initialization

The initialization step verifies that valid credentials have been created and populates the Python client library with methods that the backend server supports.

ee.Initialize()

If you are using the earthengine command line tool, it will initialize automatically.

Troubleshooting authentication issues

See the Troubleshooting section of the authentication docs.

Syntax

Both the Python and JavaScript APIs access the same server-side functionality, but client-side expressions (learn more about client vs. server) can vary because of language syntax differences. The following table includes a list of the common syntax differences you'll encounter when working with the Python API relative to the JavaScript API.

Common syntax differences between JavaScript and Python
Property JavaScript Python
Function definition
function myFun(arg) {
  return arg;
}

var myFun = function(arg) {
  return arg;
};
def my_fun(arg):
  return arg
Anonymous function mapping
var foo = col.map(function(arg) {
  return arg;
});
foo = col.map(lambda arg: arg)
Variable definition
var myVar = 'var';
my_var = 'var'
Logical operators
var match = such.and(that);
var match = such.or(that);
var match = such.not(that);
match = such.And(that)
match = such.Or(that)
match = such.Not(that)
Multi-line method chain
var foo = my.really()
              .reallyLong()
              .methodChain();
foo = (my.really()
       .reallyLong()
       .methodChain())
Dictionary keys
var dic = {'key': value};
var dic = {key: value};
dic = {'key': value}
Dictionary object access
var value = dic.key;
var value = dic['key'];
value = dic['key']
Function argument definition
// Positional arguments.
var foo = fun(argX, argY, argZ);
// Keyword arguments object.
var foo = fun({y: argY});
# Positional arguments.
foo = fun(arg_x, arg_y, arg_z)
# Keyword arguments dictionary.
foo = fun(**{'y': arg_y})
# Keyword arguments.
foo = fun(x=arg_x, z=arg_z)
Boolean
var t = true;
var f = false;
t = True
f = False
Null values
var na = null;
na = None
Comment
//
#

Date objects

Define and manipulate client-side date objects with the datetime module. Include the module in your script:

import datetime

Convert ee.Date to client-side date:

ee_date = ee.Date('2020-01-01')
py_date = datetime.datetime.utcfromtimestamp(ee_date.getInfo()['value']/1000.0)

Convert client-side date to ee.Date:

py_date = datetime.datetime.utcnow()
ee_date = ee.Date(py_date)

Exporting data

Exporting data with the Python API requires the use of the ee.batch module, which provides an interface to the Export functions. Pass parameter arguments as you would with the JavaScript API, minding the differences noted in the syntax table above. Export tasks must be started by calling the start() method on a defined task. Query a task's status by calling the status() method on it. The following example demonstrates exporting an ee.Image object.

Create an export task:

task = ee.batch.Export.image.toDrive(image=my_image,  # an ee.Image object.
                                     region=my_geometry,  # an ee.Geometry object.
                                     description='mock_export',
                                     folder='gdrive_folder',
                                     fileNamePrefix='mock_export',
                                     scale=1000,
                                     crs='EPSG:4326')

Start an export task:

task.start()

Check export task status:

task.status()

The result of task.status() is a dictionary containing information such as the state of the task and its ID.

{
  'state': 'READY',
  'description': 'my_export_task',
  'creation_timestamp_ms': 1647567508236,
  'update_timestamp_ms': 1647567508236,
  'start_timestamp_ms': 0,
  'task_type': 'EXPORT_IMAGE',
  'id': '56TVJIZABUMTD5CJ5YHTMYK4',
  'name': 'projects/earthengine-legacy/operations/56TVJIZABUMTX5CJ5HHTMYK4'
}

You can monitor task progress using the state field. See the Processing Environments page for a list of state values and more information on task lifecycle.

Printing objects

Printing an Earth Engine object in Python prints the serialized request for the object, not the object itself. Refer to the Client vs. server page to understand the reason for this.

Call getInfo() on Earth Engine objects to get the desired object from the server to the client:

# 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())
Note that getInfo() is a synchronous operation, meaning execution of expressions following the getInfo() call are blocked until the result is returned to the client. Additionally, requests for a lot of data or expensive computations can return an error and/or hang. In general, the best practice is to export your results, and once complete, import them into a new script for further analysis.

UI objects

The Earth Engine ui module is only available through the JavaScript API Code Editor. Use third party libraries for UI elements in Python. Folium and ipyleaflet provide interactive map handling, while charting can be done with Matplotlib, Altair, or seaborn, to name a few. See examples in the Earth Engine in Colab setup notebook for using Folium and Matplotlib.

Python in the Developer Guide

Python code is included for some examples in the Earth Engine Developer Guide (stay tuned for more!). On these particular pages, you'll find buttons at the top of the page to run it as a Colab Jupyter notebook or view it on GitHub. You'll also find tabbed code snippet widgets that allow you to alternate between JavaScript Code Editor code and the equivalent Python Colab code. The Colab notebooks include everything to get the examples running, but if you are copying and pasting code to run in your own environment, you'll need to do a little setup first.

Earth Engine setup

Nearly every example uses the Earth Engine API so you'll need to import the API, authenticate, and initialize.

import ee
ee.Authenticate()
ee.Initialize()

Folium interactive map display

The Folium library can be used to display ee.Image objects in an interactive map. Folium maps are used throughout the Earth Engine Developer Guide pages when Python examples display map tiles. Before you can run these examples, you need to import Folium into your Python session and add a method to the folium.Map object for handling Earth Engine tiles. Here's how:

import folium


def add_ee_layer(self, ee_image_object, vis_params, name):
  map_id_dict = ee.Image(ee_image_object).getMapId(vis_params)
  folium.raster_layers.TileLayer(
      tiles=map_id_dict['tile_fetcher'].url_format,
      attr='Map Data &copy; <a href="https://earthengine.google.com/">Google Earth Engine</a>',
      name=name,
      overlay=True,
      control=True
  ).add_to(self)

folium.Map.add_ee_layer = add_ee_layer

Pretty-print

Some printed Earth Engine objects are in a nested JSON format that is quite long and/or complex. To improve readability in these cases, the pprint.pprint function is used; import pprint is included directly in examples as needed.