在Markdown中运行Python代码

有关在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>

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

你能不在Markdown中运行Python代码?如果没有,有什么替代品?

(使用Ubuntu的python-markdown包.)

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

使用块作为:

<<engine='python', engine.path='python3'>>=
# python code
@

>默认情况下,engine.path使用python可执行文件,在大多数Linux系统中仍然是python2.如果你想要Python 2,你可以省略它.
>如果要省略代码打印输出,请不要忘记传递echo = FALSE,并且结果=’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:它适用于乳胶和降价.我还没有尝试过.

点赞