您是否注意到,如果在rails中运行rake -T,rake描述的列表将被终端窗口的宽度截断。所以应该有一种方法让它进入Ruby并使用它。
我正在屏幕上打印一些Ascii-art,我不想让它坏掉。因此,我需要找出终端在运行时的宽度。
你知道怎么做吗?
发布于 2012-05-04 14:54:40
我发现在Ubuntu上,如果在Ruby应用程序运行时调整终端的大小,这里指定的其他方法(ENV['COLUMNS']、tput columns或hirb)都不会给出正确的结果。这不是脚本的问题,而是交互式控制台的问题,比如irb。
到目前为止,ruby-terminfo gem是我找到的最好的解决方案,可以在调整大小后给出正确的尺寸,但它需要安装一个额外的gem,并且是特定于unix的。
gem的用法很简单:
require 'terminfo'
p TermInfo.screen_size # [lines, columns]TermInfo内部使用TIOCGWINSZ ioctl作为屏幕尺寸。
或者,正如user83510提到的,highline的system_extensions也可以工作:
require 'highline'
HighLine::SystemExtensions.terminal_size # [columns, lines]在内部,highline在Unix上使用stty size,在ncurses和Windows上使用其他实现。
为了监听终端大小的变化(而不是轮询),我们可以捕获SIGWINCH信号:
require 'terminfo'
Signal.trap('SIGWINCH', proc { puts TermInfo.screen_size.inspect })这对于使用Readline的应用程序特别有用,例如irb:
Signal.trap('SIGWINCH', proc { Readline.set_screen_size(TermInfo.screen_size[0], TermInfo.screen_size[1]) })发布于 2010-01-15 09:30:08
有一个常见的unix命令:
tput cols该函数返回终端的宽度。
发布于 2014-01-25 03:59:48
def winsize
#Ruby 1.9.3 added 'io/console' to the standard library.
require 'io/console'
IO.console.winsize
rescue LoadError
# This works with older Ruby, but only with systems
# that have a tput(1) command, such as Unix clones.
[Integer(`tput li`), Integer(`tput co`)]
end
rows, cols = winsize
printf "%d rows by %d columns\n", rows, colsLink
https://stackoverflow.com/questions/2068859
复制相似问题