如何测试过滤器像撬Ruby脚本? [英] How to test filter-like Ruby scripts with Pry?

查看:142
本文介绍了如何测试过滤器像撬Ruby脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本,处理来自STDIN来的线。有时候一个异常出现 - 一些UTF-8转换错误 - 我想检查变量,是什么导致错误。我用下面的语法在我的文件(姑且称之为filter.rb),但我从来没有撬提示:

I have a simple script which process the lines coming from STDIN. Sometimes an exception arise - some UTF-8 conversion error - and I would like to examine the variables, what cause the error. I use the following syntax in my file (let's call filter.rb), but I never get a Pry prompt:

#!/usr/bin/ruby
require "pry"

n=0
while line=STDIN.gets do
 begin
   n=n+1
   raise "an exception" if n==2
 rescue => e
   binding.pry
 end
end

当我发出:

cat data.txt|ruby filter.rb

我在屏幕上看到:

I see on the screen:

     5:   while line= STDIN.gets do
     6:    begin
     7:      n=n+1
     8:      raise "an exception" if n==2
     9:    rescue => e
 => 10:      binding.pry
    11:    end
    12:   end

但事实上我得到的是一个bash提示符,而不是一个撬命令提示符。

But in fact all I get is a bash prompt, not a Pry command prompt.

推荐答案

的问题是,用途的ReadLine ,从而从读取标准输入。如果您使用Ruby作为过滤器,标准输入不再是终端(isatty会是假的)。所以Readline的将不能够使用标准输入和默默游行(或给出一个语法错误和游行上,如果你幸运的话)。

The problem is that Pry uses Readline, which in turn reads from stdin. If you use ruby as a filter, stdin no longer is a terminal (isatty will be false). So Readline won't be able to use stdin and silently marches on (or gives a syntax error and marches on, if you're lucky).

您可以通过添加给Readline工作的tty

You can give Readline a working tty by adding

require "readline"
Readline.input = IO.new(IO.sysopen("/dev/tty", "r+"))

您code。

撬文档暗示了这个解决方案,但我不知道这是否是通过撬批准,或者它可能会导致撬,Ruby和任何其他移动位的其他部分的奇怪反应。你可能在你的应用程序.. 。情况因人而异。

The Pry documentation hints at this solution, but I do not know if this is sanctioned by Pry, or if it could cause weird interactions with other parts of Pry, Ruby and whatever other moving bits you may have in your app... YMMV.

这篇关于如何测试过滤器像撬Ruby脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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