简体   繁体   English

在END {}中访问Ruby退出代码

[英]Access Ruby exit code in END {}

Ruby has BEGIN {} and END {} blocks that guarantee they run before and after the main portion of code, respectively. Ruby具有BEGIN {}END {}块,以确保它们分别在代码主要部分之前和之后运行。

I have the following code: 我有以下代码:

BEGIN {
  $my_args = ARGV.dup
  ARGV.clear
} # clean up 'gets'

# For the truly paranoid in all of us
def self.run_away?
  print "You're paranoid. Exit? (Y/n) "
  ans = gets.chomp.downcase
  if ["no", "n"].include?(ans)
    puts "Alright, your call. Let's keep going."
  else
    puts "EXITING"
    log("Exiting at paranoid users request.")
    exit 3
  end
end

END {  } # do stuff here

I have a handful of error codes that I have defined in my script. 我在脚本中定义了一些错误代码。 I would like to be able to read the error code and print a short description based on that code. 我希望能够读取错误代码并根据该代码打印简短说明。 Eg - EXITING - 3: Exit at user request instead of writing a descriptive string every time I use an exit in my code. 例如EXITING - 3: Exit at user request每次我在代码中使用exitEXITING - 3: Exit at user request而不是编写描述性字符串。 Is there a way to do this in the END {} block? 是否可以在END {}块中执行此操作? Or something else I am missing? 还是我想念的其他东西?

Edit/Note: I'm stuck with Ruby 1.8.7 and the following doesn't work: (see below) 编辑/注意:我坚持使用Ruby 1.8.7 ,以下内容不起作用:( 请参见下文)

BEGIN { puts "BEGIN block!" }

puts "Main block!"
exit 3

END {
  puts "END block!"
  puts "Current Exception: \n#{$!}"
  puts "Current Backtrace: \n#{$@}"
}

Output: 输出:

~: $ ./test.rb 
BEGIN block!
Main block!
~: $ echo $?
3
~: $

Edit #2: I had to define my END block before I exited. 编辑#2:我必须在退出之前定义END块。 Thanks to @Stefan 感谢@Stefan

Kernel#exit raises a SystemExit exception and since the global variable $! Kernel#exit引发SystemExit异常,并且由于全局变量$! contains the current exception, you can get the exit status via $!.status : 包含当前异常,您可以通过$!.status获取退出$!.status

END {
  puts "exit status: #{$!.status}"
}
exit 3

Output: 输出:

exit status: 3

From the documentation : 文档中

When an exception has been raised but not yet handled (in rescue , ensure , at_exit and END blocks) the global variable $! 如果引发了异常但尚未处理异常(在rescue ,请ensure at_exitEND块),则全局变量$! will contain the current exception and $@ contains the current exception's backtrace. 将包含当前异常,而$@包含当前异常的回溯。

A way to centralize exit message : 集中退出消息的一种方法:

module Kernel
  alias :real_exit :exit

  def exit status
    puts "Hello World"
    real_exit status
  end
end

The method is just an around alias on the Kernel#exit method . 该方法只是Kernel#exit方法的一个别名。 Be aware that once you will have define this override, all other exit call will go through your override. 请注意,一旦您定义了该替代,所有其他出口呼叫将遍历您的替代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM