Ruby从bash脚本执行中捕获stderr输出

时间:2021-01-01 23:05:45

I can currently redirect stdout to a string variable in ruby/rails by simply running the command in bash and setting the result to my string variable as follows.

我现在可以通过在bash中运行命令并将结果设置为我的字符串变量,将stdout重定向到ruby / rails中的字符串变量,如下所示。

val = %x[ #{cmd} ]

where cmd is a string that represents a bash command.

其中cmd是表示bash命令的字符串。

However, this only captures stdout, for I want to capture stderr and set it to a string in ruby -- any ideas?

但是,这只捕获stdout,因为我想捕获stderr并将其设置为ruby中的字符串 - 任何想法?

2 个解决方案

#1


10  

Simply redirect it:

只需重定向它:

val = %x[ #{cmd} 2>&1 ]

If you want to capture output from stderr only, close the file descriptor for stdout after copying it to fd 2.

如果要仅从stderr捕获输出,请在将其复制到fd 2后关闭stdout的文件描述符。

val = %x[ #{cmd} 2>&1 >/dev/null ]

#2


1  

You can use Open3.popen3:

您可以使用Open3.popen3:

require 'open3'
stdin, stdout, stderr, wait_thread = Open3.popen3('ping -Z')
# => [#<IO:fd 9>, #<IO:fd 10>, #<IO:fd 12>, #<Thread:0x007fd3d30a0ce0 sleep>]

stderr.gets # => "ping: illegal option -- Z\n"
stdout.gets # => nil

#1


10  

Simply redirect it:

只需重定向它:

val = %x[ #{cmd} 2>&1 ]

If you want to capture output from stderr only, close the file descriptor for stdout after copying it to fd 2.

如果要仅从stderr捕获输出,请在将其复制到fd 2后关闭stdout的文件描述符。

val = %x[ #{cmd} 2>&1 >/dev/null ]

#2


1  

You can use Open3.popen3:

您可以使用Open3.popen3:

require 'open3'
stdin, stdout, stderr, wait_thread = Open3.popen3('ping -Z')
# => [#<IO:fd 9>, #<IO:fd 10>, #<IO:fd 12>, #<Thread:0x007fd3d30a0ce0 sleep>]

stderr.gets # => "ping: illegal option -- Z\n"
stdout.gets # => nil