能否配置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
相关产品推荐
相关产品推荐

