Python one-liners: converting markdown to HTML

This has come in handy a number of times. Assuming you have an input file in markdown format and need to convert it to HTML. This is a low-tech solution to the problem, most importantly it is available for MacOS on M1 chips without any further software installation. And yes, it’s not the only solution either …

Python-Markdown

This solution is based on python markdown. I used Python 3.11.4 on Linux x86-64as my runtime. This little trick worked with Python 3.9.6 on MacOS on M1 chip as well.

Start by creating a virtual env in a directory of your choice

mkdir ~/python/markdown2html && cd ~/python/markdown2html
python3 -m venv .venv
source .venv/bin/activate

With the virtual env created and activated initiate the installation of the markdown library:

pip install markdown

That’s literally it.

Convert Markdown to HTML

Let’s consider this simple markdown document, named test.md

# This is a heading

Adding some text

- list item 1
- list item 2

## Adding a subheading

With a little bit of extra text

1. item 1
1. item 2

And finally a code section

```
10 print "hello"
20 goto 10
run
```

And that's all

Converting this document requires the use of the fenced_code extension (included in the markdown distribution):

(.venv) [martin@linux markdown2html]$ python3 -m markdown -x fenced_code test.md 
<h1>This is a heading</h1>
<p>Adding some text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<h2>Adding a subheading</h2>
<p>With a little bit of extra text</p>
<ol>
<li>item 1</li>
<li>item 2</li>
</ol>
<p>And finally a code section</p>
<pre><code>10 print &quot;hello&quot;
20 goto 10
run
</code></pre>
<p>And that's all</p>
(.venv) [martin@linux markdown2html]$ 

Just redirect the output to a file if you need, and enjoy the HTML version of your file. I hope this saves you 5 minutes :)