将 python 与 knitr 一起使用

Using python together with knitr

我想 python 和 knitr 一起使用。但是,python 块似乎是单独评估的,并且块之间的变量定义丢失了。

如何解决这个问题?

最小示例:

test.pymd

---
title: "Minimal example"
---

With a print statement.

```{r hello}
x = 'Hello, Python World!'
print(x)
```

Without a print statement.

```{r world}
print(x)
```

test.md

---
title: "Minimal example"
---

With a print statement.


```python
x = 'Hello, Python World!'
print(x)
```

```
Hello, Python World!
```

Without a print statement.


```python
print(x)
```

```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined
```

knit2py.r

#! /usr/bin/Rscript --vanilla

args <- commandArgs(TRUE)

if(length(args) < 1) {
    message("Need arguments in the format: %.pymd [%.md]")
    q(status=1)
}

name <- substr(args[1],1,nchar(args[1])-4)

if(length(args) < 2) {
    args[2] <- paste0(name,".md")
}

library(knitr)
opts_chunk$set(engine = 'python')

res <- try(knit(args[1], args[2]))

if(inherits(res, "try-error")) {
    message("Could not successfully knit RMD (or PYMD) to MD")
    q(status=1)
} else q()

现在 运行:

./knit2py.r test.pymd test.md 

是的,确实,knitr 目前无法为 R 以外的语言评估在多个块上延伸的代码。解决方案不是使用 knitr,而是使用 pweave。对源文件的修改很少:

test.mdw

---
title: "Minimal example"
---

With a print statement.

<<>>=
x = 'Hello, Python World!'
print(x)
@

Without a print statement.

<<>>=
print(x)
@

The end.

现在 运行:

pweave -f pandoc test.mdw

pweave 的网站上有一条说明,使用 python3 进行 pip 安装会失败。不过,我完全没有问题,只要 运行ning:

pip install pweave
pip install markdown

也许,这只是一张旧纸条。

这里有一个简单的例子,说明了在 knittr 块中 运行 python 编码的两种方法:

---
title: "Works with python"
output: github_document
---

Does **knitr** work with Python? Use the chunk option `engine='python'`:

```{r engine='python'}
x = 'hello, python world!'
print(x)
print(x.split(' '))
```

Or use the syntax ```` ```{python} ````:

```{python}
x = 'hello, python world!'
print(x.split(' '))
```

我从knittr examples

那里得到的

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 的交互式绘图 将其整合到您的流程中。它将满足您的需要,而不是您需要针对工具进行调整。 自定义 CSS 支持(HTTP 和本地文件)