Last active
April 30, 2020 20:52
-
-
Save rfinnie/a4346e4bc6782bf28e67c3823accad9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# auto_pager.py | |
# Copyright (C) 2018 Ryan Finnie | |
# | |
# This program is free software; you can redistribute it and/or | |
# modify it under the terms of the GNU General Public License | |
# as published by the Free Software Foundation; either version 2 | |
# of the License, or (at your option) any later version. | |
# | |
# This program is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program; if not, write to the Free Software | |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA | |
# 02110-1301, USA. | |
import sys | |
import os | |
import shlex | |
import subprocess | |
class AutoPager: | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.close() | |
def __init__(self): | |
self.closed = False | |
self.pager = None | |
if sys.stdout.isatty(): | |
pager_cmd = ["pager"] | |
if os.environ.get("PAGER"): | |
pager_cmd = shlex.split(os.environ.get("PAGER")) | |
env = os.environ.copy() | |
if not os.environ.get("LESS"): | |
env.update({"LESS": "-FRSXMQ"}) | |
try: | |
self.pager = subprocess.Popen( | |
pager_cmd, | |
stdin=subprocess.PIPE, | |
stdout=sys.stdout, | |
encoding="UTF-8", | |
env=env, | |
) | |
except FileNotFoundError: | |
pass | |
def write(self, l): | |
if self.closed: | |
return | |
if self.pager: | |
try: | |
self.pager.stdin.write(l) | |
except KeyboardInterrupt: | |
self.close() | |
except BrokenPipeError: | |
self.close() | |
else: | |
try: | |
sys.stdout.write(l) | |
except BrokenPipeError: | |
self.close() | |
def close(self): | |
if self.closed: | |
return | |
if self.pager: | |
try: | |
self.pager.stdin.close() | |
except BrokenPipeError: | |
pass | |
ret = None | |
while ret is None: | |
try: | |
ret = self.pager.wait() | |
except KeyboardInterrupt: | |
continue | |
self.closed = True | |
if __name__ == "__main__": | |
with AutoPager() as pager: | |
for i in range(1000): | |
print(i, file=pager) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment