# Run commands Run shell commands in the foreground for the output, or in the background. ## Run one command Commands run in a shell, so pipes and redirects work. Python (run.py): ```python from fdtn import Sandbox sbx = Sandbox.create("base") result = sbx.commands.run("python3 -c 'print(1 + 1)'") print(result.stdout) # 2 print(result.exit_code) # 0 sbx.kill() ``` TypeScript (run.mjs): ```typescript import { Sandbox } from '@fdtn/sdk' const sbx = await Sandbox.create('base') const result = await sbx.commands.run("python3 -c 'print(1 + 1)'") console.log(result.stdout) // 2 console.log(result.exitCode) // 0 await sbx.kill() ``` CLI (terminal): ```bash $ fdtn create base -d i8x2k... $ fdtn exec i8x2k... python3 -c 'print(1 + 1)' 2 ``` The result has `stdout`, `stderr`, `exit_code` (`exitCode`) and `error`. ## Command options Python times are seconds. TypeScript times are milliseconds. | Python | TypeScript | CLI (`fdtn exec`) | Default | What it does | |---|---|---|---|---| | `background` | `background` | `-b`, `--background` | off | Return at once with a handle | | `envs` | `envs` | `-e KEY=VALUE` (repeat it) | none | Environment variables | | `cwd` | `cwd` | `-c`, `--cwd` | Home folder | Working folder | | `user` | `user` | `-u`, `--user` | The sandbox user | Linux user, for example `root` | | `on_stdout`, `on_stderr` | `onStdout`, `onStderr` | always on | none | Callback for each piece of output | | `stdin` | `stdin` | piped input | off | Keep standard input open | | `timeout` | `timeoutMs` | no limit | 60 s (SDK) | Longest run time. `0` means no limit. | ```bash $ fdtn exec -c /app -e CI=1 -u root npm test ``` The SDK stops a command after 60 seconds by default. Set `timeout` for long jobs. To give every command the same variables, set `envs` at create: `Sandbox.create("base", envs={"APP_ENV": "test"})` or `fdtn create base -d -e APP_ENV=test`. A per-command value wins. If you pause and resume the sandbox, pass `envs` (or `-e`) with each command after the resume. ## Stream output Pass a callback to get output as it arrives. Python: ```python result = sbx.commands.run( "for i in 1 2 3; do echo step $i; sleep 1; done", on_stdout=lambda data: print("out:", data, end=""), on_stderr=lambda data: print("err:", data, end=""), ) ``` TypeScript: ```typescript const result = await sbx.commands.run( 'for i in 1 2 3; do echo step $i; sleep 1; done', { onStdout: (data) => process.stdout.write(`out: ${data}`), onStderr: (data) => process.stderr.write(`err: ${data}`), }, ) ``` `fdtn exec` always streams. Pipe it like a local command. ```bash $ echo hello | fdtn exec cat # reads your stdin ``` Output is UTF-8 text. For binary data, use `fdtn cp` or `base64`. ## Run in the background Use background mode for servers and long jobs. The handle has: - `pid` - `wait()`: returns the result; raises on a non-zero exit code - `kill()` - `disconnect()`: stop reading output; the command keeps running - `send_stdin(data)` / `sendStdin(data)`: needs `stdin` on Python: ```python handle = sbx.commands.run("sleep 5; echo done", background=True, timeout=0) print("pid", handle.pid) # ... do other work ... result = handle.wait(on_stdout=lambda d: print(d, end="")) print(result.exit_code) ``` TypeScript: ```typescript const handle = await sbx.commands.run('sleep 5; echo done', { background: true, timeoutMs: 0, onStdout: (d) => process.stdout.write(d), }) console.log('pid', handle.pid) // ... do other work ... const result = await handle.wait() console.log(result.exitCode) ``` CLI: ```bash $ fdtn exec -b node server.js 412 $ fdtn process ls # list running commands $ fdtn process wait 412 # follow output, get the exit code $ fdtn process kill 412 # stop one command, keep the sandbox ``` Set timeout `0` for a server, or the SDK stops it after 60 seconds. `fdtn exec -b` sets no limit. For running commands, `sbx.commands` has `list()`, `connect(pid)`, `kill(pid)` and `send_stdin(pid, data)`. See [Python](https://fdtn.dev/docs/python.md#commands) and [TypeScript](https://fdtn.dev/docs/typescript.md#commands). ## Exit codes and errors A non-zero exit code raises an error with the code and output. Python: ```python from fdtn import CommandExitException, TimeoutException try: sbx.commands.run("ls /missing") except CommandExitException as e: print(e.exit_code) # 2 print(e.stderr) # ls: cannot access '/missing': ... except TimeoutException: print("the command ran longer than its timeout") ``` TypeScript: ```typescript import { CommandExitError, TimeoutError } from '@fdtn/sdk' try { await sbx.commands.run('ls /missing') } catch (e) { if (e instanceof CommandExitError) { console.log(e.exitCode) // 2 console.log(e.stderr) } else if (e instanceof TimeoutError) { console.log('the command ran longer than its timeout') } else { throw e } } ``` To continue after a failure, add `|| true` or catch the error. Other errors: [Python](https://fdtn.dev/docs/python.md#errors), [TypeScript](https://fdtn.dev/docs/typescript.md#errors). ### fdtn exec exit codes | Code | Meaning | |---|---| | 0 to 255 | The exit code of the command | | 128 + N | Signal N ended it, for example 130 after Ctrl-C | | 1 | The command could not start (unknown sandbox ID) | | 141 | The reader closed the pipe (`\| head -1`) | ## fdtn exec rules - Put options before the sandbox ID. Everything after the ID goes to the command. - Run a command that starts with a dash through `sh -c`. - Use `@name` for a sandbox named with `--name`. - No command time limit. The sandbox lifetime still applies. ```bash $ fdtn exec @worker sh -c './-weird-program --flag' ``` For many sandboxes, use [`fdtn each`](https://fdtn.dev/docs/parallel.md#each). For async Python, use [`AsyncSandbox`](https://fdtn.dev/docs/python.md#async) with the same options. ## Next - [**Files**: Upload and download files.](https://fdtn.dev/docs/files.md) - [**Ports and URLs**: Reach a server in a sandbox.](https://fdtn.dev/docs/ports.md) Source: https://fdtn.dev/docs/commands/