How to get Linux console window width in Python

后端 未结 14 1143
清歌不尽
清歌不尽 2020-11-22 15:08

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

14条回答
  •  忘了有多久
    2020-11-22 15:24

    I was trying the solution from here that calls out to stty size:

    columns = int(subprocess.check_output(['stty', 'size']).split()[1])
    

    However this failed for me because I was working on a script that expects redirected input on stdin, and stty would complain that "stdin isn't a terminal" in that case.

    I was able to make it work like this:

    with open('/dev/tty') as tty:
        height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()
    

提交回复
热议问题