How to get Linux console window width in Python

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

    It's either:

    import os
    columns, rows = os.get_terminal_size(0)
    # or
    import shutil
    columns, rows = shutil.get_terminal_size()
    

    The shutil function is just a wrapper around os one that catches some errors and set up a fallback, however it has one huge caveat - it breaks when piping!, which is a pretty huge deal.
    To get terminal size when piping use os.get_terminal_size(0) instead.

    First argument 0 is an argument indicating that stdin file descriptor should be used instead of default stdout. We want to use stdin because stdout detaches itself when it is being piped which in this case raises an error.

    I've tried to figure out when would it makes sense to use stdout instead of stdin argument and have no idea why it's a default here.

提交回复
热议问题