1

I am looking for advice on how I might best turn a large amount of program output into an HTML report. What I'm basically doing now is building the report up by hand. The python program I'm working with is very large and has extensive logging throughout. I'm finding the parts of the logging that I want in my report, marking that up as HTML and appending it to my final result.

I was looking around for an HTML building Python module with the hope that it may be a little more elegant than formatting a bunch of strings by hand.

This SO question seemed to suggest that HTML building modules are less desirable than newer templating modules: python html generator

I'm a little familiar with Jinja and Django templating, but I'm not sure how that would work in my case.

Thanks for any suggestions.

Community
  • 1
  • 1
D.C.
  • 15,340
  • 19
  • 71
  • 102

1 Answers1

1

There are multiple ways to generate an HTML from Python.

The cleanest option is to use a Template Engine:

  • create a template HTML report with placeholders for variable data
  • render the template with a context providing this variable data

There are multiple standalone (meaning Django is not an option) template engines in Python:

Example (using mako):

  • create an index.tpl template file:

    <html>
    <head>
        <title>${title}</title>
    </head>
    <body>
        <h1>${header}</h1>
    </body>
    </html>
    
  • in the python code, create a Template() instance and render the template:

    >>> from mako.template import Template
    >>> template = Template(filename='index.tpl')
    >>> print template.render(title='My Title', header='My Header')
    <html>
    <head>
        <title>My Title</title>
    </head>
    <body>
        <h1>My Header</h1>
    </body>
    </html>
    
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195