Skip to content

Instantly share code, notes, and snippets.

@presto8
Forked from gesquive/python-less-pager.py
Last active January 17, 2021 20:12
Show Gist options
  • Save presto8/c124b665de66245c1e0608b25cab8f44 to your computer and use it in GitHub Desktop.
Save presto8/c124b665de66245c1e0608b25cab8f44 to your computer and use it in GitHub Desktop.
Use less to page output
import subprocess
import sys
import os
def output_to_pager(text, command=None):
if not sys.stdout.isatty():
for line in text:
sys.stdout.write(line + os.linesep)
return
if command is None:
# args stolen from git source, see `man less`
command = "less -F -R -S -X -K".split()
try:
pager = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=sys.stdout)
for line in text:
pager.stdin.write((line + os.linesep).encode('utf8'))
pager.stdin.close()
pager.wait()
except KeyboardInterrupt:
pass
# let less handle this, -K will exit cleanly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment