IO.popen "fakefake" #=> # irb> (irb):1: command -6ren">
gpt4 book ai didi

ruby - 为 IO::popen 拯救 "command not found"

转载 作者:数据小太阳 更新时间:2023-10-29 07:08:00 31 4
gpt4 key购买 nike

当我将 IO::popen 与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:

 irb> IO.popen "fakefake"
#=> #<IO:0x187dec>
irb> (irb):1: command not found: fakefake

有什么方法可以捕获此错误,以便我可以在脚本中进行检查?

最佳答案

是:升级到 ruby​​ 1.9。如果您在 1.9 中运行它,则会引发 Errno::ENOENT,您将能够拯救它。

(编辑)这是在 1.8 中的一种 hackish 方式:

error = IO.pipe
$stderr.reopen error[1]
pipe = IO.popen 'qwe' # <- not a real command
$stderr.reopen IO.new(2)
error[1].close

if !select([error[0]], nil, nil, 0.1)
# The command was found. Use `pipe' here.
puts 'found'
else
# The command could not be found.
puts 'not found'
end

关于ruby - 为 IO::popen 拯救 "command not found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3250985/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com