diff options
author | Nick Coghlan <ncoghlan@gmail.com> | 2013-09-22 12:46:49 (GMT) |
---|---|---|
committer | Nick Coghlan <ncoghlan@gmail.com> | 2013-09-22 12:46:49 (GMT) |
commit | f94a16b494a2b21b8fcb90d666a31f6d78cabc26 (patch) | |
tree | 6c57e1aa09150175d484a45ae8351f0692cd04b3 /Lib/inspect.py | |
parent | 4c7fe6a5add2d773ae3a85679d22414d8eafe66c (diff) | |
download | cpython-f94a16b494a2b21b8fcb90d666a31f6d78cabc26.zip cpython-f94a16b494a2b21b8fcb90d666a31f6d78cabc26.tar.gz cpython-f94a16b494a2b21b8fcb90d666a31f6d78cabc26.tar.bz2 |
Close #18626: add a basic CLI for the inspect module
Diffstat (limited to 'Lib/inspect.py')
-rw-r--r-- | Lib/inspect.py | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/Lib/inspect.py b/Lib/inspect.py index 371bb35..5feef8f 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -2109,3 +2109,64 @@ class Signature: rendered += ' -> {}'.format(anno) return rendered + +def _main(): + """ Logic for inspecting an object given at command line """ + import argparse + import importlib + + parser = argparse.ArgumentParser() + parser.add_argument( + 'object', + help="The object to be analysed. " + "It supports the 'module:qualname' syntax") + parser.add_argument( + '-d', '--details', action='store_true', + help='Display info about the module rather than its source code') + + args = parser.parse_args() + + target = args.object + mod_name, has_attrs, attrs = target.partition(":") + try: + obj = module = importlib.import_module(mod_name) + except Exception as exc: + msg = "Failed to import {} ({}: {})".format(mod_name, + type(exc).__name__, + exc) + print(msg, file=sys.stderr) + exit(2) + + if has_attrs: + parts = attrs.split(".") + obj = module + for part in parts: + obj = getattr(obj, part) + + if module.__name__ in sys.builtin_module_names: + print("Can't get info for builtin modules.", file=sys.stderr) + exit(1) + + if args.details: + print('Target: {}'.format(target)) + print('Origin: {}'.format(getsourcefile(module))) + print('Cached: {}'.format(module.__cached__)) + if obj is module: + print('Loader: {}'.format(repr(module.__loader__))) + if hasattr(module, '__path__'): + print('Submodule search path: {}'.format(module.__path__)) + else: + try: + __, lineno = findsource(obj) + except Exception: + pass + else: + print('Line: {}'.format(lineno)) + + print('\n') + else: + print(getsource(obj)) + + +if __name__ == "__main__": + _main() |