🚀 New! Kestra raises $3 million to grow Learn more

Commands Commands

yaml
type: "io.kestra.plugin.scripts.python.Commands"

Execute one or more Python scripts from a Command Line Interface.

Examples

Execute a Python script in a Conda virtual environment. First, add the following script in the embedded VS Code editor and name it etl_script.py:

python
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--num", type=int, default=42, help="Enter an integer")

args = parser.parse_args()
result = args.num * 2
print(result)

Then, make sure to set the enabled flag of the namespaceFiles property to true to enable namespace files.

This flow uses a PROCESS runner and Conda virtual environment for process isolation and dependency management. However, note that, by default, Kestra runs tasks in a Docker container (i.e. a DOCKER runner), and you can use the docker property to customize many options, such as the Docker image to use.

yaml
id: python_venv
namespace: dev

tasks:
  - id: hello
    type: io.kestra.plugin.scripts.python.Commands
    namespaceFiles:
      enabled: true
    runner: PROCESS
    beforeCommands:
      - conda activate myCondaEnv
    commands:
      - python etl_script.py

Execute a Python script from Git in a Docker container and output a file

yaml
id: pythonCommandsExample
namespace: dev

tasks:
  - id: wdir
    type: io.kestra.core.tasks.flows.WorkingDirectory
    tasks:
      - id: cloneRepository
        type: io.kestra.plugin.git.Clone
        url: https://github.com/kestra-io/examples
        branch: main

      - id: gitPythonScripts
        type: io.kestra.plugin.scripts.python.Commands
        warningOnStdErr: false
        docker:
          image: ghcr.io/kestra-io/pydata:latest
        beforeCommands:
          - pip install faker > /dev/null
        commands:
          - python scripts/etl_script.py
          - python scripts/generate_orders.py
        outputFiles:
          - orders.csv

  - id: loadCsvToS3
    type: io.kestra.plugin.aws.s3.Upload
    accessKeyId: "{{secret('AWS_ACCESS_KEY_ID')}}"
    secretKeyId: "{{secret('AWS_SECRET_ACCESS_KEY')}}"
    region: eu-central-1
    bucket: kestraio
    key: stage/orders.csv
    from: "{{outputs.outputFile.uris['orders.csv']}}"

Execute a Python script on a remote worker with a GPU

yaml
id: gpuTask
namespace: dev

tasks:
  - id: hello
    type: io.kestra.plugin.scripts.python.Commands
    runner: PROCESS
    commands:
      - python ml_on_gpu.py
    workerGroup:
      key: gpu

Pass detected S3 objects from the event trigger to a Python script

yaml
id: s3TriggerCommands
namespace: blueprint
description: process CSV file from S3 trigger

tasks:
  - id: wdir
    type: io.kestra.core.tasks.flows.WorkingDirectory
    tasks:
      - id: cloneRepo
        type: io.kestra.plugin.git.Clone
        url: https://github.com/kestra-io/examples
        branch: main

      - id: python
        type: io.kestra.plugin.scripts.python.Commands
        inputFiles:
          data.csv: "{{ trigger.objects | jq('.[].uri') | first }}"
        description: this script reads a file `data.csv` from S3 trigger
        docker:
          image: ghcr.io/kestra-io/pydata:latest
        warningOnStdErr: false
        commands:
          - python scripts/clean_messy_dataset.py
        outputFiles:
          - "*.csv"
          - "*.parquet"

triggers:
  - id: waitForS3object
    type: io.kestra.plugin.aws.s3.Trigger
    bucket: declarative-orchestration
    maxKeys: 1
    interval: PT1S
    filter: FILES
    action: MOVE
    prefix: raw/
    moveTo:
      key: archive/raw/
    accessKeyId: "{{ secret('AWS_ACCESS_KEY_ID') }}"
    secretKeyId: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
    region: "{{ secret('AWS_DEFAULT_REGION') }}"

Execute a Python script from Git using a private Docker container image

yaml
id: pythonInContainer
namespace: dev

tasks:
  - id: wdir
    type: io.kestra.core.tasks.flows.WorkingDirectory
    tasks:
      - id: cloneRepository
        type: io.kestra.plugin.git.Clone
        url: https://github.com/kestra-io/examples
        branch: main

      - id: gitPythonScripts
        type: io.kestra.plugin.scripts.python.Commands
        warningOnStdErr: false
        commands:
          - python scripts/etl_script.py
        runner: DOCKER
        docker:
          image: annageller/kestra:latest
          config: |
            {
              "auths": {
                  "https://index.docker.io/v1/": {
                      "username": "annageller",
                      "password": "{{ secret('DOCKER_PAT') }}"
                  }
              }
            }

      - id: output
        type: io.kestra.core.tasks.storages.LocalFiles
        outputFiles:
          - "*.csv"
          - "*.parquet"

Create a python script and execute it in a virtual environment

yaml
id: "script_in_venv"
namespace: "dev"
tasks:
  - id: bash
    type: io.kestra.plugin.scripts.python.Commands
    inputFiles:
      main.py: |
        import requests
        from kestra import Kestra

        response = requests.get('https://google.com')
        print(response.status_code)
        Kestra.outputs({'status': response.status_code, 'text': response.text})
    beforeCommands:
      - python -m venv venv
      - . venv/bin/activate
      - pip install requests kestra > /dev/null
    commands:
      - python main.py

Properties

commands

  • Type: array
  • SubType: string
  • Dynamic: ✔️
  • Required: ✔️
  • Min items: 1

The commands to run

interpreter

  • Type: array
  • SubType: string
  • Dynamic:
  • Required: ✔️
  • Default: [/bin/sh, -c]
  • Min items: 1

Which interpreter to use

runner

  • Type: string
  • Dynamic:
  • Required: ✔️
  • Default: DOCKER
  • Possible Values:
    • PROCESS
    • DOCKER

Which script runner to use — by default, Kestra runs all scripts in DOCKER.

warningOnStdErr

  • Type: boolean
  • Dynamic:
  • Required: ✔️
  • Default: true

Set the task state to WARNINGif any stdErr is emitted

beforeCommands

  • Type: array
  • SubType: string
  • Dynamic: ✔️
  • Required:

A list of commands that will run before the commands, allowing to set up the environment e.g. pip install -r requirements.txt

docker

  • Type: DockerOptions
  • Dynamic:
  • Required:
  • Default: {image=python, pullPolicy=ALWAYS}

Docker options when using the DOCKER runner

env

  • Type: object
  • SubType: string
  • Dynamic: ✔️
  • Required:

Additional environment variables for the current process.

inputFiles

  • Type:objectstring
  • Dynamic: ✔️
  • Required:

The files to create on the local filesystem. Can be a map or a JSON object.

namespaceFiles

Inject namespace files

Inject namespace files to this task. When enabled, it will, by default, load all namespace files into the working directory. However, you can use the include or exclude properties to limit which namespace files will be injected.

outputFiles

  • Type: array
  • SubType: string
  • Dynamic: ✔️
  • Required:

The files from the local filesystem to send to the internal storage.

Must be a list of Glob expressions relative to the current working directory, some examples: my-dir/**, my-dir/*/** or my-dir/my-file.txt

Outputs

exitCode

  • Type: integer
  • Default: 0

The exit code of the entire Flow Execution

outputFiles

  • Type: object
  • SubType: string

The output files URI in Kestra internal storage

vars

  • Type: object

The value extracted from the output of the executed commands

Definitions

NamespaceFiles

enabled

  • Type: boolean
  • Dynamic:
  • Required:
  • Default: true

Whether to enable namespace files to be loaded into the working directory. If explicitly set to true in a task, it will load all Namespace Files into the task's working directory. Note that this property is by default set to true so that you can specify only the include and exclude properties to filter the files to load without having to explicitly set enabled to true.

exclude

  • Type: array
  • SubType: string
  • Dynamic:
  • Required:

A list of filters to exclude matching glob patterns. This allows you to exclude a subset of the Namespace Files from being downloaded at runtime. You can combine this property together with include to only inject a subset of files that you need into the task's working directory.

include

  • Type: array
  • SubType: string
  • Dynamic:
  • Required:

A list of filters to include only matching glob patterns. This allows you to only load a subset of the Namespace Files into the working directory.

DeviceRequest

capabilities

  • Type: array
  • SubType: array
  • Dynamic:
  • Required:

A list of capabilities; an OR list of AND lists of capabilities.

count

  • Type: integer
  • Dynamic:
  • Required:

A request for devices to be sent to device drivers

deviceIds

  • Type: array
  • SubType: string
  • Dynamic: ✔️
  • Required:

A request for devices to be sent to device drivers

driver

  • Type: string
  • Dynamic: ✔️
  • Required:

A request for devices to be sent to device drivers

options

  • Type: object
  • SubType: string
  • Dynamic:
  • Required:

Driver-specific options, specified as key/value pairs.

These options are passed directly to the driver.

Credentials

auth

  • Type: string
  • Dynamic: ✔️
  • Required:

The registry auth.

The auth field is a base64-encoded authentication string of username:password or a token.

identityToken

  • Type: string
  • Dynamic: ✔️
  • Required:

The identity token.

password

  • Type: string
  • Dynamic: ✔️
  • Required:

The registry password.

registry

  • Type: string
  • Dynamic: ✔️
  • Required:

The registry url.

if not defined, the registry will be extracted from the image name.

registryToken

  • Type: string
  • Dynamic: ✔️
  • Required:

The registry token.

username

  • Type: string
  • Dynamic: ✔️
  • Required:

The registry username.

Memory

kernelMemory

  • Type: string
  • Dynamic: ✔️
  • Required:

The maximum amount of kernel memory the container can use.

The minimum allowed value is 4m. Because kernel memory cannot be swapped out, a container which is starved of kernel memory may block host machine resources, which can have side effects on the host machine and on other containers. See --kernel-memory details.

memory

  • Type: string
  • Dynamic: ✔️
  • Required:

The maximum amount of memory resources the container can use.

That is, you must set the value to at least 6 megabytes.

memoryReservation

  • Type: string
  • Dynamic: ✔️
  • Required:

Allows you to specify a soft limit smaller than --memory which is activated when Docker detects contention or low memory on the host machine.

If you use memoryReservation, it must be set lower than memory for it to take precedence. Because it is a soft limit, it does not guarantee that the container doesn’t exceed the limit.

memorySwap

  • Type: string
  • Dynamic: ✔️
  • Required:

The amount of memory this container is allowed to swap to disk

If memory and memorySwap are set to the same value, this prevents containers from using any swap. This is because memorySwap is the amount of combined memory and swap that can be used, while memory is only the amount of physical memory that can be used.

memorySwappiness

  • Type: string
  • Dynamic: ✔️
  • Required:

The amount of memory this container is allowed to swap to disk

By default, the host kernel can swap out a percentage of anonymous pages used by a container. You can set memorySwappiness to a value between 0 and 100, to tune this percentage.

oomKillDisable

  • Type: boolean
  • Dynamic:
  • Required:

By default, if an out-of-memory (OOM) error occurs, the kernel kills processes in a container.

To change this behavior, use the oomKillDisable option. Only disable the OOM killer on containers where you have also set the memory option. If the memory flag is not set, the host can run out of memory, and the kernel may need to kill the host system’s processes to free the memory.

DockerOptions

image

  • Type: string
  • Dynamic: ✔️
  • Required: ✔️
  • Min length: 1

Docker image to use

config

  • Type: object
  • Dynamic: ✔️
  • Required:

Docker config file

Docker configuration file that can set access credentials to private container registries. Usually located in ~/.docker/config.json

cpu

  • Type: Cpu
  • Dynamic:
  • Required:

Limits the CPU usage to a given maximum threshold value.

By default, each container’s access to the host machine’s CPU cycles is unlimited. You can set various constraints to limit a given container’s access to the host machine’s CPU cycles.

credentials

Credentials for a private container registry.

deviceRequests

A list of device requests to be sent to device drivers

entryPoint

  • Type: array
  • SubType: string
  • Dynamic: ✔️
  • Required:

Docker entrypoint to use

extraHosts

  • Type: array
  • SubType: string
  • Dynamic: ✔️
  • Required:

Extra hostname mappings to the container network interface configuration

host

  • Type: string
  • Dynamic: ✔️
  • Required:

Docker api uri

memory

  • Type: Memory
  • Dynamic:
  • Required:

Limits memory usage to a given maximum threshold value.

Docker can enforce hard memory limits, which allow the container to use no more than a given amount of user or system memory, or soft limits, which allow the container to use as much memory as it needs unless certain conditions are met, such as when the kernel detects low memory or contention on the host machine. Some of these options have different effects when used alone or when more than one option is set.

networkMode

  • Type: string
  • Dynamic: ✔️
  • Required:

Docker network mode to use e.g. host, none, etc.

pullPolicy

  • Type: object
  • Dynamic:
  • Required:

shmSize

  • Type: string
  • Dynamic: ✔️
  • Required:

Size of /dev/shm in bytes.

The size must be greater than 0. If omitted the system uses 64MB.

user

  • Type: string
  • Dynamic: ✔️
  • Required:

User within the container

volumes

  • Type: array
  • SubType: string
  • Dynamic: ✔️
  • Required:

List of volumes to mount

Must be a valid mount expression as string, example : /home/user:/app

Volumes mount are disabled by default for security reasons; you must enable them on server configuration by setting kestra.tasks.scripts.docker.volume-enabled to true

Cpu

cpus

  • Type: integer
  • Dynamic:
  • Required:

The maximum amount of CPU resources a container can use.

For instance, if the host machine has two CPUs and you set cpus:"1.5", the container is guaranteed at most one and a half of the CPUs