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 combines familiar markdown syntax with the full power of Python execution. Write beautiful documents using standard markdown headers, lists, and text, while executing Python code in clearly separated code blocks!

โœจ Features

  • ๐Ÿ“ Markdown Syntax: Use familiar markdown headers (#), lists (-), and plain text
  • ๐Ÿ Dual Code Block Types:
    • ``` (3 backticks): Execute Python code and show output
    • ```` (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
  • ๐Ÿงฎ Dynamic Content: Execute Python code and display results inline
  • ๐Ÿ“ฑ Beautiful Output: Clean, responsive HTML with modern styling
  • โšก Fast Rendering: Efficient parsing and rendering engine
  • ๐Ÿ”„ 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
  • ๐Ÿ–ฑ๏ธ One-Click Export: Export buttons in the web editor interface

๐Ÿš€ 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 (NEW!)
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 (NEW!)
    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 combines familiar markdown syntax with Python code execution:

Markdown Content (Outside Code Blocks)

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

Python Code Blocks

Simple Code Execution:

```
x = 42
y = "Hello, PyMD!"
print(f"{y} The answer is {x}")
```

Data Analysis:

```
import pandas as pd
import numpy as np

# Create sample data

data = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Score': [95, 87, 92]
})

print("Sample Data:")
pymd.table(data)
```

Visualizations:

```
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(8, 5))
plt.plot(x, y, 'b-', linewidth=2)
plt.title("Sine Wave Visualization")
plt.grid(True)

pymd.image(plt.gcf(), "Beautiful sine wave")
```

Interactive Input with Mock Values:

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

# Use the input values
pymd.h2(f"Welcome, {name}!")
pymd.text(f"You are {age} years old.")

# 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")
```

Code Display (Method 1 - Using pymd.code()):

```
sample_code = '''
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n-1)
'''

pymd.code(sample_code, "python")
print(f"Factorial of 5 is: {factorial(5)}")
```

Code Display (Method 2 - Using four backticks):

````
def factorial(n):
    // Base case
    if n <= 1:
        return 1
    // Recursive case
    return n * factorial(n-1)

// Example usage (not executed)
result = factorial(5)
````

Key Features

  • Variable Persistence: Variables defined in one code block are available in subsequent blocks
  • Mixed Content: Alternate between markdown content and Python code seamlessly
  • Two Code Block Types:
    • Three backticks (```): Execute Python code and show output
    • Four backticks (````): Display code with syntax highlighting (no execution)
  • Interactive Input Support: Use input() with mock values for non-interactive execution
  • Clean Separation: Clear visual distinction between documentation and executable code
  • Rich Output: Code execution results are displayed with beautiful formatting
  • Smart Comment Styling: Display blocks use // comments for cleaner presentation

Input Mock System

PyMD supports interactive input through a mock system that allows documents to be rendered without user interaction:

  • With Mock Value: input("Prompt: ") # input: mock_value - Returns "mock_value"
  • Without Mock Value: input("Prompt: ") - Returns empty string ("")
  • Multiple Inputs: Each input() call uses mock values in sequence
  • Silent Execution: Mock inputs don't produce console output, only the actual code results are shown

๐Ÿ“ 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

๐Ÿ› ๏ธ API Reference

Markdown Syntax (Outside Code Blocks)

  • # Header - Create level 1 heading
  • ## Header - Create level 2 heading
  • ### Header - Create level 3 heading
  • - Item - Unordered list item
  • 1. Item - Ordered list item
  • Plain text - Regular paragraph text
  • // Comment - Comments (ignored during rendering)

PyMD Functions (Inside Code Blocks)

  • pymd.h1(text) - Create level 1 heading programmatically
  • pymd.h2(text) - Create level 2 heading programmatically
  • pymd.h3(text) - Create level 3 heading programmatically
  • pymd.text(content) - Create paragraph text programmatically
  • pymd.code(content, language) - Display code block with syntax highlighting
  • pymd.image(plot_obj, caption) - Render matplotlib plots
  • pymd.table(data) - Render pandas DataFrames or tables

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 (NEW!)
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

๐ŸŽฏ Use Cases

  • ๐Ÿ“Š Data Science Reports: Combine analysis, visualizations, and explanations
  • ๐Ÿ“š Interactive Documentation: Living documents that update with code changes
  • ๐ŸŽ“ Educational Materials: Tutorials with executable examples
  • ๐Ÿ“ˆ Dashboard Reports: Dynamic reports with real-time data
  • ๐Ÿ”ฌ Research Papers: Academic papers with reproducible results

๐ŸŒŸ Examples

Check out example.pymd for a comprehensive demonstration of PyMD features, including:

  • Markdown-style headers, lists, and text
  • Python code execution with output
  • Beautiful data visualizations with matplotlib
  • Dynamic calculations and variable persistence
  • Interactive tables with pandas
  • Mixed content workflow
  • Real-time preview updates
  • Export functionality (HTML and Markdown)

Export Examples

Export to HTML for presentations and sharing:

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

Export to Markdown for documentation and version control:

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

Web Editor Export:

  1. Open http://localhost:8080/editor in your browser
  2. Edit your PyMD content
  3. Click ๐Ÿ“„ Export HTML for a complete HTML file
  4. Click ๐Ÿ“ Export MD for a clean Markdown file

The exported Markdown maintains the structure while converting PyMD-specific syntax to standard Markdown format, making it compatible with GitHub, GitLab, and other Markdown renderers.

๐Ÿค 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.5.tar.gz (36.8 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.5-py3-none-any.whl (29.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pyexecmd-0.1.5.tar.gz
  • Upload date:
  • Size: 36.8 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.5.tar.gz
Algorithm Hash digest
SHA256 d2ec566e9a412c3dd4424b50a55b4108a35af726347e9d1324d1baa781f74044
MD5 7af8c9d26324b9991c46348021b08515
BLAKE2b-256 629663c9648bb1e94489655f3ffdf1270a561383024f46aeffdc4c90986f2deb

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pyexecmd-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 29.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.5-py3-none-any.whl
Algorithm Hash digest
SHA256 49af3d3209fbcabfeb4734ea4f2ad58aa14241bd871e8116adc2499097fdffe1
MD5 ddc3ecb2ae622b4ae2c9ae856ec97e46
BLAKE2b-256 71331cb04d31ec78da6c629c30277d7889ff0880d6b9b72624805632e14f6794

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