且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从从 stdin 读取的 Ruby 脚本调用时,撬不停止

更新时间:2023-12-05 13:52:10

尝试 ARGF with simple:

Try ARGF with simple:

require 'rubygems'
require 'pry'
binding.pry

现在 IO 操作不在 ARGF.read 内部涵盖,很明显这里出了什么问题.ARGF 被粘合"到 STDIN,因此传递给 STDIN 的任何东西都会直接进入 pry 的输入.

Now IO operations are not covered internally by ARGF.read and it became evident what’s wrong here. ARGF is "glued" to STDIN, therefore whatever is being passed to STDIN goes directly to pry’s input.

我不知道您的 file.txt 中的哪条指令会强制 pry 退出,但有一条指令.

I do not know exactly, what instruction in your file.txt forces pry to quit, but there is one.

更新

看起来如果一个 Ruby 脚本在 stdin 上产生任何东西(例如通过管道),$stdinSTDIN 被设置到这个管道,搞乱了 pry 的我从哪里跑"检测.

It looks like if a Ruby script yields anything on stdin (e. g. through a pipe,) both $stdin and STDIN are set to this pipe, messing up pry’s "where am I run from" detection.

我想出了这个不太优雅的解决方案:

I came up with this not-so-elegant solution:

# read input from ARGF
text = ARGF.read

# prepare new stdin to satisfy pry
pry_fd_stdin = IO.sysopen("/dev/tty")
pry_stdin = IO.new(pry_fd_stdin, "r")

# load pry and cheat it with our stdio
require 'pry'
Pry.config.input = pry_stdin

binding.pry

这个解决方案有一些小故障(例如,pry 提示仅在输入后 显示).

This solution has some glitches (e.g. pry prompt is shown only after input).