使用 ARGF 在 Ruby 脚本中捕获 Ctrl-D [英] Trap Ctrl-D in a Ruby Script with ARGF
问题描述
我目前正在使用 ARGV.gets 从命令行捕获用户输入.我想允许 Ctrl-D 终止脚本,但不知道如何使用 Signal.trap 或通过错误处理来执行此操作.我试图找到像 Ctrl-D 这样的陷阱代码列表,但找不到我要找的任何东西.同样,拯救 Exception 不起作用,因为 Ctrl-D 不会引发异常.是否有 Ctrl-D 的陷阱代码或任何其他检测方法?
I am currently using ARGV.gets to capture user input from the command line. I want to allow Ctrl-D terminate the script, but don't know how to do this using Signal.trap or through error handling. I tried to find a list of trap codes for something like Ctrl-D but was unable to find anything I was looking for. Likewise, rescuing Exception doesn't work because Ctrl-D doesn't raise an exception. Is there a trap code for Ctrl-D or any other way to detect this?
例如...我目前能够通过陷印来检测 Ctrl-C...
# Trap ^C
Signal.trap("INT") {
# Do something
exit
}
或错误处理...
def get_input
input = ARGF.gets
input.strip!
rescue SystemExit, Interrupt => e
# If we get here, Ctrl-C was encountered
end
但是,我无法捕获或检测 Ctrl-D.
However, I haven't been able to trap or detect Ctrl-D.
推荐答案
ARGF
只是流的一个特例.Ctrl + D
只是输入的结尾.
ARGF
in just a special case of stream. Ctrl + D
is just end of input.
考虑到这一点,请使用方法 ARGF.eof?
.文档链接一个>
With this in mind use method ARGF.eof?
. Link to documentation
这篇关于使用 ARGF 在 Ruby 脚本中捕获 Ctrl-D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!