加载中...

13.5 获取终端的大小


问题

You need to get the terminal size in order to properly format the output of your program.

解决方案

Use the os.get_terminal_size() function to do this:

  1. >>> import os
  2. >>> sz = os.get_terminal_size()
  3. >>> sz
  4. os.terminal_size(columns=80, lines=24)
  5. >>> sz.columns
  6. 80
  7. >>> sz.lines
  8. 24
  9. >>>

讨论

There are many other possible approaches for obtaining the terminal size, ranging fromreading environment variables to executing low-level system calls involving ioctl()and TTYs. Frankly, why would you bother with that when this one simple call willsuffice?


还没有评论.