I should say I\'m looking for a solution to the problem of viewing output that does not fit on your screen. For example, range(100) will show the last 30ish lin
Say you're writing a program in Python and all it does is pretty print some stuff. The output is in prettiest_print_ever
. You already do weird tricks importing fcntl
, termios
, struct
and friends to get the terminal size so that you can use the full width of the terminal (if any); that also gives you the screen height, so it makes sense to use it. (That also means you've long given up any pretenses of cross-platform compatibility, too.)
Sure, you can reinvent the wheel, or you can rely on less like other programs do (e.g. git diff
). This should be the outline of a solution:
def smart_print(prettiest_print_ever, terminal_height = 80):
if len(prettiest_print_ever.splitlines()) <= terminal_height:
#Python 3: make sure you write bytes!
sys.stdout.buffer.write(prettiest_print_ever.encode("utf-8"))
else
less = subprocess.Popen("less", stdin=subprocess.PIPE)
less.stdin.write(prettiest_print_ever.encode("utf-8"))
less.stdin.close()
less.wait()
just for fun :o)
Original version for Python2:
class Less(object):
def __init__(self, num_lines):
self.num_lines = num_lines
def __ror__(self, other):
s = str(other).split("\n")
for i in range(0, len(s), self.num_lines):
print "\n".join(s[i: i + self.num_lines])
raw_input("Press <Enter> for more")
less = Less(num_lines=30)
"\n".join(map(str, range(100))) | less
a Python3 version:
class Less(object):
def __init__(self, num_lines):
self.num_lines = num_lines
def __ror__(self, other):
s = str(other).split("\n")
for i in range(0, len(s), self.num_lines):
print(*s[i: i + self.num_lines], sep="\n")
input("Press <Enter> for more")
less = Less(num_lines=30)
"\n".join(map(str, range(100))) | less
if your data is json serilizable then you can try
import simplejson
print simplejson.dumps({'shipping-line': {'price': '0.00', 'code': 'Local Pickup (Portland, OR)', 'title': 'Local Pickup (Portland, OR)'}}, indent=4)
Output will be look something like
{
"shipping-line": {
"price": "0.00",
"code": "Local Pickup (Portland, OR)",
"title": "Local Pickup (Portland, OR)"
}
}
this is specifically used to debug and to see the actual content......in well readble format..
EDIT:
if your screen is limited to 25 lines..........
import simplejson
data = simplejson.dumps({'shipping-line': {'price': '0.00', 'code': 'Local Pickup (Portland, OR)', 'title': 'Local Pickup (Portland, OR)'}}, indent=4)
cnt = 0
for line in data.split('\n'):
cnt+=1
print line
raw_input() if cnt%25==0 else None