如何捕获 pry shell 命令的输出?

发布于 2025-01-04 14:44:46 字数 151 浏览 3 评论 0原文

我正在使用 pry,我想捕获并处理 shell 命令的输出。

例如,如果我运行,

pry(main)> .ls

我想将文件列表放入一个可以在 Ruby 中使用的数组中。

我该怎么做?

I'm using pry and I want to capture, and work with output of a shell command.

For example, If I run

pry(main)> .ls

I want to get the list of files into an array that I can work with in Ruby.

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南薇 2025-01-11 14:44:46

这是一个很老的问题,但无论如何我都会回答它。从 pry 命令获取数据的主要方法有两种。第一个是该命令是否将 keep_retval 选项设置为 true,而 shell 命令则不会。第二种,是使用虚拟管道。在您的示例中,可以这样做:

fizz = []
.ls | {|listing| fizz = listing.split("\n")} # can also be written as
.ls do |listing|
  fizz = listing.split("\n")
end

This is a pretty old question but I'll answer it anyways. There are two primary methods of getting data out of pry commands. The first is if the command sets the keep_retval option to true, which the shell command does not. The second, is to use the virtual pipe. In your example this can be done as:

fizz = []
.ls | {|listing| fizz = listing.split("\n")} # can also be written as
.ls do |listing|
  fizz = listing.split("\n")
end
微凉 2025-01-11 14:44:46

我认为这是某种 pry 的魔力;-)

快速查看发生的情况后(我没有查看 pry 的源代码),您可能想使用这个:

`ls`.split("\n")

或者

Dir['./*']

这个解决方案的好处是它可以在 之外工作>撬动

I assume it's some kind of pry's magic ;-)

After quick look at what's happening (I didn't look at pry's source), you might want to use this:

`ls`.split("\n")

or

Dir['./*']

What's good about this solution is that it will work outside of pry

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文