You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google Colab运行R内核时如何访问操作系统shell

Colab R内核调用Shell命令的解决方案

Colab R内核不支持Python生态的!、%%shell魔法语法,但可以通过R原生的系统调用函数实现同等效果,具体用法如下:

  • 方法1:使用system()函数执行单条命令
    该函数是R最基础的系统调用接口,可直接运行传入的shell命令,示例如下:
    # 直接执行命令,输出打印到控制台
    system("ls -la")
    
    # 如需捕获命令输出存入R变量,添加intern = TRUE参数即可
    dir_content <- system("ls -la", intern = TRUE)
    print(dir_content)
    
  • 方法2:使用system2()函数(官方更推荐)
    该函数支持参数结构化传递,可避免shell注入风险,更适合带动态参数的调用场景:
    # 无参数调用示例,打印当前工作路径
    system2("pwd")
    
    # 带参数调用示例,查看/content目录下的文件详情
    system2("ls", args = c("-lh", "/content"))
    
  • 方法3:执行多行Shell脚本
    如需连续运行多条shell命令,可将命令拼接为字符串传入调用函数即可:
    multi_shell_cmd <- "
    cd /content
    echo '测试内容' > tmp_test.txt
    ls -l tmp_test.txt
    cat tmp_test.txt
    "
    system(multi_shell_cmd)
    

注意:R内核下执行shell命令的默认工作路径与R当前工作路径一致,可通过getwd()查看当前路径、setwd("目标路径")切换路径,无需通过shell的cd命令长期修改工作目录。

内容的提问来源于stack exchange,提问作者Stephen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 17:36:04