htmlizer.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. #
  4. """
  5. HTML pretty-printing for Python source code.
  6. """
  7. __version__ = "$Revision: 1.8 $"[11:-2]
  8. import os
  9. import sys
  10. from twisted import copyright
  11. from twisted.python import htmlizer, usage
  12. header = """<html><head>
  13. <title>%(title)s</title>
  14. <meta name=\"Generator\" content="%(generator)s" />
  15. %(alternate)s
  16. %(stylesheet)s
  17. </head>
  18. <body>
  19. """
  20. footer = """</body>"""
  21. styleLink = '<link rel="stylesheet" href="%s" type="text/css" />'
  22. alternateLink = '<link rel="alternate" href="%(source)s" type="text/x-python" />'
  23. class Options(usage.Options):
  24. synopsis = """{} [options] source.py
  25. """.format(
  26. os.path.basename(sys.argv[0]),
  27. )
  28. optParameters = [
  29. ("stylesheet", "s", None, "URL of stylesheet to link to."),
  30. ]
  31. compData = usage.Completions(
  32. extraActions=[usage.CompleteFiles("*.py", descr="source python file")]
  33. )
  34. def parseArgs(self, filename):
  35. self["filename"] = filename
  36. def run():
  37. options = Options()
  38. try:
  39. options.parseOptions()
  40. except usage.UsageError as e:
  41. print(str(e))
  42. sys.exit(1)
  43. filename = options["filename"]
  44. if options.get("stylesheet") is not None:
  45. stylesheet = styleLink % (options["stylesheet"],)
  46. else:
  47. stylesheet = ""
  48. with open(filename + ".html", "wb") as output:
  49. outHeader = header % {
  50. "title": filename,
  51. "generator": f"htmlizer/{copyright.longversion}",
  52. "alternate": alternateLink % {"source": filename},
  53. "stylesheet": stylesheet,
  54. }
  55. output.write(outHeader.encode("utf-8"))
  56. with open(filename, "rb") as f:
  57. htmlizer.filter(f, output, htmlizer.SmallerHTMLWriter)
  58. output.write(footer.encode("utf-8"))