Python port of markdown-it providing CommonMark-compliant markdown parsing with configurable syntax and pluggable architecture
—
Command-line tools for converting markdown files to HTML with batch processing and interactive modes. Provides a simple interface for markdown processing without requiring Python programming.
Primary entry point for command-line usage.
def main(args: list[str] = None) -> int:
"""
Main CLI entry point.
Parameters:
- args: command line arguments (default: sys.argv[1:])
Returns:
- int: exit code (0 for success)
"""Convert markdown files to HTML output.
def convert(filenames: list[str]) -> None:
"""
Convert multiple markdown files to HTML.
Parameters:
- filenames: list of markdown file paths to convert
"""
def convert_file(filename: str) -> None:
"""
Parse single markdown file and output HTML to stdout.
Parameters:
- filename: path to markdown file
Raises:
- SystemExit: on file read errors
"""Interactive markdown processing mode.
def interactive() -> None:
"""
Interactive markdown parsing mode.
Parse user input and output HTML in REPL style.
"""markdown-it [OPTIONS] [FILES...]usage: markdown-it [-h] [-v] [filenames [filenames ...]]
Parse one or more markdown files, convert each to HTML, and print to stdout
positional arguments:
filenames specify an optional list of files to convert
optional arguments:
-h, --help show this help message and exit
-v, --version show program's version number and exitConvert one or more files to HTML:
# Convert single file
markdown-it README.md
# Convert multiple files
markdown-it file1.md file2.md file3.md
# Redirect output to file
markdown-it input.md > output.html
# Process all markdown files in directory
markdown-it *.md > combined.htmlExample:
$ echo "# Hello World\n\nThis is **bold** text." > hello.md
$ markdown-it hello.md
<h1>Hello World</h1>
<p>This is <strong>bold</strong> text.</p>Start interactive processing when no files are specified:
# Start interactive mode
markdown-it
# Interactive session example:
markdown-it-py [version 4.0.0] (interactive)
Type Ctrl-D to complete input, or Ctrl-C to exit.
>>> # Example
... > markdown *input*
...
<h1>Example</h1>
<blockquote>
<p>markdown <em>input</em></p>
</blockquote>
>>>Interactive Usage:
$ markdown-it
markdown-it-py [version 4.0.0] (interactive)
Type Ctrl-D to complete input, or Ctrl-C to exit.
>>> **Bold text** and *italic text*
...
<p><strong>Bold text</strong> and <em>italic text</em></p>
>>> ## Heading
...
... - List item 1
... - List item 2
...
<h2>Heading</h2>
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>The CLI uses default MarkdownIt configuration:
# Equivalent Python usage
from markdown_it import MarkdownIt
md = MarkdownIt() # Uses 'commonmark' preset by default
html = md.render(markdown_content)The CLI handles common errors gracefully:
# File not found
$ markdown-it nonexistent.md
Cannot open file "nonexistent.md".
# Exits with code 1
# Permission denied
$ markdown-it /root/restricted.md
Cannot open file "/root/restricted.md".
# Exits with code 1Files are read with UTF-8 encoding and error handling:
# Implementation detail
with open(filename, encoding="utf8", errors="ignore") as fin:
content = fin.read()Using markdown-it in shell scripts:
#!/bin/bash
# convert-docs.sh - Convert all markdown docs to HTML
for md_file in docs/*.md; do
html_file="${md_file%.md}.html"
echo "Converting $md_file -> $html_file"
markdown-it "$md_file" > "$html_file"
done
echo "Conversion complete!"Using markdown-it in build systems:
# Makefile
MARKDOWN_FILES := $(wildcard *.md)
HTML_FILES := $(MARKDOWN_FILES:.md=.html)
.PHONY: all clean
all: $(HTML_FILES)
%.html: %.md
markdown-it $< > $@
clean:
rm -f $(HTML_FILES)
# Usage: make allUsing in continuous integration:
# .github/workflows/docs.yml
name: Generate Documentation
on: [push, pull_request]
jobs:
generate-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Python
uses: actions/setup-python@v2
with:
python-version: '3.10'
- name: Install markdown-it-py
run: pip install markdown-it-py
- name: Convert README to HTML
run: |
markdown-it README.md > docs/index.html
markdown-it CHANGELOG.md > docs/changelog.html
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docsUsing in containerized environments:
# Dockerfile
FROM python:3.10-slim
RUN pip install markdown-it-py
WORKDIR /app
COPY . .
# Convert all markdown files
RUN find . -name "*.md" -exec markdown-it {} \; > combined.html
# Or use as entry point
ENTRYPOINT ["markdown-it"]# Build and run
docker build -t markdown-converter .
# Convert files
docker run --rm -v $(pwd):/app markdown-converter README.md
# Interactive mode
docker run --rm -it markdown-converterInvoke CLI functionality programmatically:
from markdown_it.cli.parse import main, convert_file, interactive
import sys
# Call main function directly
exit_code = main(['--help'])
# Convert specific file
try:
convert_file('README.md')
except SystemExit as e:
print(f"Conversion failed: {e}")
# Programmatic file conversion (safer approach)
from markdown_it import MarkdownIt
import sys
def safe_convert_file(filename):
"""Convert file with proper error handling."""
try:
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
md = MarkdownIt()
html = md.render(content)
return html
except FileNotFoundError:
print(f"Error: File '{filename}' not found")
return None
except PermissionError:
print(f"Error: Permission denied reading '{filename}'")
return None
# Usage
html_output = safe_convert_file('example.md')
if html_output:
print(html_output)Call CLI from other programs:
import subprocess
import tempfile
def convert_markdown_string(markdown_text):
"""Convert markdown string using CLI."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
f.write(markdown_text)
temp_file = f.name
try:
result = subprocess.run(
['markdown-it', temp_file],
capture_output=True,
text=True,
check=True
)
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Conversion failed: {e}")
return None
finally:
import os
os.unlink(temp_file)
# Usage
html = convert_markdown_string("# Hello\n\n**World**")
print(html)Install with Tessl CLI
npx tessl i tessl/pypi-markdown-it-py