python - Limiting print output -
i have number of objects need print out terminal (for debugging). normal print
function perfect, except objects large, print
create millions of lines of output. i'd create function print
does, except output truncated after predefined number of characters, replacing rest ...
.
what's way that?
note performance concern, ideally i'd prefer not save gigabyte-sized string , take first few characters it; similarly, pprint
bit of problem since sorts keys in dictionaries (and millions of keys takes while).
example:
obj = [ [1, 2, 3], list(range(1000000)) ] my_print(obj, 20) # should output: # [[1, 2, 3], [0, 1, 2...
python 3, if matters.
the reprlib
module (python 3.x only) suggested @m0nhawk made purpose. here's how use it:
if you're fine default limits, can use reprlib.repr(obj)
:
import reprlib obj = [[1, 2, 3], list(range(10000))] print(reprlib.repr(obj))
output:
[[1, 2, 3], [0, 1, 2, 3, 4, 5, ...]]
in order customize available limits, create reprlib.repr
instance , set appropriate instance attributes:
r = reprlib.repr() r.maxlist = 4 # max elements displayed lists r.maxstring = 10 # max characters displayed strings obj = [[1, 2, 3], list(range(10000)), 'looooooong string', 'a', 'b', 'c'] print(r.repr(obj))
output:
[[1, 2, 3], [0, 1, 2, 3, ...], 'lo...ing', 'a', ...]
if you're dealing sequence objects refer themselves, can use repr.maxlevel
limit recursion depth:
lst = [1, 2, 3] lst.append(lst) # oh my! r = reprlib.repr() r.maxlevel = 5 # max recursion depth print(r.repr(lst))
output:
[1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [...]]]]]]
note reprlib.repr()
returns string, doesn't print
(unless you're in interactive console result of every expression enter gets evaluated , representation displayed).
Comments
Post a Comment