作者:雨之夜惊恐_136 | 来源:互联网 | 2023-05-18 14:06
yihuigivesanexampleofusingthecacheoptionforthedifferentenginesyihui给出了一个使用不同引擎的缓存选项的示例
yihui gives an example of using the cache option for the different engines
yihui给出了一个使用不同引擎的缓存选项的示例
https://github.com/yihui/knitr-examples/blob/master/023-engine-python.Rmd
I can't seem to get it to work for python.
我似乎无法让它为python工作。
The following works
以下作品
```{r,engine='python',cache=TRUE}
x=10
print x
```
But this doesn't work
但这不起作用
```{r,engine='python',cache=TRUE}
x = 10
```
```{r,engine='python',cache=TRUE}
print x
```
Anyone have an idea?
有人有想法吗?
1 个解决方案
The chunk option cache
doesn't save all the variables defined in the block for languages other than R
. It is, though, saving printed outputs, so if you compute something that takes a while, any results will not need to be re-computed. From the knitr
website:
块选项缓存不会保存块中为R以外的语言定义的所有变量。但是,它会保存打印输出,因此如果计算需要一段时间的内容,则不需要重新计算任何结果。来自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).
除了engine ='R'(默认),所有块都在不同的会话中执行,因此无法直接共享变量。如果我们想要使用在先前块中创建的对象,我们通常必须将它们写入文件(作为副作用)。对于bash引擎,我们可以使用Sys.setenv()将变量从R导出到bash(示例)。
It's possible to save a few values in the shell's environment, and retrieve those values from the other cells by reading the environment. This is the approach Yihui took in the Polyglot example. So, for Python, if you can format the value as a string and pass it to sys.setenv()
, you could use that value in another cell (run as a separate Python session) by calling sys.getenv()
.
可以在shell的环境中保存一些值,并通过读取环境从其他单元格中检索这些值。这是Yihui在Polyglot例子中所采用的方法。因此,对于Python,如果您可以将值格式化为字符串并将其传递给sys.setenv(),则可以通过调用sys.getenv()在另一个单元格中运行该值(作为单独的Python会话运行)。
Though, I am mildly confused about the approach taken with the C
and Fortran
engines. Those seem to have access to compiled functions in later chunks by using some function called .C()
or a function called .Fortran()
. But it seems that Python does not have an equivalent.
尽管如此,我对使用C和Fortran引擎的方法感到有些困惑。那些似乎可以通过使用一些名为.C()的函数或一个名为.Fortran()的函数来访问后续块中的编译函数。但似乎Python没有相应的东西。