【问题标题】:Using python together with knitr将python与knitr一起使用
【发布时间】:2017-03-03 11:42:28
【问题描述】:

我想将 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 

【问题讨论】:

标签: python r markdown knitr


【解决方案1】:

是的,的确,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 安装会失败。不过,我在运行时完全没有问题:

pip install pweave
pip install markdown

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

【讨论】:

    【解决方案2】:

    这是在 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得到它

    【讨论】:

      【解决方案3】:

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

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

      当前功能 Python 3.7+ 兼容性 支持 IPython 魔法和丰富的输出。 在块中执行 python 代码并将输入和输出捕获到报告中。 使用隐藏的代码块,即代码被执行,但不打印在输出文件中。 捕获 matplotlib 图形。 评估使用 `{ } 标记的文档块中的内联代码 从 Python 脚本发布报告。类似于 R 降价。 使用 plotly 的交互式绘图 将其集成到您的流程中。它将满足您的需求,而不是您需要调整工具。 自定义 CSS 支持(HTTP(s) 和本地文件)

      【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多