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

NPM you don’t know

Introduction Act asnodeThe package manager tool, which comes with thenodejsCommunity andWeb front end EngineeringIn the context of growing field development,npmIt has become a necessary tool for each front-end development student. Every day, countless developers usenpmTo build the project,npm init、npm installBut most of the students only use NPMnpm installHere. (trust to deletenode_modulesFolders, re executingnpm installYou should […]