# 后台运行命令
<subtitle>在后台运行长时间命令，并在需要时终止它。</subtitle>

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

```python
from ucloud_sandbox 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()
```
