如何在 运行 R 内核时访问 google Colab 中的 shell

How to access the shell in google Colab when running the R kernel

当我将 Python 与 colab 一起使用时,您可以使用 !%%shell 之类的东西访问底层操作系统,例如 !ls 以列出文件。

当我将 colab 与 R 内核一起使用时,!%%shell 技巧不起作用。在这种情况下,有没有办法从 colab 调用 shell?

https://colab.research.google.com/#create=true&language=r

有基本的 R 函数 system,它允许您调用笔记本后面的 shell。由于 colab 抑制了标准输出,因此需要设置选项 intern = TRUE 才能将结果视为 R 字符向量。为了正确显示换行符,我定义了一个名为 shell_call 的函数,它类似于 ipython:

中的 !
shell_call <- function(command, ...) {
  result <- system(command, intern = TRUE, ...)
  cat(paste0(result, collapse = "\n"))
}

shell_call("ls -lah / | head")

如解释的那样,魔法的实现是特定于内核的here

To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether Magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the % syntax element for Magics as % is not a valid unary operator in Python. However, % might have meaning in other languages.

R 不提供以这种方式实现魔法的良好条件,例如 %% 用作模运算符,! 用作逻辑非运算符。

这就是 IRkernel 的开发人员选择不支持 %%cell 魔法的原因 - 请参阅 this or this

正如在使用 IRkernel 时的评论中所述,您需要在 R 语言本身中找到解决方案,例如使用内置函数访问 shell system2("ls", stdout = TRUE) 或搜索文件 list.files() (您可能还想按照@danlooo 的建议将它们包装在自定义函数中)。

如果您仍想使用魔法,另一种方法是将 R 魔法(扩展名 rmagic)与 IPython 内核一起使用,如图 or here: