【问题标题】:How to write wrapper R file for executing .sh file如何编写用于执行 .sh 文件的包装 R 文件
【发布时间】:2021-05-10 17:26:39
【问题描述】:

我的目标是使用这个 shell 调用一个 python 模型。有没有办法制作一个包装 R 文件来执行这个 sh 文件?

【问题讨论】:

    标签: python r shell sh


    【解决方案1】:

    运行操作系统命令的推荐方法是函数system2

    system2("sh", args = "model.sh")
    

    如果文件model.sh在主目录下,其内容如下:

    # file: model.sh
    pwd
    cd $1
    pwd
    cd $2
    pwd
    cd ~
    

    命令"sh" 后跟所有 参数、脚本名称及其参数,将更改目录两次,然后更改回主目录"~"

    system2(command = "sh", args = c("model.sh", "tmp", "tmp"))
    #/home/rui
    #/home/rui/tmp
    #/home/rui/tmp/tmp
    
    getwd()
    #[1] "/home/rui"
    

    如果要使脚本成为可执行文件,可以从 R 命令行完成

    system2(command = "chmod", args = c("+x", "model.sh"))
    

    那么system2 的第一个参数是命令(脚本文件),脚本的参数在args 中传递。

    system2(command = "./model.sh", args = c("tmp", "tmp"))
    #/home/rui
    #/home/rui/tmp
    #/home/rui/tmp/tmp
    
    getwd()
    #[1] "/home/rui"
    

    返回之前的权限。

    system2(command = "chmod", args = "-x model.sh")
    

    任何系统命令都可以这样运行,见help("system2")

    参数向量可以是单个字符串,如上面最后一个chmod 命令,也可以是每个参数按顺序排列的向量。

    system2("chmod", args = c("-x", "model.sh"))
    

    在这种情况下,system2 的返回值是操作系统命令错误代码。

    res <- system2(command = "ls", args = c("-l", "model.sh"))
    #-rwxrwxr-x 1 rui rui 45 fev  7 07:24 model.sh
    
    res
    #[1] 0
    

    要让命令返回其输出的字符向量,请设置stdout = TRUE

    system2(command = "chmod", args = c("+x", "model.sh"))
    main_sh <- system2(command = "./model.sh",
                       args = c("model.py","x.json"),
                       stdout = TRUE
    )
    

    有关返回值的更多详细信息,请参阅帮助页面部分Value

    【讨论】:

    • 如何将文件名和json文件作为参数传入sh文件
    • @James 看看编辑是否回答了问题。
    • 我所有的工作目录都在R的当前工作目录中。这是正确的做法吗..shell是一个可执行文件,参数是python文件名,第二个参数是json文件main_sh
    • @James 是的,就是这样。将可执行文件作为第一个参数或命名参数 command = "model.sh" 传递,然后将参数向量传递给 model.sh
    • @James 是的,有基础 R writeLineswrite.table,这取决于你得到什么。
    猜你喜欢
    • 2010-10-14
    • 2020-01-24
    • 1970-01-01
    • 2014-12-17
    • 2012-11-24
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多