> ## Documentation Index
> Fetch the complete documentation index at: https://ppio.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 在后台运行命令

export const SandboxConfigHint = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    return <Note>在运行本文档中的示例代码前，请确保您已正确配置环境变量，详情请参考 <a href="/sandbox/get-start#配置环境变量">配置环境变量</a>。</Note>;
  }
};

<SandboxConfigHint />

要在后台运行命令，请向 `commands.run()` 方法开启 `background` 选项，启用后，运行 `commands.run()` 方法会立即返回，命令将继续在沙箱中运行。使用 `commands.kill()` 方法可以终止该命令。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={null}
  import { Sandbox } from 'ppio-sandbox/code-interpreter'

  const sandbox = await Sandbox.create()

  // 在后台运行命令
  const command = await sandbox.commands.run('echo hello; sleep 10; echo world', {
    background: true,
    onStdout: (data) => {
      console.log(data)
    },
  })

  // 终止命令
  await command.kill()
  await sandbox.kill()
  ```

  ```python Python icon="python" theme={null}
  from ppio_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create()

  # 在后台运行命令
  command = sandbox.commands.run('echo hello; sleep 10; echo world', background=True)

  # 获取命令运行在后台的 stdout 和 stderr。
  # 您可以在单独的线程中运行此代码，或使用 command.wait() 等待命令被执行完。
  for stdout, stderr, _ in command:
      if stdout:
          print(stdout)
      if stderr:
          print(stderr)

  # 终止命令
  command.kill()
  sandbox.kill()
  ```
</CodeGroup>
