使用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 ...
For example... I am currently able to detect Ctrl-C by trapping...
# 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?
. 链接到文档
这篇关于使用ARGF在Ruby脚本中陷阱Ctrl-D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!