Logic for inspecting an object given at command line
()
| 3347 | |
| 3348 | |
| 3349 | def _main(): |
| 3350 | """ Logic for inspecting an object given at command line """ |
| 3351 | import argparse |
| 3352 | import importlib |
| 3353 | |
| 3354 | parser = argparse.ArgumentParser(color=True) |
| 3355 | parser.add_argument( |
| 3356 | 'object', |
| 3357 | help="The object to be analysed. " |
| 3358 | "It supports the 'module:qualname' syntax") |
| 3359 | parser.add_argument( |
| 3360 | '-d', '--details', action='store_true', |
| 3361 | help='Display info about the module rather than its source code') |
| 3362 | |
| 3363 | args = parser.parse_args() |
| 3364 | |
| 3365 | target = args.object |
| 3366 | mod_name, has_attrs, attrs = target.partition(":") |
| 3367 | try: |
| 3368 | obj = module = importlib.import_module(mod_name) |
| 3369 | except Exception as exc: |
| 3370 | msg = "Failed to import {} ({}: {})".format(mod_name, |
| 3371 | type(exc).__name__, |
| 3372 | exc) |
| 3373 | print(msg, file=sys.stderr) |
| 3374 | sys.exit(2) |
| 3375 | |
| 3376 | if has_attrs: |
| 3377 | parts = attrs.split(".") |
| 3378 | obj = module |
| 3379 | for part in parts: |
| 3380 | obj = getattr(obj, part) |
| 3381 | |
| 3382 | if module.__name__ in sys.builtin_module_names: |
| 3383 | print("Can't get info for builtin modules.", file=sys.stderr) |
| 3384 | sys.exit(1) |
| 3385 | |
| 3386 | if args.details: |
| 3387 | print('Target: {}'.format(target)) |
| 3388 | print('Origin: {}'.format(getsourcefile(module))) |
| 3389 | print('Cached: {}'.format(module.__cached__)) |
| 3390 | if obj is module: |
| 3391 | print('Loader: {}'.format(repr(module.__loader__))) |
| 3392 | if hasattr(module, '__path__'): |
| 3393 | print('Submodule search path: {}'.format(module.__path__)) |
| 3394 | else: |
| 3395 | try: |
| 3396 | __, lineno = findsource(obj) |
| 3397 | except Exception: |
| 3398 | pass |
| 3399 | else: |
| 3400 | print('Line: {}'.format(lineno)) |
| 3401 | |
| 3402 | print('\n') |
| 3403 | else: |
| 3404 | print(getsource(obj)) |
| 3405 | |
| 3406 |
no test coverage detected