Tho*_*ius 8 python markdown r knitr
我想和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)
```
Run Code Online (Sandbox Code Playgroud)
---
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
```
Run Code Online (Sandbox Code Playgroud)
#! /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()
Run Code Online (Sandbox Code Playgroud)
现在运行:
./knit2py.r test.pymd test.md
Run Code Online (Sandbox Code Playgroud)
是的,的确是这样,的确,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.
Run Code Online (Sandbox Code Playgroud)
现在运行:
pweave -f pandoc test.mdw
Run Code Online (Sandbox Code Playgroud)
在pweave的网站上有一条注释,指出使用python3进行pip安装会失败。但是,仅运行时,我一点也没有问题:
pip install pweave
pip install markdown
Run Code Online (Sandbox Code Playgroud)
也许,这只是一个旧的音符。