在Markdown中运行Python代码

Ric*_*ruz 5 python markdown

Markdown文档中有很多有关使用Python代码的信息。但这似乎只是为了演示Python代码段,而不是创建美观的文档。

我不能像在R和Markdown中那样将Python和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, :]))
```
Run Code Online (Sandbox Code Playgroud)

编译此: 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>
Run Code Online (Sandbox Code Playgroud)

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

您不能在Markdown中运行Python代码吗?如果没有,那还有什么选择?

(使用来自Ubuntu的python-markdown软件包。)

Ric*_*ruz 5

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

使用块作为:

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

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

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

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

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

或者只使用RStudio

附录:本机解决方案显然是Pweave:它适用于 Latex 和 Markdown。不过我还没有尝试过。