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\'
It is a good idea to be explicit in your code, so that it shows that you use a special print function printc() instead of the standard one. Using subprocess.call() is also sufficient (you don't need the pipe machinery). Furthermore, you can save a variable by not storing the name of the temporary file:
from __future__ import print_function
import subprocess, tempfile
page = True # For tests
# Definition of a printc() function that prints to the correct output
if page:
tmp_file = open(tempfile.mkstemp()[1], 'w') # No need to store the name in a specific variable
def printc(*largs, **kwargs):
if 'file' not in kwargs: # The code can still use the usual file argument of print()
kwargs['file'] = tmp_file # Forces the output to go to the temp file
print(*largs, **kwargs)
else:
printc = print # Regular print
# Main program:
printc('...some text...', 'some more text', sep='/') # Python3 syntax
# Paging of the current contents of the temp file:
if page:
tmp_file.flush() # No need to close the file: you can keep printing to it
subprocess.call(['less', tmp_file.name]) # Simpler than a full Popen()
This way, you get the flexibility of Python 3's print function, with a code that explicitly shows that you're doing some fancy printing stuff. This scales better with larger programs than modifying the "global" sys.stdout variable in some locations of your code.