__main__.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import sys
  2. import os
  3. import argparse
  4. from .modulegraph import ModuleGraph
  5. def parse_arguments():
  6. parser = argparse.ArgumentParser(
  7. conflict_handler='resolve', prog='%s -mmodulegraph' % (
  8. os.path.basename(sys.executable)))
  9. parser.add_argument(
  10. '-d', action='count', dest='debug', default=1,
  11. help='Increase debug level')
  12. parser.add_argument(
  13. '-q', action='store_const', dest='debug', const=0,
  14. help='Clear debug level')
  15. parser.add_argument(
  16. '-m', '--modules', action='store_true',
  17. dest='domods', default=False,
  18. help='arguments are module names, not script files')
  19. parser.add_argument(
  20. '-x', metavar='NAME', action='append', dest='excludes',
  21. default=[], help='Add NAME to the excludes list')
  22. parser.add_argument(
  23. '-p', action='append', metavar='PATH', dest='addpath', default=[],
  24. help='Add PATH to the module search path')
  25. parser.add_argument(
  26. '-g', '--dot', action='store_const', dest='output', const='dot',
  27. help='Output a .dot graph')
  28. parser.add_argument(
  29. '-h', '--html', action='store_const',
  30. dest='output', const='html', help='Output a HTML file')
  31. parser.add_argument(
  32. 'scripts', metavar='SCRIPT', nargs='+', help='scripts to analyse')
  33. opts = parser.parse_args()
  34. return opts
  35. def create_graph(scripts, domods, debuglevel, excludes, path_extras):
  36. # Set the path based on sys.path and the script directory
  37. path = sys.path[:]
  38. if domods:
  39. del path[0]
  40. else:
  41. path[0] = os.path.dirname(scripts[0])
  42. path = path_extras + path
  43. if debuglevel > 1:
  44. print("path:", file=sys.stderr)
  45. for item in path:
  46. print(" ", repr(item), file=sys.stderr)
  47. # Create the module finder and turn its crank
  48. mf = ModuleGraph(path, excludes=excludes, debug=debuglevel)
  49. for arg in scripts:
  50. if domods:
  51. if arg[-2:] == '.*':
  52. mf.import_hook(arg[:-2], None, ["*"])
  53. else:
  54. mf.import_hook(arg)
  55. else:
  56. mf.add_script(arg)
  57. return mf
  58. def output_graph(output_format, mf):
  59. if output_format == 'dot':
  60. mf.graphreport()
  61. elif output_format == 'html':
  62. mf.create_xref()
  63. else:
  64. mf.report()
  65. def main():
  66. opts = parse_arguments()
  67. mf = create_graph(
  68. opts.scripts, opts.domods, opts.debug,
  69. opts.excludes, opts.addpath)
  70. output_graph(opts.output, mf)
  71. if __name__ == '__main__': # pragma: no cover
  72. try:
  73. main()
  74. except KeyboardInterrupt:
  75. print("\n[interrupt]")