Loading

获取当前运行的终端大小

方法

shutil 模块有一个方法 .get_terminal_size,通过这个方法可以获取到当前运行的终端大小。
比如:

>>> import shutil

>>> shutil.get_terminal_size()
os.terminal_size(columns=195, lines=52)

>>> shutil.get_terminal_size().columns
195

将终端窗口缩小再次运行,会得到对应的值:

>>> shutil.get_terminal_size()
os.terminal_size(columns=120, lines=30)

该方法接收一个默认参数,用来在获取失败时返回,默认值为 (80, 24),如果有定义环境变量 COLUMNSLINES,且环境变量的值是一个正整数的话,那么会优先返回环境变量所定义的值。


扩展

os 模块也有一个同名的方法,不过根据其文档所说,更推荐使用 shutil 模块所提供的方法,因为 os 模块定义的方法是其更低层次的实现(shutil 模块的文档也说明,它是通过调用 os 模块所获取的)。
当然,实际使用过程中,两个模块所表现的几乎类似,不过 os 模块支持更多的底层的参数。


相关文档

shutil.get_terminal_size

Get the size of the terminal window.

For each of the two dimensions, the environment variable, COLUMNS
and LINES respectively, is checked. If the variable is defined and
the value is a positive integer, it is used.

When COLUMNS or LINES is not defined, which is the common case,
the terminal connected to sys.stdout is queried
by invoking os.get_terminal_size.

If the terminal size cannot be successfully queried, either because
the system doesn't support querying, or because we are not
connected to a terminal, the value given in fallback parameter
is used. Fallback defaults to (80, 24) which is the default
size used by many terminal emulators.

The value returned is a named tuple of type os.terminal_size.


os.get_terminal_size

Return the size of the terminal window as (columns, lines).

The optional argument fd (default standard output) specifies
which file descriptor should be queried.

If the file descriptor is not connected to a terminal, an OSError
is thrown.

This function will only be defined if an implementation is
available for this system.

shutil.get_terminal_size is the high-level function which should
normally be used, os.get_terminal_size is the low-level implementation.

如果想要了解 os.get_terminal_sizecpython 实现,可以查阅代码:cpython/Modules/posixmodule.c at main · python/cpython


参考

  1. shutil — High-level file operations — Python 3.12.4 documentation
  2. os — Miscellaneous operating system interfaces — Python 3.12.4 documentation
posted @ 2024-07-03 14:28  kingron  阅读(8)  评论(0编辑  收藏  举报