从从 stdin 读取的 Ruby 脚本调用时,撬不停止 [英] Pry not stopping when called from a Ruby script that reads from stdin

查看:44
本文介绍了从从 stdin 读取的 Ruby 脚本调用时,撬不停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个控制台 Ruby 脚本,该脚本使用 ARGF 从文件或标准输入中加载数据,然后调用 Pry.

I've created a console Ruby script that uses ARGF to load data from a file or stdin, that then calls Pry.

当我传入一个文件(Pry 暂停)但失败(Pry 不会停止,只是退出 Ruby)时,当我使用 stdin 传递我的数据时,这很有效.

This works great when I pass a file in (Pry pauses) but fails (Pry doesn't stop and just exits Ruby) when I pass my data using stdin.

这很奇怪,有人知道为什么吗?我想通过标准输入传递数据并暂停 Pry.

This is weird, anyone know why? I would like to pass data in via stdin and have Pry pause.

看,一个示例脚本:

require 'rubygems'
require 'pry'


def pry_it(str)
    binding.pry
end

pry_it(ARGF.read)

当我使用 ARGV 中的文件调用此应用程序时,我得到了正确的响应 - 暂停

When I call this app with a file in ARGV I get my proper response - pry pausing

% bundle exec ruby pry_test.rb file.txt

From: /Users/wilcoxr/Development/json_pry/pry_test.rb @ line 8 Object#pry_it:

    6: def pry_it(str)
    7:
 => 8:  binding.pry
    9: end

[1] pry(main)>

太好了!我可以随心所欲地执行 Pry 命令

Great! I can execute Pry commands all I want

当我尝试使用 STDIN 将数据发送到我的工具时:

When I try to use STDIN to send data into my tool:

% cat file.txt | bundle exec ruby pry_test.rb

From: /Users/wilcoxr/Development/json_pry/pry_test.rb @ line 8 Object#pry_it:

    6: def pry_it(str)
    7:
 => 8:  binding.pry
    9: end

[1] pry(main)>
% 

仔细观察:注意我回到了我的 shell 提示符,而不是 IRB 中的暂停.奇怪的!我不明白为什么我会出现这种行为......

Look closely: note I'm back at my shell prompt, not pauses in IRB. Weird! I don't understand why I'm getting this behavior....

推荐答案

尝试 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).

这篇关于从从 stdin 读取的 Ruby 脚本调用时,撬不停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆