2
\$\begingroup\$

I often work on embedded system projects in which I have a number of documentation files, such as microprocessor datasheets, schematics, bills of materials, etc. I find it convenient to create a simple little HTML file that contains the file descriptions and a hyperlink to each file. I used to create these all by hand, but I now have an automated script that does that for me. I still have to edit the file to include the descriptions of the files, but this creates both an index.html and style.css file as a start. I'd be interested in a review of both the Python code and the HTML and Javascript and CSS that it creates. The code is intended solely for use on a Linux box.

Invocation and use

This is designed to placed in the path and invoked from the command line from within the directory to be documented. Then the resulting HTML file is invoked in the same way as with firefox index.html. Although it doesn't make much difference in this case, the intent is that the HTML file is not served from a web server but simply interpreted from the file system so that the entire project, with documentation, can be put on a CD or DVD (or other read-only media) and used without having to run a web server.

docdir.py

#! /usr/bin/python3
from os import walk

style = '''\
body 
{ 
    font-style:normal;
    font-family:sans-serif,Georgia, Helvetica, Arial, sans-serif;
        background-color:white;
    color:black;
    margin-left:5%;
}
div.navbar 
{
    text-align:center;
}
h1 
{
    text-indent:1em;
    color:white;
    background-color:navy;
}
h2 
{
    text-indent:2em;
    color:white;
    background-color:navy;
}
h3 
{
    margin-left:1em;
    margin-right:1em;
    text-indent:2em;
    color:white;
    background-color:navy;
}
div.trailer table
{
    width:100%;
    border-style:none;
    padding-left:0;
}
table
{
    border-style:solid;
}
td
{
    padding-left:20px;
}
caption
{
    font-style:oblique;
}'''

index_tail='''\
];

function loadLinks() {
    var table = document.getElementById("docTable");
    links.reverse();
    links.forEach(function(element, index, array) { 
        var row = table.insertRow(0);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.innerHTML = "<a href=\\""+element.name + "\\">" + element.name + "</a>";
        cell2.innerHTML = element.desc;
    });
}
</script>
</head>
<body onload="loadLinks()">
<h1>Documents</h1>
<p>
These directories may contain <b>proprietary and confidential</b> information.
</p>

<p>
<table id="docTable">
<caption>Document list</caption>
</table>
<p>&nbsp;</p>
<table>
<tr>
    <td>
    <a href="index.html">index.html</a>
    </td>
    <td>
this file
    </td>
</tr>
</table>
</body>
</html>'''


if __name__=="__main__":
    title="Documents"
    index_head=f'''\
<!DOCTYPE html>
<html>
<head>
<title>{title}</title>
<link rel="stylesheet" href="style.css">
<script>
var links = [''' 
    # create style file
    css=open('./style.css', 'w+')
    print(style, file=css)
    css.close()
    # get files into array
    _, _, filenames = next(walk('.'), (None, None, []))
    # create index file
    html=open('./index.html', 'w+')
    print(index_head, file=html)
    for fn in filenames:
        print('{{ "name":"{0:s}", "desc":"{0:s}" }},'.format(fn), file=html)
    print(index_tail, file=html)
    html.close()

    # sample of how each document line looks after editing:
    # { "name":"msp430f5438a.pdf", "desc":"MSP430F5438 datasheet" },
\$\endgroup\$
2
  • 1
    \$\begingroup\$ How are you running this script? Is it installed in a specific location and you use something like ~/cwd> python /path/to/file.py? \$\endgroup\$
    – Peilonrayz
    Commented Mar 9, 2019 at 15:43
  • \$\begingroup\$ I've added more details to the question to show how I use it. \$\endgroup\$
    – Edward
    Commented Mar 9, 2019 at 20:41

1 Answer 1

2
\$\begingroup\$

(Warning I havn't tested the following code.)

Python

  1. Offload the custom html to a template engine. Jinja2 can be used in both flask and django. And so I'll change your code to use this. (I'm not affiliated)
  2. It's good to see you manually .closeing your files. But using with is better.
  3. Use ' or " string delimiter. You can switch if the string contains your prefered one. I prefer ', but would use "it's" rather than 'it\'s'.
  4. You can move your CSS into its own file and copy the file with whatever you think is best.
  5. I'd use ''.join and a comprehension to make filenames a string, that can be passed to Jinja.
#! /usr/bin/python3
from os import walk
from pathlib import Path
import shutil

from jinja import Environment, FileSystemLoader, select_autoescape

FILE = Path(__file__).resolve()
RESOURCES = FILE / 'name'
CWD = Path.cwd()

env = Environment(
    loader=FileSystemLoader(str(RESOURCES / 'templates')),
    autoescape=select_autoescape(['html'])
)

if __name__ == '__main__':
    shutil.copyfileobj(
        open(RESOURCES / 'css' / 'style.css'),
        open(CWD / 'style.css', 'w+')
    )

    filenames = ''.join(
        '{{ "name":"{0}", "desc":"{0}" }},'.format(f.name)
        for f in CWD.iterdir()
        if f.is_file()
    )

    with open(CWD / 'index.html', 'w+') as html:
        page = env.get_template('index.html').render(
            title='Documents',
            links=filenames
        )
        print(page, file=html)

CSS

From the little I've done with CSS your file looks a bit off to me:

  1. I'm used to seeing a line between each style.
  2. I'm used to seeing K&R, rather than Allman, indentation style.
  3. You should keep your indentation consistant.
  4. I'm used to seing a space after : and ,.

New location: /bin/name/css/style.css.

body { 
    font-style: normal;
    font-family: sans-serif, Georgia, Helvetica, Arial, sans-serif;
    background-color: white;
    color: black;
    margin-left: 5%;
}

div.navbar {
    text-align:center;
}

HTML

I'm used to seing indentation, most webdev tools also do this for you. And so I'd assume that if they're doing it then there's a good reason for it. I find your HTML code to be a bit hard to read currently because of it.

New location: /bin/name/templates/index.html.

<!DOCTYPE html>
<html>
<head>
  <title>{{ title }}</title>
  <link rel="stylesheet" href="style.css">
  <script>
    var links = [{{ links }}];

    function loadLinks() {
      var table = document.getElementById("docTable");
      links.reverse();
      links.forEach(function(element, index, array) { 
        var row = table.insertRow(0);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.innerHTML = "<a href=\\"" + element.name + "\\">" + element.name + "</a>";
        cell2.innerHTML = element.desc;
      });
    }
  </script>
</head>
<body onload="loadLinks()">
  <h1>Documents</h1>
  <p>
    These directories may contain <b>proprietary and confidential</b> information.
  </p>

  <p>
  <table id="docTable">
    <caption>Document list</caption>
  </table>
  <p>&nbsp;</p>
  <table>
    <tr>
      <td>
        <a href="index.html">index.html</a>
      </td>
      <td>
        this file
      </td>
    </tr>
  </table>
</body>
</html>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.