跳转到主要内容

自动执行Markdown文件中的代码块,并就地更新输出

项目描述

:rocket: Markdown代码运行器

markdown-code-runner是一个Python包,它可以自动执行Markdown文件中的代码块(包括隐藏的代码块),并就地更新输出。此包特别适用于维护包含嵌入式代码片段的Markdown文件,确保显示的输出始终是最新的和准确的。它还可以直接从代码生成内容,如表格、图表和其他可视化。

此包托管在GitHub上:https://github.com/basnijholt/markdown-code-runner

:star: 功能

  • :rocket: 自动执行Markdown文件中的代码块,包括隐藏的代码块
  • :eyes: 允许隐藏代码块(即在Markdown文件中不显示的代码块)生成表格、图表等内容
  • :snake: :shell: 与Python和Bash代码块兼容
  • :white_check_mark: 保持代码块输出的更新
  • :octocat: 可轻松与GitHub Actions集成
  • :tada: 无外部依赖,与Python 3.7+兼容
  • :globe_with_meridians: 通过文件代码块和bash执行来执行所有语言(请参阅Rust :crab: 示例

:question: 问题陈述

在创建包含代码示例的Markdown文件时,保持这些代码片段的输出准确和最新至关重要。手动更新输出可能会很耗时且容易出错,尤其是在处理大型文件或多个人协作时。此外,可能需要隐藏代码块来生成表格、图表和其他可视化,而无需在Markdown文件中显示代码本身。

markdown-code-runner通过自动执行Markdown文件中的代码块(包括隐藏的代码块)并就地更新输出来解决此问题。这确保了显示的输出始终与代码同步,并且隐藏代码块生成的内容可以无缝集成。

:books: 目录

:computer: 安装

通过 pip 安装 markdown-code-runner

pip install markdown-code-runner

:rocket: 快速入门

要开始使用 markdown-code-runner,请按照以下步骤操作

  1. 使用以下任一方法将代码块添加到您的 Markdown 文件中

    方法 1 (展示您的代码): 使用语言指定符 python markdown-code-runner 的三重反引号代码块。

    示例

    ```python markdown-code-runner
    print('Hello, world!')
    ```
    (Optionally, you can place some text between the code block and the output markers)
    <!-- OUTPUT:START -->
    This content will be replaced by the output of the code block above.
    <!-- OUTPUT:END -->
    

    或者用于 Bash

    ```bash markdown-code-runner
    echo 'Hello, world!'
    ```
    (Optionally, you can place some text between the code block and the output markers)
    <!-- OUTPUT:START -->
    This content will be replaced by the output of the code block above.
    <!-- OUTPUT:END -->
    

    方法 2 (隐藏您的代码): 将代码放在 <!-- CODE:START --><!-- CODE:END --> 标记之间。在您想要显示输出的地方添加输出标记 <!-- OUTPUT:START --><!-- OUTPUT:END -->

    示例

    This is an example code block:
    
    <!-- CODE:START -->
    <!-- print('Hello, world!') -->
    <!-- CODE:END -->
    <!-- OUTPUT:START -->
    This content will be replaced by the output of the code block above.
    <!-- OUTPUT:END -->
    

    或者用于 Bash

    This is an example code block:
    
    <!-- CODE:BASH:START -->
    <!-- MY_VAR="Hello, World!" -->
    <!-- echo $MY_VAR -->
    <!-- CODE:END -->
    <!-- OUTPUT:START -->
    This content will be replaced by the output of the code block above.
    <!-- OUTPUT:END -->
    
  2. 在您的 Markdown 文件上运行 markdown-code-runner

    markdown-code-runner /path/to/your/markdown_file.md
    
  3. 代码块的输出将自动执行并插入到输出标记之间。

:snake: Python API

要使用 markdown-code-runner,只需从包中导入 update_markdown_file 函数,并用您的 Markdown 文件路径调用它

from markdown_code_runner import update_markdown_file

update_markdown_file("path/to/your/markdown_file.md")

:book: 示例

以下是一些展示如何使用 markdown-code-runner 的示例

:star: 示例 1:简单的代码块

This is an example of a simple hidden code block:

<!-- CODE:START -->
<!-- print('Hello, world!') -->
<!-- CODE:END -->
<!-- OUTPUT:START -->
This content will be replaced by the output of the code block above.
<!-- OUTPUT:END -->

运行 markdown-code-runner

This is an example of a simple code block:

<!-- CODE:START -->
<!-- print('Hello, world!') -->
<!-- CODE:END -->
<!-- OUTPUT:START -->
<!-- ⚠️ This content is auto-generated by `markdown-code-runner`. -->
Hello, world!

<!-- OUTPUT:END -->

:star: 示例 2:多个代码块

Here are two code blocks:

First code block:

<!-- CODE:START -->
<!-- print('Hello, world!') -->
<!-- CODE:END -->
<!-- OUTPUT:START -->
This content will be replaced by the output of the first code block.
<!-- OUTPUT:END -->
Second code block:

<!-- CODE:START -->
<!-- print('Hello again!') -->
<!-- CODE:END -->
<!-- OUTPUT:START -->
This content will be replaced by the output of the second code block.
<!-- OUTPUT:END -->

运行 markdown-code-runner

Here are two code blocks:

First code block:

<!-- CODE:START -->
<!-- print('Hello, world!') -->
<!-- CODE:END -->
<!-- OUTPUT:START -->
<!-- ⚠️ This content is auto-generated by `markdown-code-runner`. -->
Hello, world!

<!-- OUTPUT:END -->

Second code block:

<!-- CODE:START -->
<!-- print('Hello again!') -->
<!-- CODE:END -->
<!-- OUTPUT:START -->
<!-- ⚠️ This content is auto-generated by `markdown-code-runner`. -->
Hello again!

<!-- OUTPUT:END -->

:bulb: 使用想法

Markdown Code Runner 可用于各种目的,如创建 Markdown 表格、生成可视化以及展示具有实时输出的代码示例。以下是一些使用想法以帮助您入门

:gear: 想法 1:与 GitHub Actions 进行持续集成

您可以使用 markdown-code-runner 自动在 CI 环境中更新您的 Markdown 文件。以下示例演示了如何配置 GitHub Actions 工作流程,以便在将更改推送到 main 分支时更新您的 README.md

  1. 在您的存储库中 .github/workflows/markdown-code-runner.yml 创建一个新的工作流程文件。

  2. 将以下内容添加到工作流程文件中

name: Update README.md

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  update_readme:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository
        uses: actions/checkout@v3
        with:
          persist-credentials: false
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v3
        with:
          python-version: '3.x'

      - name: Install markdown-code-runner
        run: |
          python -m pip install --upgrade pip
          pip install markdown-code-runner

      # Install dependencies you're using in your README.md
      - name: Install other Python dependencies
        run: |
          pip install pandas tabulate pytest matplotlib requests

      # Rust is only needed for an example in our README.md
      - name: Set up Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          profile: minimal

      - name: Run update-readme.py
        run: markdown-code-runner --verbose README.md

      - name: Commit updated README.md
        id: commit
        run: |
          git add README.md
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          if git diff --quiet && git diff --staged --quiet; then
            echo "No changes in README.md, skipping commit."
            echo "commit_status=skipped" >> $GITHUB_ENV
          else
            git commit -m "Update README.md"
            echo "commit_status=committed" >> $GITHUB_ENV
          fi

      - name: Push changes
        if: env.commit_status == 'committed'
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ github.head_ref }}
  1. 提交并推送工作流程文件到您的存储库。现在,每当您将更改推送到 main 分支时,工作流程将自动运行,并使用代码块的最新输出更新您的 README.md

有关配置 GitHub Actions 的更多信息,请参阅 官方文档

:computer: 想法 2:显示命令行输出

使用 markdown-code-runner 显示命令行程序的输出。例如,以下 Markdown 文件显示了此包的帮助选项。

使用反引号 bash 代码块

export PATH=~/micromamba/bin:$PATH
echo '```bash'
markdown-code-runner --help
echo '```'

这将渲染为

usage: markdown-code-runner [-h] [-o OUTPUT] [-d] [-v] input

Automatically update Markdown files with code block output.

positional arguments:
  input                 Path to the input Markdown file.

options:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Path to the output Markdown file. (default: overwrite
                        input file)
  -d, --verbose         Enable debugging mode (default: False)
  -v, --version         show program's version number and exit

:bar_chart: 想法 3:生成 Markdown 表格

使用 pandas 库从 DataFrame 创建 Markdown 表格。以下示例演示了如何创建具有随机数据的表格

import pandas as pd
import numpy as np

# Generate random data
np.random.seed(42)
data = np.random.randint(1, 101, size=(5, 3))

# Create a DataFrame and column names
df = pd.DataFrame(data, columns=["Column A", "Column B", "Column C"])

# Convert the DataFrame to a Markdown table
print(df.to_markdown(index=False))

这将渲染为

列 A 列 B 列 C
52 93 15
72 61 21
83 87 75
75 88 100
24 3 22

:art: 想法 4:生成可视化

使用 matplotlib 库创建可视化并将其保存为图像。然后,在您的 Markdown 文件中引用该图像。以下示例演示了如何创建柱状图。

使用三重反引号代码块

import matplotlib.pyplot as plt
import io
import base64
from urllib.parse import quote

# Example data for the plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create a simple line plot
plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Sample Line Plot")

# Save the plot to a BytesIO buffer
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close()

# Encode the buffer as a base64 string
data = base64.b64encode(buf.getvalue()).decode('utf-8')

# Create an inline HTML img tag with the base64 string
from urllib.parse import quote
img_html = f'<img src="data:image/png;base64,{quote(data)}" alt="Sample Line Plot"/>'

print(img_html)

:information_source: 注意:此输出在此处已禁用,因为 GitHub Markdown 不支持内联图像 HTML。在其他 Markdown 渲染器上这将有效。

:page_facing_up: 想法 5:从 CSV 数据生成表格

假设您有一个包含您想要在 Markdown 文件中以表格形式显示的数据的 CSV 文件。您可以使用 pandas 读取 CSV 文件,将其转换为 DataFrame,然后将其输出为 Markdown 表格。

使用三重反引号代码块

import pandas as pd
csv_data = "Name,Age,Score\nAlice,30,90\nBob,25,85\nCharlie,22,95"
with open("sample_data.csv", "w") as f:
    f.write(csv_data)
df = pd.read_csv("sample_data.csv")
print(df.to_markdown(index=False))

这将渲染为

姓名 年龄 分数
Alice 30 90
Bob 25 85
Charlie 22 95

:star: 想法 5:以列表形式显示 API 数据

您可以使用 markdown-code-runner 来进行 API 调用,并将数据以列表形式显示在您的 Markdown 文件中。在这个例子中,我们将使用 requests 库从 API 获取数据,并以列表形式显示结果。

使用隐藏的代码块

<!-- CODE:START -->
<!-- import requests -->
<!-- response = requests.get("https://jsonplaceholder.typicode.com/todos?_limit=5") -->
<!-- todos = response.json() -->
<!-- for todo in todos: -->
<!--     print(f"- {todo['title']} (User ID: {todo['userId']}, Completed: {todo['completed']})") -->
<!-- CODE:END -->
<!-- OUTPUT:START -->
<!-- OUTPUT:END -->

这将渲染为

  • delectus aut autem(用户 ID:1,完成:否)
  • quis ut nam facilis et officia qui(用户 ID:1,完成:否)
  • fugiat veniam minus(用户 ID:1,完成:否)
  • et porro tempora(用户 ID:1,完成:是)
  • laboriosam mollitia et enim quasi adipisci quia provident illum(用户 ID:1,完成:否)

:crab: 想法 6:运行 Rust 程序

我们可以使用 markdown-code-runner 将 Rust 代码写入文件,然后使用隐藏的 bash 代码块来运行代码并显示输出。

下面的代码实际上是执行过的,请查看 README.md 的纯文本版本 以了解其工作原理。

fn main() {
    println!("Hello, world!");
}

执行后产生以下内容

Hello, world!

这仅仅是使用 Markdown Code Runner 增强您的 Markdown 文档动态内容的一些例子。可能性是无穷无尽的!

:page_with_curl: 许可证

markdown-code-runner 采用 MIT 许可协议 发布。请在您的项目中包含 LICENSE 文件,并引用原始来源。

:handshake: 贡献

欢迎贡献!要贡献,请按照以下步骤操作

  1. 在 GitHub 上派生存储库:https://github.com/basnijholt/markdown-code-runner
  2. 为您的更改创建一个新的分支。
  3. 进行更改,确保它们遵循代码风格和指南。
  4. 提交包含您的更改描述的拉取请求。

请在 GitHub 问题跟踪器上报告任何问题或错误:https://github.com/basnijholt/markdown-code-runner/issues

感谢您对 markdown-code-runner 的兴趣!

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装软件包 的信息。

源分布

markdown-code-runner-2.1.0.tar.gz (15.8 kB 查看哈希值

上传时间

构建分布

markdown_code_runner-2.1.0-py3-none-any.whl (11.9 kB 查看哈希值

上传时间 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面