Using Python markdown to generate HTML

Time:2020-3-25

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
reload(sys)
sys.setdefaultencoding('utf8')

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

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

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



if __name__ == '__main__':

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

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

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


    outfile = open(sys.argv[2],'a')
    outfile.write(md2html(md))
    outfile.close()

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

Save the code on as md2html.py and execute

python md2html.py test.md 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 […]