Skip to content

How to run a program from a flow

cereyan.command runs an external program from a flow, a task or a code rule. It streams what the program prints to the run's log while it runs, decides the outcome from the exit code by a table, can turn JSON lines the program prints into events, and stops the program when the run is cancelled or times out.

The examples run small Python programs so the page can be tested. In a lane they are your own binaries.

Run a program and read its exit code

command.run takes the program and its arguments, waits for it to end, and returns a Result. Exit 0 is success. Any other code raises command.CommandFailed, which carries the code and the last lines the program printed.

import sys

from cereyan import command

result = command.run([sys.executable, "-c", "print('checked 12 markets')"])
assert result.code == 0
assert result.output == "checked 12 markets"

try:
    command.run([sys.executable, "-c", "import sys; print('no data dir', file=sys.stderr); sys.exit(7)"])
except command.CommandFailed as exc:
    assert exc.code == 7 and "no data dir" in exc.output

While the program runs, each line it prints on standard output goes to the run's log at INFO and each line on standard error at WARNING, so a long program's progress is visible in the UI before it ends. Outside a run the lines go to the cereyan.command logger. result.output keeps the last 1,000 lines of standard output.

Say what each exit code means

Programs often use exit codes for more than success and failure. exit_codes maps a code to command.OK (success) or to an exception class to raise. Map a code to cereyan.Abort when retrying cannot help, such as a bad argument: the task or run fails once, with no retry.

import sys

from cereyan import Abort, command


class NotDelivered(Exception):
    pass


TABLE = {3: command.OK, 2: Abort, 1: NotDelivered}

quiet = command.run([sys.executable, "-c", "raise SystemExit(3)"], exit_codes=TABLE)
assert quiet.code == 3

try:
    command.run([sys.executable, "-c", "print('chat not found'); raise SystemExit(1)"], exit_codes=TABLE)
except NotDelivered as exc:
    assert "exited 1" in str(exc) and "chat not found" in str(exc)

Bind a program once with Tool

A lane usually calls the same binary from several flows. command.Tool binds the program, the arguments every call starts with and the defaults of run, and Tool.run adds this call's arguments. env is exactly the environment the program gets, with nothing inherited from the engine, which keeps the engine's secrets away from it. Without env the program inherits the engine's environment.

import os
import sys

from cereyan import Abort, command

POLL = command.Tool(
    sys.executable, "-c", "import os, sys; print(sys.argv[1], os.environ.get('API_TOKEN', 'no token'))",
    env={"PATH": os.defpath, "SYSTEMROOT": os.environ.get("SYSTEMROOT", "")},
    exit_codes={3: command.OK, 2: Abort},
)

os.environ["API_TOKEN"] = "secret"
assert POLL.run("--moves").output == "--moves no token"

Turn JSON lines into events

With events, each line of standard output that is a JSON object becomes an event through emit_event, and so can fire rules. A template such as "account.{kind}" names the event from the object's fields and uses the object as the payload. A function given the object returns (name, payload), or None to leave the line to the log. Lines that are not JSON objects, or that lack a field the template names, are logged as usual.

import json
import sys

from cereyan import command, flow

PRINTS = "\n".join([
    "import json",
    "print(json.dumps({'kind': 'price_move', 'market': 'BTC'}))",
    "print('checked 12 markets')",
])


@flow
def send_move_alerts() -> int:
    return command.run([sys.executable, "-c", PRINTS], events="account.{kind}").events


assert send_move_alerts() == 1

Follow a long-running program with marks

A program that runs for a long time, such as one following a stream, needs to know which of its output is safely held so it can save its place. With ack="mark", a line such as {"mark": 12} is a mark: 12 is written back on the program's standard input once every event printed before it has reached the server. Events inside a run are buffered by the engine and sent in batches, so the helper waits for them to be stored before it writes the mark. If the engine dies first, the program never saw the mark and starts again from before those events.

import sys

from cereyan import command, flow

FOLLOWER = "\n".join([
    "import json, sys",
    "print(json.dumps({'alert': {'kind': 'stop_loss', 'id': 'a1'}}), flush=True)",
    "print(json.dumps({'mark': 1}), flush=True)",
    "print('saved place ' + sys.stdin.readline().strip(), flush=True)",
])


def alert(message):
    if "alert" in message:
        return f"account.{message['alert']['kind']}", message["alert"]
    return None


@flow(holds_processor=False)
def watch_the_stream() -> str:
    return command.run([sys.executable, "-c", FOLLOWER], events=alert, ack="mark").output


assert watch_the_stream() == "saved place 1"

ack keeps the program's standard input open for marks, so it cannot be combined with stdin, which writes text to the program and closes its input.

Stop a program

When the run is cancelled or times out, or the call's own timeout passes, the program's standard input is closed, it is sent SIGTERM, and it is killed grace seconds later (default 5) if it is still running. A call past its timeout raises command.TimedOut, which a task's retries treat like any other failure.

import sys

from cereyan import command

try:
    command.run([sys.executable, "-c", "import time; time.sleep(60)"], timeout=0.5, grace=1)
except command.TimedOut as exc:
    assert "timeout of 0.5 s" in str(exc)

Called from a flow body, the program is gone before the run ends. Called from a task with timeout_seconds, which runs on a thread of its own, the run can end first, and the program is gone within grace seconds. If the engine itself is stopped or dies, its signal reaches the program too: see Stop the programs a run started. On Windows the program is ended at once, without the grace.