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.
โจ 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
-
Clone the repository:
git clone https://www.github.com/treeleaves30760/PyMD cd PyMD
-
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
-
Create a new PyMD document:
pyexecmd create my_document.pymd
-
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 8000or another port to avoid conflicts. -
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 `` 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.pngformat prevents conflicts - HTML fallback: Base64 encoding for portability
- Markdown compatible: Standard
syntax
๐ก Best Practices
- File Structure: Start with
# # Titleas the main header - Code Comments: Use
# Commentsinside 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, orpymd.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:
- Live Editing: Open
http://localhost:8080/editorin your browser - Syntax Highlighting:
#prefixed markdown and Python code blocks - Live Preview: See rendered output in real-time
- Export Options: Click ๐ Export HTML or ๐ Export MD
- 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e8b7d37c9d9de0bbec03518778e976a1d714b8060a641a7eac33869f5c741a27
|
|
| MD5 |
c6122b2ca521dd83cd753be0c2513173
|
|
| BLAKE2b-256 |
b9dd4eddd8e1ae8601f3f815f24aaef52d05c85fd6fe2d1d1dbe562fc495bde9
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9d5c9c42790396aab1d32f6d620da56e8decf8fe01c6b952c73d5bfef7444e7f
|
|
| MD5 |
d84bf150e345ffcfad3acf3906f1b1b4
|
|
| BLAKE2b-256 |
0ba6fe950d98398d24caf93fa09eb323994b46198ae4193d636ec8add6281699
|