Created
November 20, 2014 05:44
-
-
Save yuzurihara/3b805aa29aad20e7506e 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
# 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