从管道读取后将用户丢弃到 IRB
我有一个脚本,在执行时会将用户放入 IRB 会话。
一切都很好,但是当我使用 *nix 管道获取输入(例如使用 cat
)时,IRB 会话立即结束。
我可以将脚本(我们称其为 myscript.rb)简化为以下内容:
require 'irb' if $stdin.stat.size > 0 @text = $stdin.read else @text= "nothing" end ARGV.clear IRB.start
当像以下那样执行时:ruby myscript.rb
,我最终进入 IRB 会话(如预期)。
但是(假设 foo.txt
存在于 cwd
中): cat foo.txt | ruby myscript.rb 将只打印 IRB 提示符,然后 IRB 会话关闭(我将被删除到 $bash)。
有任何已知的解决方法或想法吗?
顺便说一句:它在 ruby 1.8.7 和 1.9.2 上具有相同的行为。
I have this script that drops the user to an IRB session when executed.
All good, but when I use *nix pipes to get the input (e.g. with cat
), the IRB session ends immediately.
I could reduce the script (let's call it myscript.rb) to the following:
require 'irb' if $stdin.stat.size > 0 @text = $stdin.read else @text= "nothing" end ARGV.clear IRB.start
When executed like: ruby myscript.rb
, I end up in the IRB session (as expected).
But (assuming foo.txt
exists in the cwd
): cat foo.txt | ruby myscript.rb
will just print the IRB prompt and then the IRB session is closed (I'm being dropped to $bash).
Any known workarounds or ideas?
BTW: it has the same behavior on ruby 1.8.7 as well as on 1.9.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你的问题是,当你通过管道传输到脚本时,STDIN 将是文件中的流,因此当你启动 IRB 时,它将从同一个流中读取,但请注意它已位于末尾,然后退出,就像它一样当您键入 ctrl-D (这是手动文件结束信号)时。
您可以重新打开 STDIN 以从 tty(即键盘)读取数据,如下所示:
但这对我来说看起来有点奇怪,我没有得到正确的 IRB 提示。但 IRB 确实有效。
I think your problem is that when you pipe to your script STDIN will be the stream from your file, so when when you start IRB it will read from the same stream, but notice that it's at its end, and quit, just like it would when you type ctrl-D (which is a manual end of file signal).
You can reopen STDIN to read from the tty (i.e. the keyboard) like this:
but it looks a bit weird for me, I don't get the proper IRB promt. IRB works though.
@Theo 发现了问题。
此外,在
IRB.start
之前要求 irb 将修复丢失的 IRB 设置。最后,代码如下所示:@Theo identified the problem.
Also, requiring irb before
IRB.start
will fix missing IRB settings. In the end, the code looks like this:$stdin.read 在 IRB 有机会读取您的输入之前读取它(如果您试图强制 IRB 从 stdin 执行命令)。
$stdin.read reads your input before IRB has a chance to read it (if you're trying to force IRB to execute commands from stdin).