如何在Ruby中获取终端窗口的宽度 [英] How to get the width of terminal window in Ruby

查看:38
本文介绍了如何在Ruby中获取终端窗口的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您有没有注意到,如果您在 rails 中运行 rake -T,则 rake 描述列表会被终端窗口的宽度截断.所以应该有一种方法可以在 Ruby 中获取它并使用它.

Have you ever noticed that if you run rake -T in rails the list of rake descriptions are truncated by the width of the terminal window. So there should be a way to get it in Ruby and Use it.

我正在屏幕上打印一些 Ascii-art,但我不希望它被破坏.因此我需要以某种方式找出运行时终端的宽度.

I'm printing some Ascii-art on the screen and I don't want it to be broken. therefore I need to find out the width of terminal at run time some how.

知道怎么做吗?

推荐答案

我发现在 Ubuntu 上,这里没有指定任何其他方法 (ENV['COLUMNS'], 如果在 Ruby 应用程序运行时调整终端的大小,tput columns 或 hirb) 会给出正确的结果.这不是脚本的问题,而是交互式控制台的问题,例如 irb.

I've found that on Ubuntu, none of the other methods specified here (ENV['COLUMNS'], tput columns or hirb) give the correct result if the terminal is resized while the Ruby application is running. This is not an issue for scripts, but it is an issue for interactive consoles, such as irb.

ruby-terminfo gem 是迄今为止我找到的最佳解决方案调整大小后正确的尺寸,但它需要您安装额外的 gem,并且是特定于 Unix 的.

The ruby-terminfo gem is the best solution I've find so far to give the correct dimensions after a resize, but it requires that you install an additional gem, and is unix-specific.

gem 的用法很简单:

The gem's usage is simple:

require 'terminfo'
p TermInfo.screen_size        # [lines, columns]

TermInfo 在内部使用 TIOCGWINSZ ioctl 作为屏幕尺寸.

TermInfo internally uses TIOCGWINSZ ioctl for the screen size.

或者,如 user83510 所述,highline 的 system_extensions 也有效:

Alternatively, as mentioned by user83510, highline's system_extensions also works:

require 'highline'
HighLine::SystemExtensions.terminal_size # [columns, lines]

实际上,highline 在 Unix 上使用 stty size,并在 ncurses 和 Windows 上使用其他实现.

Interally, highline uses stty size on Unix, and other implementations for ncurses and Windows.

为了监听终端大小的变化(而不是轮询),我们可以捕获 SIGWINCH 信号:

To listen for changes to the terminal size (instead of polling), we can trap the SIGWINCH signal:

require 'terminfo'
Signal.trap('SIGWINCH', proc { puts TermInfo.screen_size.inspect })

这对于使用 Readline 的应用程序特别有用,例如 irb:

This is specifically useful for applications using Readline, such as irb:

Signal.trap('SIGWINCH', proc { Readline.set_screen_size(TermInfo.screen_size[0], TermInfo.screen_size[1]) })

这篇关于如何在Ruby中获取终端窗口的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆