我想和knitr一起使用python。但是,python块似乎单独进行评估,并且变量定义在块之间丢失。
如何解决这个问题?
最小例子:
---
title: "Minimal example"
---
With a print statement.
```{r hello}
x = 'Hello, Python World!'
print(x)
```
Without a print statement.
```{r world}
print(x)
```
---
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
```
#! /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
答案 0 :(得分:4)
是的,确实,knitr目前无法评估除R以外的语言的多个块的代码。解决方案不是使用knitr而是使用pweave。对源文件的修改很少:
---
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 install pweave
pip install markdown
也许,这只是一个旧笔记。
答案 1 :(得分:0)
这是在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那里得到了