knitr - Python 引擎缓存选项不起作用

knitr - Python engine cache option not working

yihui给出了不同引擎使用缓存选项的例子

https://github.com/yihui/knitr-examples/blob/master/023-engine-python.Rmd

我似乎无法让它为 python 工作。

以下作品

```{r,engine='python',cache=TRUE}
x=10
print x
```

但这行不通

```{r,engine='python',cache=TRUE}
x = 10
```

```{r,engine='python',cache=TRUE}
print x
```

有人有想法吗?

块选项 cache 不会保存块中为 R 以外的语言定义的所有变量。不过,它会保存打印输出,因此如果您计算需要一段时间的东西,任何结果都不需要 re-computed。来自 knitr 网站:

Except engine='R' (default), all chunks are executed in separate sessions, so the variables cannot be directly shared. If we want to make use of objects created in previous chunks, we usually have to write them to files (as side effects). For the bash engine, we can use Sys.setenv() to export variables from R to bash (example).

可以在 shell 的环境中保存一些值,并通过读取环境从其他单元格中检索这些值。这就是方法Yihui took in the Polyglot example。因此,对于 Python,如果您可以将值格式化为字符串并将其传递给 sys.setenv(),则可以在另一个单元格中使用该值(运行 作为单独的 Python会话)通过调用 sys.getenv().

不过,我对 CFortran 引擎采用的方法感到有点困惑。那些似乎可以通过 using some function called .C() or a function called .Fortran() 访问后面块中的编译函数。但似乎 Python 没有等价物。