Run commands in a sandbox
There are two common patterns for executing commands in a sandbox:- Run a single command and let the sandbox stop when the command finishes.
- Run multiple commands in the same sandbox.
Run a single command
To run a single command, pass the command directly toSandbox.run(). The sandbox stops automatically when the command finishes and is no longer available for additional work.
Run multiple commands sequentially in the same sandbox
Use the same sandbox for workflows that require multiple steps, such as installing dependencies, writing files, running a script, and reading results. To run multiple commands in the same sandbox, start the sandbox without a command. Then useSandbox.exec() to run commands in the running sandbox.
The following code snippet starts a sandbox without a main command, then runs two commands sequentially in the same sandbox: first it installs PyTorch, then it runs a training script:
Sandbox.exec() method runs a command inside a running sandbox and returns a Process object that you can use to wait for completion, read output, and inspect the exit code.
For more information about Sandbox.exec() and its parameters, see the Sandbox.exec() reference documentation.
You can also explictly define a long runnig main process to keep the sandbox alive while the command runs. This is useful if you want to run a command that takes a long time to execute, such as training a machine learning model.
The following code snippet starts a sandbox with the command sleep infinity, which keeps the sandbox running indefinitely. Then it runs a Python training script inside the sandbox using Sandbox.exec(). The sandbox stays active while the training script runs, and you can run additional commands in the same sandbox if needed.
Read output and exit codes
Sandbox.exec() returns a Process object. Call Process.result() to wait for the command to finish and get its result. Process.result() includes the standard output (stdout), standard error (stderr), and exit code (returncode).
Use the exit code to determine whether the command succeeded. By convention, an exit code of 0 indicates success.
For example, the following code snippet runs a Python command that prints the standard output (stdout) and the exit code (returncode). After the command finishes, it prints the standard output, standard error, and exit code to the console.
Check for sandbox execution errors
Specifycheck=True (Sandbox.exec(check=True)) to raise an error if the command exits with a non-zero exit code. A SandboxExecutionError is raised if the command exits with a non-zero code: