I'm trying to implement something similar to git log
, which will only page the output if the log is of a certain length. If you're not familiar with git, I'm essentially trying to achieve this:
python some_script.py | less
With some help from the paging implementation in python2.6/pydoc.py, I was able to come up with this:
import os
text = '...some text...'
pipe = os.popen('less', 'w')
pipe.write(text)
pipe.close()
which works great, but os.popen() is deprecated. I've considered writing to a temp file and calling less with its path, but that doesn't seem ideal. Is this possible with subprocess? Any other ideas?
EDIT:
So I've gotten subprocess working. I was able to give it the text variable with Popen.communicate(text)
, but since I really want to redirect print statements, I've settled on this:
import os, sys, subprocess, tempfile
page = True
if page:
path = tempfile.mkstemp()[1]
tmp_file = open(path, 'a')
sys.stdout = tmp_file
print '...some text...'
if page:
tmp_file.flush()
tmp_file.close()
p = subprocess.Popen(['less', path], stdin=subprocess.PIPE)
p.communicate()
sys.stdout = sys.__stdout__
Of course, I'd end up wrapping it into functions. Does anyone see a problem with that?