ReferenceSDK

Python SDK

Install the Python SDK, run a command on a computer and look up the client, computers, exec, files and errors

The Python SDK runs computers from Python code. It has two clients with the same resources and methods. Nevia blocks and AsyncNevia awaits. The SDK is in early access, so names and behaviour can change.

The quick start creates a computer, runs a command on it, writes and reads a file and deletes the computer. The reference after it covers the client, computers, exec, files and errors.

Prerequisites

You need:

  • Python 3.11 or later.
  • A Nevia workspace where you have the admin or editor role.
  • The nevia CLI, signed in with nevia login. The Quickstart shows how to install it.

Install the SDK

Invited testers only

The SDKs are in early access for invited testers. To ask for access, see Request access to Nevia.

From your project's root, download the SDK bundle. It unpacks to vendor/nevia-sdk-0.1.0/:

curl -fsSL --oauth2-bearer "$(nevia auth access-token)" https://sdk.nevia.cloud/0.1.0.tar.gz | tar -xz

Then install the SDK from it:

uv add ./vendor/nevia-sdk-0.1.0/python/nevia-0.1.0-py3-none-any.whl

Authenticate

The SDK uses your nevia login session, so a signed-in machine needs nothing more. A server or CI job uses a service-account key instead:

export NEVIA_KEY_FILE="$HOME/path/to/key.json"

Use an automation key file shows how to create one. If you belong to more than one workspace, set NEVIA_WORKSPACE to the workspace ID too.

Create a computer and run a command

Save this as quickstart.py:

from nevia import Nevia

with Nevia() as nevia:
    with nevia.computers.create(image='docker.io/library/python:3.13-slim') as computer:
        print(f'Computer: {computer.id}')

        result = computer.exec('python3 --version')
        print(f'Exit code: {result.exit_code}, output: {result.stdout.strip()}')

        computer.files.write('/tmp/hello.txt', 'Hello from Nevia!\n')
        print(computer.files.read_text('/tmp/hello.txt'), end='')

Run it:

python quickstart.py

The computer ID and Python version in the output vary:

Computer: 01d69b2m9d26k14b244xjwmp9mb
Exit code: 0, output: Python 3.13.18
Hello from Nevia!

computers.create() returns once the computer is ready, so the first command runs at once. A command that exits nonzero still returns a result. Check result.exit_code or result.ok to see whether it succeeded.

Clean up

The with block deletes the computer when it ends, also when the code inside it raises. nevia ls confirms the computer is gone.

To keep a computer after the program ends, create it without with and save its ID:

computer = nevia.computers.create(image='docker.io/library/python:3.13-slim')
print(computer.id)

A later program reconnects with nevia.computer(saved_id) and calls computer.delete() when it is done.

Reference

Sync and async clients

Nevia and AsyncNevia have the same resources, methods and arguments. The tables on this page list each method once and apply to both. Pick one client per program: Nevia for scripts and blocking code, AsyncNevia for code that already runs an event loop, such as an async web server or agent framework.

Where the two differ:

Nevia (sync)AsyncNevia (async)
Calling a methodcomputer.exec(...)await computer.exec(...)
Scoped clientwith Nevia() as nevia:async with AsyncNevia() as nevia:
Closing the clientnevia.close()await nevia.aclose()
Deleting a computer at the end of a blockwith nevia.computers.create(...) as computer:async with nevia.computers.create(...) as computer:
When create() createsAt the callWhen awaited or entered
Deleting a branch at the end of a blockNot available, call delete()async with computer.branch() as branch:
Listingfor computer in nevia.computers.list():async for computer in nevia.computers.list():
Workspace IDnevia.workspace() returns a strawait nevia.workspace()
credentials= callableA plain functionAn async function
Deadlineswith nevia.fail_after(30):with anyio.fail_after(30):
Resource classesComputer, Files, Process, DatabaseAsyncComputer, AsyncFiles, AsyncProcess, AsyncDatabase

Results and errors are the same classes in both: ExecResult, ComputerInfo, FileStat, DirEntry and NeviaError.

The deadline helpers bound every blocking call the SDK makes. fail_after raises TimeoutError when the time is up, move_on_after ends the block without raising and shield() lets cleanup run past either one:

import nevia

with nevia.fail_after(30):
    computer.exec('npm test')

Client

Nevia(
    *,
    base_url=None,
    credentials=None,
    key_file=None,
    key=None,
    workspace=None,
)
ArgumentDescription
credentialsToken string, or a callable that returns one
key_filePath to a service-account key file
keyService-account key as JSON text or a dict
workspaceWorkspace ID (defaults to your only workspace)
base_urlAPI base URL (defaults to production)

The client looks for credentials in this order:

  1. The credentials, key_file or key argument.
  2. NEVIA_TOKEN.
  3. NEVIA_KEY_FILE, or NEVIA_KEY with the key's JSON.
  4. Your nevia login session.

The workspace is the workspace argument, then NEVIA_WORKSPACE, then the only workspace you belong to.

Use the client as a context manager, or call close() (aclose() on AsyncNevia) when you are done. Closing the client leaves your computers running.

MemberDescription
nevia.computersCreate, get, find and list computers
nevia.computer(id)Handle to an existing computer, without a request
nevia.workspace()ID of the selected workspace
nevia.workspace(id)Client scoped to another workspace, on the same connections

Computers

MethodDescription
computers.create(*, image, name=None, env=None, protected=None, wait=True)Create a computer and wait until it is ready
computers.get(id)Get a computer by ID
computers.find(name)First computer whose name is exactly name, or None
computers.list()Iterate over every computer in the workspace

create() returns the computer. Inside a with block the SDK deletes the computer when the block ends. If the computer fails to become ready, or the wait times out or is interrupted, create() deletes it before raising.

On a computer:

MemberDescription
id, name, stateIdentity and lifecycle state
infoFull record as a ComputerInfo
refresh()Fetch the latest record
sleep()Sleep the computer and wait until it is sleeping
wake()Wake the computer and wait until it is ready
branch(*, name=None)Create a branch of the computer and return it
delete()Delete the computer (succeeds if it is already gone)

A branch is a new computer. AsyncNevia deletes it at the end of an async with block. With Nevia, call delete() on the branch when you are done.

Exec

computer.exec(command, *, cwd=None, env=None, stdin=None, timeout=None, transport='api', max_output_bytes=65536)

exec() runs a command to completion and returns an ExecResult.

ArgumentDescription
commandShell string (runs under sh -c), or a list of arguments
cwdWorking directory on the computer
envExtra environment variables for this command
stdinText sent to the command's standard input
timeoutSeconds before the command is stopped
transport'api' (default) or 'direct' for direct exec
max_output_bytesBytes kept from the end of each stream with direct exec

When timeout passes, the SDK stops the command's process group and returns the output so far with timed_out=True.

Exec runs through the API by default, which ends a request after about 50 seconds. Direct exec sends the command straight to the computer instead, so it suits longer commands. It keeps the last 64 KiB of each output stream and sets truncated=True when it drops output. See Limits and workarounds.

ExecResult fieldDescription
exit_codeExit code of the command
signalSignal that ended the command (0 when none)
stdout, stderrOutput of the command
timed_outWhether timeout stopped the command
truncatedWhether direct exec dropped output
okTrue when exit_code and signal are 0 and the command did not time out

Files

computer.files reads and writes files on the computer. Every path is a path on the computer.

MethodDescription
read(path)File content as bytes, or None when there is no file
read_text(path, encoding='utf-8')File content as str, or None when there is no file
write(path, data)Write a whole file from str or bytes, creating parent directories
stat(path)FileStat with type, size and times, or None when nothing is there
list(path, *, recursive=False, max_depth=1)Entries in a directory as DirEntry values, sorted by name
remove(path, *, recursive=False, force=False)Remove a file, or a directory tree with recursive

write() replaces the file in one step, so a reader never sees it half written. list() raises FileNotFoundError for a missing path and NotADirectoryError for a file.

Errors

The SDK raises every SDK and API error as a NeviaError. A command that exits nonzero is a result, not an error.

from nevia import Nevia, NeviaError

with Nevia() as nevia:
    try:
        computer = nevia.computers.get('01d4cnjk3xg90y576w8y6t4gdwm')
    except NeviaError as error:
        if error.code != 'not_found':
            raise
        print('No such computer')
FieldDescription
statusHTTP status (0 when the SDK refused the call before sending it)
codeError code, such as not_found or invalid_state
messageMessage for a person to read
detailsExtra facts about the error, as a dict
request_idAPI request ID to quote when you report a problem
retry_afterSeconds to wait before retrying, when the API sent one
resourceWhat the call had created before it failed, so you can delete it

New codes can appear, so treat a code you don't recognise as a generic failure. is_nevia_error(error, code) checks the type and the code in one call.

On this page