我一直在互联网上寻找这个答案一段时间,并发现其他人也在问同样的事情,即使在这里。所以这篇文章将介绍我的案例以及对我发现的解决方案的回应。
I've been looking for this answer in the internet for a while and have found other people asking the same thing, even here. So this post will be a presentation of my case and a response to the "solutions" that I have found.
我是Ruby的新手,但出于学习目的我决定创建一个gem,这里。 我正在尝试对该程序实现键盘导航,这将允许用户使用快捷方式来选择他想要查看的请求类型。在将来,箭头导航等等。
I am such new in Ruby, but for learning purposes I decided to create a gem, here. I am trying to implement a keyboard navigation to this program, that will allow the user use short-cuts to select what kind of request he want to see. And in the future, arrow navigations, etc.
我的问题:我找不到一种一致的方法来从用户控制台获取Ruby事件。
My problem: I can't find a consistent way to get the keyboard events from the user's console with Ruby.
我尝试过的解决方案:
这里是我试图去做的地方。 您可能会注意到我在显示我的文本之前使用stty -raw echo(关闭生成)和之后使用stty raw -echo(生成开启)。这样可以保持我的文本格式化。
Here is where I am trying to do it. You may note that I am using "stty -raw echo" (turns raw off) before show my text and "stty raw -echo" (turns raw on) after. That keeps my text formated.
但我的关键监听器循环不起作用。我的意思是,它有时有效,但不一致。如果按两次键不再有效,有时它也会单独停止。
But my key listener loop is not working. I mean, It works in sometimes but is not consistent. If a press a key twice it don't work anymore and sometimes it stops alone too.
让我把代码的一部分放在这里:
Let me put one part of the code here:
def run # Two loops run in parallel using Threads. # stream_log loops like a normal stream in the file, but it also parser the text. # break it into requests and store in @requests_queue. # stream_parsed_log stream inside the @requests_queue and shows it in the screen. @requests_queue = Queue.new @all_requests = Array.new # It's not working yet. Thread.new { listen_keyboard } Thread.new { stream_log } stream_parsed_log end def listen_keyboard # not finished loop do char = STDIN.getch case char when 'q' puts "Exiting." exit when 'a' @types_to_show = ['GET', 'POST', 'PUT', 'DELETE', 'ASSET'] requests_to_show = filter_to_show(@all_requests) command = true when 'p' @types_to_show = ['POST'] requests_to_show = filter_to_show(@all_requests) command = true end clear_screen if command @requests_queue += requests_to_show if command command = false end end我的路上需要一盏灯,我该怎么办?
I need a light in my path, what should I do?
推荐答案那是我的错。 这是在另一个线程中运行的另一部分代码中的逻辑错误,因此默认情况下ruby不会显示错误。我用ruby -d并意识到出了什么问题。这个错误搞砸了我的键盘输入。
That one was my mistake. It's just a logic error in another part of code that was running in another thread so the ruby don't shows the error by default. I used ruby -d and realized what was wrong. This mistake was messing my keyboard input.
所以现在它已修复,我正在使用STDIN.getch没有问题。 我只是在显示任何字符串之前关闭原始模式。一切正常。
So now it's fixed and I am using STDIN.getch with no problem. I just turn the raw mode off before show any string. And everything is ok.
你可以查看此处,或 gem 本身。
就是这样。
更多推荐
在Ruby控制台应用程序中获取键盘事件(没有按'enter'输入)的最佳方法是什么?
发布评论