Skip to main content

Python-Powered Markdown with executable code and dynamic content

Project description

PyMD: Python-Powered Markdown

PyMD is a revolutionary markup language that creates executable Python files that also render beautifully as markdown documents. All markdown content is prefixed with # (making it Python comments), while code blocks contain regular executable Python code that prints markdown during rendering.

Screen Shot

โœจ Features

  • ๐Ÿ Executable Python Files: Files can be run directly with python filename.pymd
  • ๐Ÿ“ Commented Markdown: All markdown content is prefixed with # (Python comments)
  • ๐Ÿ–จ๏ธ Print-to-Markdown: Python print() statements output markdown content during rendering
  • ๐ŸŽจ Dual Code Block Types:
    • ``` (3 backticks): Execute Python code and process print output as markdown
    • ```` (4 backticks): Display code with syntax highlighting only
  • ๐Ÿ”— Variable Persistence: Variables persist across code blocks in the same document
  • ๐Ÿ”ด Live Preview: Real-time rendering with auto-refresh as you edit
  • ๐Ÿ“Š Rich Visualizations: Built-in support for matplotlib, pandas, and other data science libraries
  • ๐Ÿ–ผ๏ธ Automatic Image Capture: plt.show() automatically saves and renders plots in HTML and Markdown
  • ๐Ÿ“‹ Table Support: Automatic detection and rendering of markdown tables with proper formatting
  • ๐Ÿงฎ Dynamic Content: Execute Python code and display results inline
  • ๐Ÿ“ฑ Beautiful Output: Clean, responsive HTML with modern styling
  • โšก Fast Rendering: Efficient parsing and rendering engine with caching
  • ๐Ÿ”„ Auto-Refresh: Changes reflect immediately in the live preview
  • ๐Ÿ’ฌ Smart Comments: Display blocks use // for cleaner code presentation
  • ๐Ÿ“„ Export Options: Export to HTML or standard Markdown formats with embedded images
  • ๐Ÿ–ผ๏ธ Image Management: Automatic file organization with unique naming and format flexibility
  • ๐Ÿ–ฑ๏ธ One-Click Export: Export buttons in the web editor interface
  • โ†”๏ธ Backward Compatible: Supports both executable and legacy syntax

๐Ÿš€ Quick Start

Installation

Option 1: Install from PyPI (Recommended)

pip install pyexecmd
Option 2: Install from source
  1. Clone the repository:

    git clone https://www.github.com/treeleaves30760/PyMD
    cd PyMD
    
  2. Install in development mode:

    pip install -e .
    

Usage

For Conda Users (Recommended Development Setup)

If you're using conda for development, first activate the environment:

# Initialize conda and activate environment
source /opt/miniconda3/etc/profile.d/conda.sh && conda activate PyMD

# Verify activation
python --version && which python

Then use standard Python commands:

# Create a new PyMD document
python -m pymd.cli create my_document.pymd

# Start live preview with web editor
python -m pymd.cli serve --file my_document.pymd --port 8080

# Render to HTML
python -m pymd.cli render my_document.pymd -o output.html

# Render to Markdown
python -m pymd.cli render my_document.pymd -f markdown -o output.md

For PyPI Installation

  1. Create a new PyMD document:

    pyexecmd create my_document.pymd
    
  2. Start live preview with web editor:

    pyexecmd serve --file my_document.pymd --port 8080
    

    Then open http://localhost:8080/editor in your browser for the full editor experience, or http://localhost:8080 for display-only view.

    Note for macOS users: Port 5000 is often used by AirPlay. Use --port 8000 or another port to avoid conflicts.

  3. Export Options:

    # Render to HTML
    pyexecmd render my_document.pymd -o output.html
    
    # Render to Markdown
    pyexecmd render my_document.pymd -f markdown -o output.md
    

Web Editor Features

The web editor (available at /editor) includes:

  • ๐Ÿ“ Split-view editing: Side-by-side editor and live preview
  • ๐Ÿ–ฑ๏ธ One-click export: Export HTML and Markdown buttons in the interface
  • โšก Live rendering: Ctrl+S to execute code and update preview
  • ๐Ÿ’พ File management: Save and download your documents
  • ๐ŸŽจ Syntax highlighting: Python syntax highlighting with PyMD-specific features

๐Ÿ“ PyMD Syntax

PyMD files are executable Python scripts where:

  • Markdown content is prefixed with # (Python comments)
  • Code blocks contain regular Python code that prints markdown
  • Print output becomes rendered markdown content during PyMD rendering
  • Files run as Python and render as beautiful documents

Basic Structure

# # This is a markdown header
# 
# This is regular markdown text with **bold** formatting.
#
# - This is a list item
# - Another list item
#
# ```
# This is a comment in the code block
print("## This becomes a rendered H2 header")
print("Regular text from Python print statement")
print("- **Dynamic list item** with variables")
# ```
#
# More markdown content here...

๐Ÿ“ Markdown Content (Prefixed with #)

All markdown content is prefixed with # making it Python comments:

Headers:

# # Main Title
# ## Section Title  
# ### Subsection Title

Lists:

# - Unordered list item
# - Another unordered item
#
# 1. Ordered list item
# 2. Another ordered item

Plain Text:

# This is a paragraph of regular text.
# You can write multiple paragraphs easily.

Comments:

# // This is a comment and will be ignored during rendering

๐Ÿ Code Blocks (Executable Python)

Code blocks markers are prefixed with #, but the code inside is regular Python:

Executable Code Block:

# ```
# This is a comment inside the code block
x = 42
y = "Hello, PyMD!"
print(f"## {y} The answer is {x}")  # This becomes an H2 header
print(f"The calculation result: **{x * 2}**")  # Bold text
# ```

Display-Only Code Block:

# ````
# def example_function():
#     // This code is displayed but not executed
#     return "example"
# ````

๐Ÿ“‹ Table Support

PyMD automatically detects and renders markdown tables with proper formatting:

# # Employee Report
#
# Here's our team data:
#
# | Name | Age | Department | Score |
# | --- | --- | --- | --- |
# | Alice | 28 | Engineering | 95 |
# | Bob | 32 | Sales | 87 |
# | Charlie | 29 | Marketing | 92 |
#
# You can also generate tables dynamically from code:
#
# ```
import pandas as pd

# Create sample data
employees = pd.DataFrame({
    'Name': ['Diana', 'Eve', 'Frank'], 
    'Age': [26, 31, 35],
    'Department': ['Design', 'HR', 'Finance'],
    'Score': [89, 94, 88]
})

print("## Dynamic Employee Data")
print()
for _, row in employees.iterrows():
    print(f"| {row['Name']} | {row['Age']} | {row['Department']} | {row['Score']} |")
# ```

๐Ÿ–ผ๏ธ Automatic Image Rendering

PyMD automatically captures and renders matplotlib plots when you use plt.show():

# # Data Visualization Report
#
# Let's create some visualizations:
#
# ```
import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
plt.title('Sine Wave Visualization')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()
plt.grid(True, alpha=0.3)

# This automatically captures and renders the plot!
plt.show()
# ```
#
# ```
# Create another plot
y2 = np.cos(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y2, 'r-', linewidth=2, label='cos(x)')
plt.title('Cosine Wave Visualization')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()
plt.grid(True, alpha=0.3)

# Multiple plots are automatically captured
plt.show()
# ```
#
# Each `plt.show()` call automatically:
# - **Saves the plot** as a PNG file in an `images/` directory
# - **Renders in HTML** with file references and base64 fallbacks
# - **Embeds in Markdown** using standard `![](images/filename.png)` syntax
# - **Generates unique filenames** to avoid conflicts

๐Ÿ“Š Complete Example

Data Analysis with Print-to-Markdown:

# # Data Analysis Report
#
# Let's analyze some sample data:
#
# ```
import pandas as pd
import numpy as np

# Create sample data
np.random.seed(42)
data = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Score': [95, 87, 92],
    'Department': ['Engineering', 'Sales', 'Marketing']
})

print("## Sample Employee Data")
print(f"**Total employees:** {len(data)}")
print(f"**Average score:** {data['Score'].mean():.1f}")
print()
print("### Individual Scores:")
for _, row in data.iterrows():
    print(f"- **{row['Name']}** ({row['Department']}): {row['Score']}")
# ```
#
# ## Analysis Results
#
# The data shows interesting patterns in employee performance.

๐Ÿ’ฌ Interactive Input with Mock Values

# ## User Profile Generator
#
# ```
# Get user input (with mock values for non-interactive execution)
name = input("Enter your name: ") # input: Alice
age = input("Enter your age: ") # input: 25

print(f"### Welcome, {name}!")
print(f"**Age:** {age} years old")
print(f"**Birth year:** {2025 - int(age)}")

# Input without mock value defaults to empty string
optional_input = input("Optional comment: ")
if optional_input:
    print(f"**Comment:** {optional_input}")
else:
    print("*No comment provided*")
# ```

๐ŸŽจ Display-Only Code Blocks

Use four backticks for code that displays but doesn't execute:

# ## Algorithm Reference
#
# Here's the algorithm we'll implement:
#
# ````
# def factorial(n):
#     // Base case
#     if n <= 1:
#         return 1
#     // Recursive case  
#     return n * factorial(n-1)
# 
# // Example usage (this won't execute)
# result = factorial(5)
# ````
#
# Now let's implement it:
#
# ```
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n-1)

result = factorial(5)
print(f"## Factorial Results")
print(f"Factorial of 5 is: **{result}**")
# ```

๐Ÿ”‘ Key Concepts

  • ๐Ÿ Executable Python: Files run directly with python filename.pymd
  • ๐Ÿ“ Commented Markdown: All markdown content prefixed with # (Python comments)
  • ๐Ÿ–จ๏ธ Print-to-Markdown: Use print() to output markdown that gets rendered
  • ๐Ÿ”— Variable Persistence: Variables persist across all code in the file
  • ๐Ÿ“ฆ Two Code Block Types:
    • ``` (3 backticks): Execute Python and process print output as markdown
    • ```` (4 backticks): Display code with syntax highlighting (no execution)
  • ๐Ÿ’ฌ Interactive Input: Use input() with mock values for non-interactive execution
  • ๐ŸŽจ Clean Rendering: # prefixes hidden during HTML/Markdown export
  • ๐Ÿ“Š Rich Output: Print statements can output headers, lists, tables, even HTML
  • ๐Ÿ–ผ๏ธ Automatic Plot Capture: plt.show() calls automatically save and render images
  • ๐Ÿ“‹ Smart Table Rendering: Markdown tables are automatically detected and styled
  • ๐Ÿ’ก Smart Comments: Use // in display blocks for cleaner presentation
  • โ†”๏ธ Dual Purpose: Same file serves as Python script AND beautiful document

๐Ÿ› ๏ธ Syntax Reference

๐Ÿ“ Markdown Content (All prefixed with #)

Headers:

# # Level 1 Header
# ## Level 2 Header  
# ### Level 3 Header

Lists:

# - Unordered list item
# - Another item
# 
# 1. Ordered list item
# 2. Another ordered item

Text and Formatting:

# Regular paragraph text.
# 
# Text with **bold** and *italic* formatting.
# 
# // This is a comment (ignored during rendering)

Tables:

# | Header 1 | Header 2 | Header 3 |
# | --- | --- | --- |
# | Cell 1 | Cell 2 | Cell 3 |
# | Row 2 | Data | More Data |
#
# Tables support alignment:
# | Left | Center | Right |
# | :--- | :---: | ---: |
# | Left aligned | Centered | Right aligned |

๐Ÿ Code Blocks (Regular Python)

Executable Code Block:

# ```
# Comments inside code blocks (optional)
variable = "Hello World"
print(f"## {variable}")  # Becomes H2 header in output
print(f"Current value: **{variable}**")  # Bold text in output
print("- First result")   # List item in output
print("- Second result")  # Another list item
# ```

Display-Only Code Block:

# ````
# def example_function():
#     // This is displayed but not executed
#     // Use // for comments in display blocks
#     return "example"
# ````

๐Ÿ–จ๏ธ Print-to-Markdown

Use print() statements to output markdown content:

# ```
data = [1, 2, 3, 4, 5]
print("## Analysis Results")  # H2 header
print(f"**Count:** {len(data)}")  # Bold text
print(f"**Sum:** {sum(data)}")    # Bold text
print("### Detailed Breakdown:")   # H3 header
for i, value in enumerate(data, 1):
    print(f"{i}. Item value: **{value}**")  # Ordered list
# ```

๐Ÿ–ผ๏ธ Automatic Plot Rendering

Matplotlib plots are automatically captured when using plt.show():

# ```
import matplotlib.pyplot as plt
import numpy as np

# Create visualization
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(8, 6))
plt.plot(x, y, 'b-', linewidth=2)
plt.title('Automatic Plot Capture')
plt.grid(True)

# Automatically saves image and includes in output
plt.show()
# ```

Image Features:

  • Automatic saving: Images saved to images/ directory
  • Unique filenames: plot_1_abc123.png format prevents conflicts
  • HTML fallback: Base64 encoding for portability
  • Markdown compatible: Standard ![](images/filename.png) syntax

๐Ÿ’ก Best Practices

  • File Structure: Start with # # Title as the main header
  • Code Comments: Use # Comments inside code blocks for Python comments
  • Markdown Output: Use print() to generate headers, lists, and formatted text
  • Display Code: Use `# ````...# ``````` for code examples that shouldn't execute
  • Variables: Define variables in code blocks and reference them in print statements
  • Clean Syntax: Keep markdown content in # prefixed sections, code in blocks
  • Tables: Use standard markdown table syntax with | separators for static tables
  • Images: Use plt.show() for automatic plot capture, or pymd.image() for manual control
  • File Organization: Images are saved to images/ directory relative to output file
  • Performance: Large plots are automatically optimized for web display

CLI Commands

# Create new PyExecMD file from template
pyexecmd create <filename> [--force]

# Start live preview server with web editor
pyexecmd serve [--file FILE] [--port PORT] [--host HOST] [--debug] [--mode {editing,viewing,both}]

# Render PyExecMD to HTML (default)
pyexecmd render <input> [-o OUTPUT] [-f html]

# Render PyExecMD to Markdown
pyexecmd render <input> [-o OUTPUT] -f markdown

# Render options
pyexecmd render <input> --format {html,markdown} --output <filename>

Command Examples

# Conda development setup
source /opt/miniconda3/etc/profile.d/conda.sh && conda activate PyMD

# Create and serve
python -m pymd.cli create tutorial.pymd
python -m pymd.cli serve --file tutorial.pymd --port 8080

# Export to different formats
python -m pymd.cli render tutorial.pymd -o tutorial.html          # HTML export
python -m pymd.cli render tutorial.pymd -f markdown -o tutorial.md # Markdown export
python -m pymd.cli render tutorial.pymd -f markdown               # Print to stdout

# PyPI installation
pyexecmd create tutorial.pymd
pyexecmd serve --file tutorial.pymd --port 8080
pyexecmd render tutorial.pymd -f markdown -o tutorial.md

๐ŸŒŸ Examples

Simple Example (example-simple.pymd)

# # Simple PyMD Example
#
# This demonstrates basic syntax:
#
# ```
# This is a comment in Python
print("## Hello from PyMD!")
a = 20
b = 30
print(f"The answer is: **{a + b}**")
# ```
#
# - This is a markdown list item
# 1. This is an ordered list item

Usage:

  • Run as Python: python example-simple.pymd
  • Render to HTML: python -m pymd.cli render example-simple.pymd -o output.html

Comprehensive Example (example.pymd)

Check out example.pymd for a full demonstration including:

  • Executable Python file with # prefixed markdown content
  • Data analysis with pandas and numpy
  • Print-to-markdown for dynamic content generation
  • Variable persistence across code blocks
  • Interactive input with mock values
  • Mixed workflow of documentation and executable code
  • Export functionality (HTML and Markdown)

Complex Example (example-complex.pymd)

Advanced features including:

  • Machine learning model loading
  • Error handling and device management
  • AI text generation integration
  • Complex data processing workflows

๐Ÿš€ Quick Example Usage

1. Run as executable Python:

python example.pymd

2. Render as beautiful HTML:

python -m pymd.cli render example.pymd -o presentation.html

3. Export to standard Markdown:

python -m pymd.cli render example.pymd -f markdown -o documentation.md

4. Live editor with preview:

python -m pymd.cli serve --file example.pymd --port 8080
# Open http://localhost:8080/editor in your browser

How Export Works:

  • HTML Export: Full rendering with executed code output and styled markdown
  • Markdown Export: Removes # prefixes and converts to standard markdown
  • Source Files: Remain executable Python scripts with commented markdown
  • Compatibility: Exported markdown works with GitHub, GitLab, and other renderers

Web Editor Features:

  1. Live Editing: Open http://localhost:8080/editor in your browser
  2. Syntax Highlighting: # prefixed markdown and Python code blocks
  3. Live Preview: See rendered output in real-time
  4. Export Options: Click ๐Ÿ“„ Export HTML or ๐Ÿ“ Export MD
  5. File Execution: Use Ctrl+S to execute code and update preview

๐ŸŽฏ Use Cases

  • ๐Ÿ“Š Data Science Reports: Python scripts that execute analysis AND generate beautiful reports with automatic plot capture
  • ๐Ÿ“š Executable Documentation: Documentation that actually runs and validates itself, with embedded visualizations
  • ๐ŸŽ“ Interactive Tutorials: Learning materials that students can execute and modify, featuring live charts and tables
  • ๐Ÿ“ˆ Living Dashboards: Python scripts that generate dynamic visual reports with automatic image saving
  • ๐Ÿ”ฌ Reproducible Research: Research papers where the code actually runs and produces publication-ready figures
  • ๐Ÿงช Literate Programming: Self-documenting code through executable markdown comments with inline visualizations
  • ๐Ÿ“‹ Technical Specifications: Specs that include working code examples and automatically generated plots
  • ๐Ÿค– AI/ML Workflows: Machine learning pipelines with embedded documentation and automatic model visualization
  • ๐Ÿ“‘ Business Reports: Automated reports with data tables and charts that update when code runs
  • ๐ŸŽจ Presentation Materials: Technical presentations that combine code, explanation, and live visualizations

๐Ÿ“ Project Structure

PyMD/
โ”œโ”€โ”€ pymd/                   # Main package directory
โ”‚   โ”œโ”€โ”€ __init__.py        # Package initialization
โ”‚   โ”œโ”€โ”€ cli.py             # Command-line interface
โ”‚   โ”œโ”€โ”€ renderer.py        # Core rendering engine
โ”‚   โ””โ”€โ”€ server.py          # Live preview server
โ”œโ”€โ”€ example.pymd           # Example PyMD document
โ”œโ”€โ”€ pyproject.toml         # Package configuration
โ”œโ”€โ”€ MANIFEST.in            # Additional files to include
โ”œโ”€โ”€ LICENSE                # MIT License
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ””โ”€โ”€ README.md              # This file

๐Ÿค Contributing

We welcome contributions! Please feel free to submit issues, feature requests, or pull requests.

๐Ÿ“„ License

This project is licensed under the MIT License.


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyexecmd-0.1.6.tar.gz (42.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyexecmd-0.1.6-py3-none-any.whl (37.2 kB view details)

Uploaded Python 3

File details

Details for the file pyexecmd-0.1.6.tar.gz.

File metadata

  • Download URL: pyexecmd-0.1.6.tar.gz
  • Upload date:
  • Size: 42.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.13

File hashes

Hashes for pyexecmd-0.1.6.tar.gz
Algorithm Hash digest
SHA256 e8b7d37c9d9de0bbec03518778e976a1d714b8060a641a7eac33869f5c741a27
MD5 c6122b2ca521dd83cd753be0c2513173
BLAKE2b-256 b9dd4eddd8e1ae8601f3f815f24aaef52d05c85fd6fe2d1d1dbe562fc495bde9

See more details on using hashes here.

File details

Details for the file pyexecmd-0.1.6-py3-none-any.whl.

File metadata

  • Download URL: pyexecmd-0.1.6-py3-none-any.whl
  • Upload date:
  • Size: 37.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.13

File hashes

Hashes for pyexecmd-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 9d5c9c42790396aab1d32f6d620da56e8decf8fe01c6b952c73d5bfef7444e7f
MD5 d84bf150e345ffcfad3acf3906f1b1b4
BLAKE2b-256 0ba6fe950d98398d24caf93fa09eb323994b46198ae4193d636ec8add6281699

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page