标准输入

更新时间:
复制 MD 格式

标准输入用于向运行中的命令发送数据,适合交互式程序、脚本参数输入和长进程控制。

启动可接收 stdin 的命令

TypeScript 示例:

const handle = await sandbox.commands.run("cat", {
  background: true,
  stdin: true,
});

await sandbox.commands.sendStdin(handle.pid, "hello from stdin\n");
await sandbox.commands.closeStdin(handle.pid);

const result = await handle.wait();
console.log(result.stdout);

Python 示例:

handle = sandbox.commands.run(
    "cat",
    background=True,
    stdin=True,
)

sandbox.commands.send_stdin(handle.pid, "hello from stdin\n")
sandbox.commands.close_stdin(handle.pid)

result = handle.wait()
print(result.stdout)

closeStdin() 会关闭非 PTY 命令的标准输入,并向进程发送 EOF。PTY 会话不使用 closeStdin();如果需要在 PTY 中结束输入,可以发送 Ctrl+D(0x04)或按交互式程序约定发送退出命令。

使用建议

  • 对简单参数,优先使用命令参数或环境变量。

  • 对需要持续输入的进程,保存 pid,任务正常结束时优先关闭 stdin 并等待结果;超时或异常时再主动 kill()

  • 不要把敏感凭证直接写入命令输出可见的交互流程。