CommonMark Python Parser
CommonMark-py is a pure Python port of jgm's commonmark.js, a Markdown parser and renderer for the CommonMark specification, using only native modules. It provides functionality to parse Markdown into an Abstract Syntax Tree (AST) and render it to HTML. While it aimed to keep up with CommonMark spec updates, the project is now officially deprecated, with `markdown-it-py` recommended as an alternative for new projects. [7]
Warnings
- deprecated The commonmark.py project is no longer actively maintained and has been officially deprecated. The maintainers recommend migrating to `markdown-it-py` for new projects or existing ones. [7]
- breaking The package and module name changed from `CommonMark` to `commonmark` for PEP8 compliance in version 0.8.0. While 0.8.0 allowed both `import commonmark` and `import CommonMark`, the symlink for `CommonMark` was removed in 0.8.1. This means code using `import CommonMark` will break when upgrading to 0.8.1 or later. [10, 12]
- gotcha For Python 2 compatibility in version 0.9.1, the `future` library (>=0.14.0) is a required dependency. Users on Python 2 environments should ensure this dependency is installed. The project's testing covered Python 2.7, 3.5-3.8. [0.9.1 release notes, 7]
Install
-
pip install commonmark
Imports
- commonmark
from commonmark import commonmark
- Parser, HtmlRenderer
from commonmark import Parser, HtmlRenderer
Quickstart
import commonmark
from commonmark import Parser, HtmlRenderer
markdown_text = "Hello *World*! This is **CommonMark**."
# Simple conversion
html_output_simple = commonmark.commonmark(markdown_text)
print(f"Simple HTML:\n{html_output_simple}")
# Advanced usage with AST manipulation
parser = Parser()
ast = parser.parse(markdown_text)
renderer = HtmlRenderer()
html_output_advanced = renderer.render(ast)
print(f"\nAdvanced HTML:\n{html_output_advanced}")
# Example of AST inspection (prints a tree structure)
# commonmark.dumpAST(ast)