Rupyex.Session (Rupyex v0.1.0)

Copy Markdown View Source

A live Python interpreter: a namespace plus the thread that runs it.

A session is a plain struct wrapping a NIF resource, so it can be passed between processes and stored in any state. Requests from different processes are queued and run one at a time, and each answer goes back to the process that asked for it.

The interpreter thread stops when the session is closed with close/1 or when the struct becomes garbage — hold on to it for as long as you need the Python state to survive.

{:ok, session} = Rupyex.Session.open()
{:ok, 3} = Rupyex.eval(session, "1 + 2")
:ok = Rupyex.Session.close(session)

Summary

Functions

Stop the interpreter and release everything it holds.

Abort whatever the session is running right now.

Start an interpreter.

Same as open/1, but raises on failure.

Whether the session still accepts requests.

Types

open_option()

@type open_option() ::
  {:stdlib, boolean()}
  | {:capture_output, boolean()}
  | {:sys_path, [String.t()]}
  | {:argv, [String.t()]}
  | {:init, String.t() | nil}
  | {:timeout, timeout()}
  | {:open_timeout, timeout()}

Options for open/1:

  • :stdlib — make the embedded Python standard library importable (default true)
  • :capture_output — send sys.stdout/sys.stderr to Rupyex.Result instead of the OS streams (default true); with false, Python prints land on the BEAM's own stdout
  • :sys_path — extra sys.path entries, for importing real .py files
  • :argvsys.argv
  • :init — Python source to run once at start-up
  • :timeout — default timeout for every call on this session (default 5000 ms)
  • :open_timeout — how long to wait for the interpreter to start (default 30000 ms)

t()

@type t() :: %Rupyex.Session{ref: reference(), timeout: timeout()}

Functions

close(session)

@spec close(t()) :: :ok

Stop the interpreter and release everything it holds.

Any queued request fails with a :closed error. Closing twice is fine.

interrupt(session)

@spec interrupt(t()) :: :ok

Abort whatever the session is running right now.

The running Python code receives a KeyboardInterrupt at its next safe point, which it may catch. Callers waiting on that job get an :interrupted error.

open(opts \\ [])

@spec open([open_option()]) :: {:ok, t()} | {:error, Rupyex.Error.t()}

Start an interpreter.

Blocks until the interpreter is ready, so start-up failures (a broken :init script, for instance) are reported here rather than on first use.

open!(opts \\ [])

@spec open!([open_option()]) :: t()

Same as open/1, but raises on failure.

open?(session)

@spec open?(t()) :: boolean()

Whether the session still accepts requests.