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

查看:300
本文介绍了如何在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"命令,该命令根据 a 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作为我的标准外壳程序无法访问)不同,数据也将是最新的,而我相信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).

(有关如何在python 3.3+上执行此操作的信息,请参见@GringoSuave的答案)

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

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

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