本节介绍如何在沙箱中设置和使用环境变量。

默认环境变量

创建沙箱后,环境变量 E2B_SANDBOX 会自动设置为 true,该环境变量可用于判断代码是否在沙箱内运行,示例如下:

import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('echo $E2B_SANDBOX')

console.log(result)

// 输出示例:
// { exitCode: 0, error: undefined, stdout: 'true\n', stderr: '' }

设置环境变量

您可以通过如下 3 种方式来设置环境变量:

1. 创建沙箱时设置全局环境变量

您可以在创建沙箱时设置全局环境变量。

import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create({
    envs: {
        MY_VAR: 'my_value',
    },
})

const result = await sandbox.commands.run("echo $MY_VAR")

console.log(result)

// 输出示例:
// { exitCode: 0, error: undefined, stdout: 'my_value\n', stderr: '' }

2. 运行代码时设置环境变量

您可以为沙箱中特定的代码运行片段设置环境变量。

如果您设置了同名的全局环境变量,全局环境变量值将被覆盖。

import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()

const result = await sandbox.runCode('import os; print(os.environ.get("MY_VAR"))', {
  envs: {
    MY_VAR: 'my_value',
  },
})

3. 运行命令时设置环境变量

您可以为沙箱中特定的命令执行片段设置环境变量。

如果您设置了同名的全局环境变量,全局环境变量值将被覆盖。

import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()

const result = await sandbox.commands.run('echo $MY_VAR', {
  envs: {
    MY_VAR: '123',
  },
})

console.log(result)

// 输出示例:
// { exitCode: 0, error: undefined, stdout: '123\n', stderr: '' }