栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

无法从Java程序执行R脚本?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

无法从Java程序执行R脚本?

您将必须

/usr/bin/Rscript
直接运行。另外,该程序不会从标准输入中读取脚本(您必须将脚本的路径指定为的参数
Rscript
),因此您必须:

  • 创建一个临时文件
  • 写你的脚本
  • 用Rscript执行脚本
  • 删除您的临时文件(作为良好的编程习惯)

例如,这是一个POC:

public static void main(String[] args) throws IOException, InterruptedException {    // Your script    String script = "#!/usr/bin/env Rscriptn" + "n" + "sayHello <- function() {n" + "    print('hello')n" + "}n" + "n" + "sayHello()n";    // create a temp file and write your script to it    File tempscript = File.createTempFile("test_r_scripts_", "");    try(OutputStream output = new FileOutputStream(tempscript)) {        output.write(script.getBytes());    }    // build the process object and start it    List<String> commandList = new ArrayList<>();    commandList.add("/usr/bin/Rscript");    commandList.add(tempscript.getAbsolutePath());    ProcessBuilder builder = new ProcessBuilder(commandList);    builder.redirectErrorStream(true);    Process shell = builder.start();    // read the output and show it    try(BufferedReader reader = new BufferedReader( new InputStreamReader(shell.getInputStream()))) {        String line;        while((line = reader.readLine()) != null) { System.out.println(line);        }    }    // wait for the process to finish    int exitCode = shell.waitFor();    // delete your temp file    tempscript.delete();    // check the exit pre (exit pre = 0 usually means "executed ok")    System.out.println("EXIT CODE: " + exitCode);}

或者, 如果您的脚本的第一行带有“ shebang”,则 可以进行以下更改:

  • 将其可执行属性设置为“ true”
  • 使用临时文件的路径作为commandList中的第一个元素(即delete
    commandList.add("/usr/bin/Rscript");

要修改的代码部分为:

...// create a temp file and write your script to itFile tempscript = File.createTempFile("test_r_scripts_", "");tempscript.setExecutable(true);try(OutputStream output = new FileOutputStream(tempscript)) {    output.write(script.getBytes());}// build the process object and start itList<String> commandList = new ArrayList<>();commandList.add(tempscript.getAbsolutePath());ProcessBuilder builder = new ProcessBuilder(commandList);...


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428678.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号