我看过一些关于如何获取终端大小(以列数和行数表示)的帖子和答案。我可以获得终端大小,或者等效地,终端中使用的字体大小(以像素为单位)吗?
(我写了等价,因为终端宽度[px] = 字体宽度[px]*列数。或者这就是我所说的终端宽度。)
我正在寻找一种在 Linux 上使用 python 2 的方法,但我确实很欣赏仅适用于 python 3 的答案。谢谢!
另一种可能的方法(支持有限)是检查 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 功能请求为支持矩阵设置这些字段。
terminfo。这是任何一般终端查询都会读取的结构。它不包含像素信息,因为这与它旨在指定的纯文本终端无关。
如果您在 X 兼容终端中运行代码,则可能可以使用控制代码,但这很可能不可移植。
此处)。
恐怕这是不可能的。 TTY 是一个文本终端,无法控制它的运行位置。 所以如果你的控制台程序在终端中执行,你无法知道它显示在哪里。但是,您可以使用图形模式来控制字体、显示等。 但为什么是终端呢?您可以使用 GUI 来实现。
tput cols
告诉您列数。
tput lines
告诉您行数。所以
from subprocess import check_output
cols = int(check_output(['tput', 'cols']))
lines = int(check_output(['tput', 'lines']))
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")
感谢: