How to get Linux console window width in Python

后端 未结 14 1322
清歌不尽
清歌不尽 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:16

    Many of the Python 2 implementations here will fail if there is no controlling terminal when you call this script. You can check sys.stdout.isatty() to determine if this is in fact a terminal, but that will exclude a bunch of cases, so I believe the most pythonic way to figure out the terminal size is to use the builtin curses package.

    import curses
    w = curses.initscr()
    height, width = w.getmaxyx()
    

提交回复
热议问题