Python — How do you view output that doesn't fit the screen?

前端 未结 9 1855
挽巷
挽巷 2021-02-05 10:27

I should say I\'m looking for a solution to the problem of viewing output that does not fit on your screen. For example, range(100) will show the last 30ish lin

9条回答
  •  半阙折子戏
    2021-02-05 11:02

    Say you're writing a program in Python and all it does is pretty print some stuff. The output is in prettiest_print_ever. You already do weird tricks importing fcntl, termios, struct and friends to get the terminal size so that you can use the full width of the terminal (if any); that also gives you the screen height, so it makes sense to use it. (That also means you've long given up any pretenses of cross-platform compatibility, too.)

    Sure, you can reinvent the wheel, or you can rely on less like other programs do (e.g. git diff). This should be the outline of a solution:

    def smart_print(prettiest_print_ever, terminal_height = 80):
      if len(prettiest_print_ever.splitlines()) <= terminal_height:
        #Python 3: make sure you write bytes!
        sys.stdout.buffer.write(prettiest_print_ever.encode("utf-8"))
      else
        less = subprocess.Popen("less", stdin=subprocess.PIPE)
        less.stdin.write(prettiest_print_ever.encode("utf-8"))
        less.stdin.close()
        less.wait()
    

提交回复
热议问题