运行 Python Markdown 代码

Running Python code in Markdown

有很多关于在 Markdown 文档中使用 Python 代码的信息。但这一切似乎都是为了展示 Python 片段,而不是创建美观的文档。

我可以不将 Python 和 Markdown 结合在一个文档中,就像您可以结合 R 和 Markdown 一样吗?

MWE:

Output some text from Python in **Markdown**:
```python
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
print(clf.predict_proba(iris.data[:1, :]))
```

编译:markdown_py markdown.txt

<p>Output some text from Python in <strong>Markdown</strong>:
<code>python
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
clf.predict_proba(iris.data[:1, :])</code></p>

它显示代码(很酷),但实际上 运行 它没有。

你不能运行 Python Markdown 代码吗?如果没有,还有哪些替代方案?

(使用 Ubuntu 中的 python-markdown 包。)

好吧,我刚刚找到了解决方案:

将块用作:

<<engine='python', engine.path='python3'>>=
# python code
@
  • engine.path 默认使用 python 可执行文件,在大多数 Linux 系统中仍然是 python2。如果需要可以省略 Python 2.
  • 如果您想省略代码打印输出,请不要忘记传递 echo=FALSE,以及 results='asis',这样它就不会尝试转义输出。

您可以在文档的开头使用以下块来设置默认值:

<<r setup, include=FALSE>>=
knitr::opts_chunk$set(echo=FALSE, engine='whathaveyou', ...)
@

将文件另存为markdown.Rmd,并使用R 和knitr 对其进行编译。它将 运行 Python 代码使用 python.

R 命令:rmarkdown::render('markdown.Rmd','output.html')

或者直接使用RStudio.

附录: 原生解决方案显然是 Pweave:它适用于 latex 和 markdown。不过我还没试过。

截至 2018 年,CRAN-package reticulate 提供了更好的解决方案。

'Python' 模块、类 和函数的接口。调用 'Python' 时,R 数据类型会自动转换为其等效的 'Python' 类型。当值从 'Python' 返回到 R 时,它们将转换回 R 类型。兼容所有版本 'Python' >= 2.7.

Zen knit 是 Python 的 RMarkdown 替代品。报告示例位于 https://github.com/Zen-Reportz/zen_knit/tree/main/doc/example

它支持直接从 python 或类似于 .Rmd 的 .pyz 文件创建报告。

当前功能

  • Python 3.7+ 兼容性

  • 支持 IPython 魔法和丰富的输出。

  • 在块中执行 python 代码并将输入和输出捕获到 报告。

  • 使用隐藏代码块,即执行代码,但不在输出文件中打印。

  • 捕获 matplotlib 图形。

  • 评估使用 `{ }

    标记的文档块中的内联代码
  • 从 Python 脚本发布报告。类似于 R 降价。

  • 使用 plotly 的交互式绘图

  • 将其整合到您的流程中。它将满足您的需要,而不是您需要针对工具进行调整。 (您可以直接使用 python 生成报告。示例 here

  • 自定义 CSS 支持(HTTP 和本地文件)