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. from __future__ import print_function
  8. __version__ = '$Revision: 1.8 $'[11:-2]
  9. from twisted.python import htmlizer, usage
  10. from twisted import copyright
  11. import os, sys
  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 = """%s [options] source.py
  25. """ % (
  26. os.path.basename(sys.argv[0]),)
  27. optParameters = [
  28. ('stylesheet', 's', None, "URL of stylesheet to link to."),
  29. ]
  30. compData = usage.Completions(
  31. extraActions=[usage.CompleteFiles('*.py', descr='source python file')]
  32. )
  33. def parseArgs(self, filename):
  34. self['filename'] = filename
  35. def run():
  36. options = Options()
  37. try:
  38. options.parseOptions()
  39. except usage.UsageError as e:
  40. print(str(e))
  41. sys.exit(1)
  42. filename = options['filename']
  43. if options.get('stylesheet') is not None:
  44. stylesheet = styleLink % (options['stylesheet'],)
  45. else:
  46. stylesheet = ''
  47. with open(filename + '.html', 'wb') as output:
  48. outHeader = (header % {
  49. 'title': filename,
  50. 'generator': 'htmlizer/%s' % (copyright.longversion,),
  51. 'alternate': alternateLink % {'source': filename},
  52. 'stylesheet': stylesheet
  53. })
  54. output.write(outHeader.encode("utf-8"))
  55. with open(filename, 'rb') as f:
  56. htmlizer.filter(f, output, htmlizer.SmallerHTMLWriter)
  57. output.write(footer.encode("utf-8"))