Skip to content

Instantly share code, notes, and snippets.

@yuzurihara
Created November 20, 2014 05:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuzurihara/3b805aa29aad20e7506e to your computer and use it in GitHub Desktop.
Save yuzurihara/3b805aa29aad20e7506e to your computer and use it in GitHub Desktop.
# 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