如何在 Python 中获取 Linux 控制台窗口的宽度 [英] How to get Linux console window width in Python

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

问题描述

在 python 中有没有办法以编程方式确定控制台的宽度?我的意思是一行中不换行的字符数,而不是窗口的像素宽度.

Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.

编辑

寻找适用于 Linux 的解决方案

Looking for a solution that works on Linux

推荐答案

import os
rows, columns = os.popen('stty size', 'r').read().split()

根据一个线程使用'stty size'命令在 python 邮件列表中 在 linux 上相当普遍.它将stty size"命令作为文件打开,从中读取",并使用简单的字符串拆分来分隔坐标.

uses the 'stty size' command which according to a thread on the python mailing list is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from it, and uses a simple string split to separate the coordinates.

与 os.environ["COLUMNS"] 值不同(尽管我使用 bash 作为我的标准 shell,但我无法访问该值),数据也将是最新的,而我相信 os.environ["COLUMNS"] 值仅在 python 解释器启动时有效(假设用户从那时起调整了窗口大小).

Unlike the os.environ["COLUMNS"] value (which I can't access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ["COLUMNS"] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).

(请参阅@GringoSuave 的回答,了解如何在 python 3.3+ 上执行此操作)

(See answer by @GringoSuave on how to do this on python 3.3+)

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

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