Using Python markdown to generate HTML


More and more people like to use markdown to write documents, which is simpler and more convenient than doc, and can render and output their favorite styles.
The document markdown written in the development process is convenient for the management of version control tools such as SVN and GIT.

Install Python markdown and do the syntax conversion from markdown to HTML

pip install markdown

Install pysegments to highlight syntax

pip install Pygments

Execute the following command to generate a default syntax highlighting CSS file. For more information, please refer to the pysegments project website

pygmentize -S default -f html > default.css

The current GitHub style stylesheet, where the code is downloaded and saved as github.css.

Full code:

# -*- coding: utf-8 

import markdown
import os
import sys

def md2html(mdstr):
    exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite','markdown.extensions.tables','markdown.extensions.toc']

    html = '''
    <html lang="zh-cn">
    <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    <link href="default.css" rel="stylesheet">
    <link href="github.css" rel="stylesheet">

    ret = markdown.markdown(mdstr,extensions=exts)
    return html % ret

if __name__ == '__main__':

    if len(sys.argv) < 3:
        print('usage: md2html source_filename target_file')

    infile = open(sys.argv[1],'r')
    md =

    if os.path.exists(sys.argv[2]):

    outfile = open(sys.argv[2],'a')

    print('convert %s to %s success!'%(sys.argv[1],sys.argv[2]))

Save the code on as and execute

python test.html

Recommended Today

Decision tree classifier and pruning based on Python

By angel DasCompile | VKSource: toward Data Science introduce Decision tree classifier is a supervised learning model, which is very useful when we are concerned about interpretability. Decision trees decompose data by making decisions based on multiple problems at each level Decision tree is one of the common algorithms for classification. To better understand it, […]