如何与衍生的进程交互并在ruby中捕获其输出?

时间:2016-09-26 14:54:38

标签: ruby spawn pry

我有一个ruby程序,它为我运行rake任务并捕获输出。现在他们正在PTY.spawn中运行。我遇到了这种方法的两个问题:

  1. 我不能在子进程中使用binding.pry。
  2. 重写自己的输出(例如进度条gem)的进程会产生输出,但不能删除以前的输出,所以我得到一堆渐进式输出,其中一行是预期的。
  3. 我需要解决撬问题。如果我能让第二个问题在这个过程中消失,那就太好了。

1 个答案:

答案 0 :(得分:0)

Pry支持调试远程进程,这应该适用于子进程。搜索" pry-remote"。

就删除以前的输出而言,你似乎并不了解究竟发生了什么;您必须考虑TTY的工作方式。之前的输出没有被删除,而是使用回车而不是换行将光标移动到行的开头。

您可以捕获输出并使用lines来维护行分隔符,将其分解为数组并取第一行或最后一行。例如:

text = "this is the first line."
text += "\rthis is another line."
text += "\rthis is the last line."
text # => "this is the first line.\rthis is another line.\rthis is the last line."

text.lines("\r").first # => "this is the first line.\r"
text.lines("\r").last # => "this is the last line."

或者,您可以使用split不会返回行分隔符:

text.split("\r").first # => "this is the first line."
text.split("\r").last # => "this is the last line."
相关问题