# Copyright (c) 2014 yuzurihara. All rights reserved. | |
# Released under the BSD 3-Clause License. | |
# http://opensource.org/licenses/BSD-3-Clause | |
import os | |
import sys | |
import subprocess | |
import atexit | |
def with_pager(func, *args, **kwargs): | |
pager = os.getenv('PAGER', '/usr/bin/less') | |
p2 = None | |
stdout_save = sys.stdout | |
def on_exit(): | |
if p2: | |
p2.stdin.close() | |
p2.wait() | |
sys.stdout = stdout_save | |
if pager and os.isatty(sys.stdout.fileno()): | |
p2 = subprocess.Popen( | |
pager, shell=True, | |
stdin=subprocess.PIPE, | |
universal_newlines=True) | |
if p2.poll() is None: | |
sys.stdout = p2.stdin | |
atexit.register(on_exit) | |
else: # Popen() failed. | |
p2 = None | |
try: | |
retval = func(*args, **kwargs) | |
finally: | |
on_exit() | |
atexit.unregister(on_exit) | |
return retval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment