You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否配置expect使其在stdin关闭时不关闭stdout?

解决Expect脚本在stdin关闭后无法继续向stdout写入的问题

问题重现

你的Expect脚本如下:

#!/usr/bin/env expect -f

send "Hello world"
expect eof
send "Goodbye world"

当通过 ./stdout-close.exp < /dev/null 运行时,会触发报错:

Hello worldsend: spawn id exp0 not open
    while executing
"send "Goodbye world""
    (file "./stdout-close.exp" line 5)

原因是expect eof检测到stdin的EOF后,会关闭默认关联的spawn交互通道(此处为脚本自身的标准输入输出通道),导致后续send命令无法写入。

解决方案

放弃使用send,改用puts stdout直接向标准输出写入内容,该操作不受spawn通道关闭的影响。修改后的脚本如下:

#!/usr/bin/env expect -f

send "Hello world"
expect eof
puts stdout "Goodbye world"

运行 ./stdout-close.exp < /dev/null 即可得到预期输出:

Hello worldGoodbye world

如果需要换行,可在字符串末尾添加\n:

puts stdout "Goodbye world\n"

原理说明

  • send命令的作用是向spawn启动的进程或默认交互通道发送数据,当默认通道因stdin的EOF被关闭后,该通道不再可用,因此触发报错。
  • puts stdout是直接操作标准输出的文件描述符,独立于Expect的spawn通道机制,只要stdout未被主动关闭,就能持续写入内容。

内容的提问来源于stack exchange,提问作者merlin2011

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 01:18:13