Skip to content

Instantly share code, notes, and snippets.

@FilipDominec
Created September 21, 2017 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FilipDominec/c2731c7ea8d59dd0929d1b095172df22 to your computer and use it in GitHub Desktop.
Save FilipDominec/c2731c7ea8d59dd0929d1b095172df22 to your computer and use it in GitHub Desktop.
Recursively prints all attributes, lists, dicts etc. of a given object - here used for analysis of a parsed OPJ file
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import liborigin
opj = liborigin.parseOriginFile('../test.opj')
coloured = True
if coloured:
normal = "\033[1;0m"
bold = "\033[1;1m"
grey = "\033[1;2m"
else:
normal, bold , grey = '', '', ''
maxlistlen = 5
allstrings = []
def explore(obj, parentstr, indent):
print(indent + parentstr)
if coloured: indent = indent + grey + parentstr + normal ## prints ancestry objects with grey color for better clarity (terminal only)
else: indent = indent + ' '*len(parentstr) ## replaces ancestry objects with whitespace for clarity
if len(indent)>200:
print(' --------------- nesting too deep - halted here ----------------')
return
if type(obj) == list:
print(indent+bold+'[', normal)
for n, item in enumerate(obj[:maxlistlen]):
explore(item, '[%d]' % n, indent)
if len(obj) > maxlistlen:
print(indent+bold+'--- listing truncated here, %d values would follow ---' % (len(obj)-maxlistlen))
print(indent+bold+']', normal)
elif type(obj) == dict:
print(indent+bold+'{', normal)
for key, value in obj.items():
explore(value, '["'+key+'"]', indent)
print(indent+bold+'}', normal)
elif type(obj) == str:
print(indent+bold+'"'+obj+'"', normal)
allstrings.append(obj)
elif type(obj) == bytes:
print(indent+bold+' b"'+obj.decode('utf-8').strip()+'"')
elif type(obj) in (float, int, bool):
print(indent+bold,obj, normal)
else:
print(indent, bold, obj, grey, type(obj), normal)
usefulattrs = [attrname for attrname in dir(obj) if not attrname.startswith('__')]
print(' '*(len(indent)-len(parentstr)), grey, usefulattrs, normal)
for attrname in usefulattrs:
explore(getattr(obj, attrname), '.'+attrname, indent)
explore(opj, '', '')
print(allstrings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment