Ruby + Curses:非阻塞getch() + Trap (Ctrl+c) ?

时间:2021-06-09 20:43:24

I want to use Curses in Ruby:

我想在Ruby中使用Curses:

  1. getch() cannot block/suspend the program.
  2. getch()不能阻塞/挂起程序。
  3. When pressing q , exit the program immediately.
  4. 按q时,立即退出程序。
  5. A trap for Ctrl-C to avoid interruption.
  6. 用于Ctrl-C的陷阱,以避免中断。

However, I just can done the first point:

但是,我可以做第一点:

  1. When press q, it would wait for a while (< 1 sec) before exit.
  2. 当按q时,它会在退出前等待一段时间(< 1秒)。
  3. It seems that Curses makes the trap for Ctrl-C not work at all...
  4. 似乎诅咒会让Ctrl-C的陷阱完全失效……
# -*- coding: utf-8 -*-
require "curses"

Curses.init_screen
Curses.noecho()
Curses.curs_set(0)              #invisible cursor
Curses.timeout = 0
Curses.addstr("Press [q] to abort")
sec=0
while true

  # if place this outside the while loop, q key will be unable to work
  # at all...
  if Curses.getch == 'q'
    Curses.close_screen         #seems unnecessary
    exit
  end

  sec += 1
  hello = "Hello World #{sec}"
  Curses.setpos(Curses.lines / 2, Curses.cols / 2 - (hello.length / 2))
  Curses.addstr(hello)
  Curses.refresh
  sleep 1
end

# Avoid C-c interruption, but Curses seems to ignore it.
Signal.trap(:INT){
  return nil
}

1 个解决方案

#1


1  

When press q, it would wait for a while (< 1 sec) before exit.

当按q时,它会在退出前等待一段时间(< 1秒)。

You should combine unresponsive sleep with blocking input:
Set timeout = 1000 and remove sleep 1.

您应该将无响应睡眠与阻塞输入相结合:设置timeout = 1000,并删除sleep 1。

If this is not what you want, then you need multithreading.

如果这不是您想要的,那么您需要多线程。

A trap for Ctrl-C to avoid interruption.

用于Ctrl-C的陷阱,以避免中断。

You can use Curses.raw() to switch to raw mode, where all input will be transfered to you directly, without automatic handling of Ctrl+C and such.

您可以使用curs. raw()切换到原始模式,在此模式下,所有输入都将直接传递给您,而无需自动处理Ctrl+C等。

#1


1  

When press q, it would wait for a while (< 1 sec) before exit.

当按q时,它会在退出前等待一段时间(< 1秒)。

You should combine unresponsive sleep with blocking input:
Set timeout = 1000 and remove sleep 1.

您应该将无响应睡眠与阻塞输入相结合:设置timeout = 1000,并删除sleep 1。

If this is not what you want, then you need multithreading.

如果这不是您想要的,那么您需要多线程。

A trap for Ctrl-C to avoid interruption.

用于Ctrl-C的陷阱,以避免中断。

You can use Curses.raw() to switch to raw mode, where all input will be transfered to you directly, without automatic handling of Ctrl+C and such.

您可以使用curs. raw()切换到原始模式,在此模式下,所有输入都将直接传递给您,而无需自动处理Ctrl+C等。