Command Palette

Search for a command to run...

Назад к скиллам
скилл № 95378

ports

Guide for Elixir/Erlang Ports — communicating with external OS processes. Use when spawning external programs, implementing port protocols, wrapping ports in…

БесплатноБез исполняемых скриптов
vinnie357от vinnie357★ 30 звёзд на GitHub

Установить ports в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Elixir Ports

Ports are Elixir's mechanism for communicating with external OS programs via stdin/stdout. A Port is not a network port — it is a process-like entity that manages an external OS program, forwarding messages as bytes and delivering responses back to the owning Elixir process.

Port Fundamentals

Open a port with Port.open/2. The most common name forms are {:spawn, command} and {:spawn_executable, path}.

# Spawn by shell command string (uses shell, PATH lookups apply)
port = Port.open({:spawn, "cat"}, [:binary])

# Spawn executable directly (no shell, preferred for security)
port = Port.open({:spawn_executable, "/usr/bin/python3"}, [
  :binary,
  args: ["-u", "my_script.py"]
])

Send data to the port and receive from it:

# Send bytes to the external process's stdin
Port.command(port, "hello\n")

# Receive response — messages arrive in the process mailbox
receive do
  {^port, {:data, data}} ->
    IO.puts("Got: #{data}")
end

Close the port explicitly or let it close when the owner process exits:

Port.close(port)
# The port will reply {port, :closed} after the external process exits

Port Options Reference

Option Description
:binary Deliver data as binaries (recommended; default is charlists)
{:packet, N} Prefix each message with N-byte length header (N = 1, 2, or 4)
{:line, L} Deliver complete lines up to L bytes; partial lines flagged
:stream No framing — raw bytes delivered as received (default)
:exit_status Send {port, {:exit_status, code}} when the program exits
:use_stdio Use stdin/stdout for communication (default)
:stderr_to_stdout Merge stderr into stdout stream
{:cd, dir} Set working directory for the external process
{:env, env_list} EXTENDS the spawned process's environment (does NOT replace it)
{:args, arg_list} Argument list when using :spawn_executable
{:arg0, string} Override argv[0] for the external process
:parallelism Hint to scheduler for improved throughput

Note on {:env, env_list}: This option extends the environment the BEAM already holds — the spawned process inherits every existing variable, and env_list adds to or overrides individual entries. There is no replace-all option. To withhold an inherited variable, pair its name with false (an empty charlist — ~c"" or [] — also unsets; Elixir's "" is a binary and raises). See the Security section.

Communication Patterns

Stream Mode (default)

Bytes are delivered as they arrive with no framing. Use :binary to get binaries instead of charlists.

port = Port.open({:spawn_executable, "/bin/cat"}, [:binary, :stream])

Port.command(port, "some data")

receive do
  {^port, {:data, chunk}} -> IO.inspect(chunk)
end

Packet Mode

Use {:packet, N} for message framing. The external program must also implement the same N-byte big-endian length prefix.

# Elixir side
port = Port.open({:spawn_executable, "/usr/local/bin/my_worker"}, [
  :binary,
  {:packet, 4}
])

Port.command(port, encode_message("hello"))

receive do
  {^port, {:data, response}} -> decode_message(response)
end

The external program reads a 4-byte big-endian integer as the message length, then reads that many bytes. It writes responses with the same framing.

Line Mode

port = Port.open({:spawn_executable, "/usr/bin/python3"}, [
  :binary,
  {:line, 4096},
  args: ["script.py"]
])

receive do
  {^port, {:data, {:eol, line}}} ->
    IO.puts("Complete line: #{line}")

  {^port, {:data, {:noeol, partial}}} ->
    IO.puts("Partial line (too long): #{partial}")
end

Receiving Exit Status

port = Port.open({:spawn, "false"}, [:binary, :exit_status])

receive do
  {^port, {:exit_status, code}} ->
    IO.puts("Exited with code #{code}")
end

GenServer Port Wrapper

Wrapping a port in a GenServer is the standard OTP pattern for managing external processes. The GenServer owns the port, handles messages, and exposes a clean API.

defmodule MyApp.ExternalWorker do
  use GenServer

  @timeout 5_000

  # Client API

  def start_link(opts \\ []) do
    GenServer.start_link(__MODULE__, opts, name: __MODULE__)
  end

  def call(payload) do
    GenServer.call(__MODULE__, {:call, payload}, @timeout)
  end

  # Server Callbacks

  @impl true
  def init(_opts) do
    executable = System.find_executable("my_worker") ||
      raise "my_worker not found in PATH"

    port =
      Port.open({:spawn_executable, executable}, [
        :binary,
        {:packet, 4},
        :exit_status
      ])

    ref = Port.monitor(port)

    {:ok, %{port: port, ref: ref, caller: nil}}
  end

  @impl true
  def handle_call({:call, payload}, from, %{port: port} = state) do
    encoded = :erlang.term_to_binary(payload)
    Port.command(port, encoded)
    {:noreply, %{state | caller: from}}
  end

  @impl true
  def hand
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • references/erlang-ports.md

FAQ

Что делает скилл ports?

Guide for Elixir/Erlang Ports — communicating with external OS processes. Use when spawning external programs, implementing port protocols, wrapping ports in GenServer, or choosing between Port, NIF, System.cmd, and C Nodes.

Как установить скилл ports?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл ports запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить ports с