如何获取终端大小或字体大小(以像素为单位)?

问题描述 投票:0回答:6

我看过一些关于如何获取终端大小(以列数和行数表示)的帖子和答案。我可以获得终端大小,或者等效地,终端中使用的字体大小(以像素为单位)吗?

(我写了等价,因为终端宽度[px] = 字体宽度[px]*列数。或者这就是我所说的终端宽度。)

我正在寻找一种在 Linux 上使用 python 2 的方法,但我确实很欣赏仅适用于 python 3 的答案。谢谢!

python terminal
6个回答
6
投票

也许吧。如果您的终端软件支持XTerm控制序列,那么序列

\e[14t
将为您提供尺寸宽度*高度(以像素为单位)。

相关:

  • xtermctl - 将标准 xterm/dtterm 窗口控制代码放入 shell 参数中以方便使用。请注意,某些终端不支持所有组合。

4
投票

另一种可能的方法(支持有限)是检查 struct terminfo 的 ws_xpixel 和 ws_ypixel 值。

用于查询这些值的 python 代码片段:

import array, fcntl, termios buf = array.array('H', [0, 0, 0, 0]) fcntl.ioctl(1, termios.TIOCGWINSZ, buf) print(buf[2], buf[3])

这只适用于某些终端模拟器,其他模拟器总是报告

0 0

。参见例如
VTE 功能请求为支持矩阵设置这些字段


2
投票
Linux中存储终端信息的数据结构是

terminfo。这是任何一般终端查询都会读取的结构。它不包含像素信息,因为这与它旨在指定的纯文本终端无关。

如果您在 X 兼容终端中运行代码,则可能可以使用控制代码,但这很可能不可移植。


1
投票
所以,您已经知道如何获取字符中的终端大小(

此处)。

恐怕这是不可能的。 TTY 是一个文本终端,无法控制它的运行位置。 所以如果你的控制台程序在终端中执行,你无法知道它显示在哪里。

但是,您可以使用图形模式来控制字体、显示等。 但为什么是终端呢?您可以使用 GUI 来实现。


0
投票

tput cols

 告诉您列数。

tput lines
 告诉您行数。

所以

from subprocess import check_output cols = int(check_output(['tput', 'cols'])) lines = int(check_output(['tput', 'lines']))
    

0
投票
这是

egmont Aaron Digulla 的答案合并到一个脚本中:

import termios import array import fcntl import tty import sys def get_text_area_size(): # https://gist.github.com/secemp9/ab0ce0bfb0eaf73d831033dbfade44d9 + ... # Save the terminal's original settings fd = sys.stdin.fileno() original_attributes = termios.tcgetattr(fd) try: # Set the terminal to raw mode tty.setraw(sys.stdin.fileno()) # Query the text area size print("\x1b[14t", end="", flush=True) # Read the response (format: "\x1b[4;height;widtht") response = "" while True: # maybe add a timeout (eg. in nvim-toogleterm for example it stucks) char = sys.stdin.read(1) response += char if char == "t": break # Parse the response to extract height and width if response: return tuple(map(int, response[:-1].split(';')[1:])) else: # ... https://stackoverflow.com/a/43947507/11465149 buf = array.array('H', [0, 0, 0, 0]) fcntl.ioctl(1, termios.TIOCGWINSZ, buf) return (buf[3], buf[2]) finally: # Restore the terminal's original settings termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes) # Example usage text_area_size = get_text_area_size() if text_area_size: print(f"Text area size is {text_area_size[0]} rows by {text_area_size[1]} columns") else: print("Failed to get text area size")
感谢:

来源

© www.soinside.com 2019 - 2024. All rights reserved.