假设我有一个像这样的简单命令行解释器:
while true
print '> '
cmd = gets.chomp
break if cmd =~ /^(exit|quit)/
system(cmd) || puts('Command not found or invalid.')
end
我想,而不是“未找到或无效的命令”。 message 得到一个实际的错误信息,就像你从 bash 得到的一样。我该怎么做?
最佳答案
好吧,如果它是类 unix 系统,您实际上可以将 2>&1 附加到您的命令中:
system(cmd + ' 2>&1 ')
这会将您的 stderr 重定向到 stdout
另一种方法是使用 %x[...] :
irb(main):027:0> def hello
irb(main):029:2* %x[hello]
irb(main):030:2> rescue Exception => e
irb(main):031:2> puts e.message
irb(main):033:1> end
=> nil
irb(main):034:0> hello
No such file or directory - hello
=> nil
irb(main):035:0>
也就是说,你可以挽救命令执行并返回异常信息
关于Ruby 系统调用获取有关命令失败的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6945585/