How to get Linux console window width in Python

后端 未结 14 1384
清歌不尽
清歌不尽 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条回答
  •  猫巷女王i
    2020-11-22 15:15

    Code above didn't return correct result on my linux because winsize-struct has 4 unsigned shorts, not 2 signed shorts:

    def terminal_size():
        import fcntl, termios, struct
        h, w, hp, wp = struct.unpack('HHHH',
            fcntl.ioctl(0, termios.TIOCGWINSZ,
            struct.pack('HHHH', 0, 0, 0, 0)))
        return w, h
    

    hp and hp should contain pixel width and height, but don't.

提交回复
热议问题