java 调用 r脚本_无法从Java程序执行R脚本?

我在String变量中有一个Rscript,我想从Java程序执行它并将一些变量传递给它。如果我独立执行该R脚本,则可以正常工作。我已通过使用Python程序将所有脚本转义,从而将该R脚本转换为一行,如下所示:

import json

jsonstr = json.dumps({"script": """\

#!/usr/bin/Rscript

# read the data file

library('jsonlite')

library('rpart')

args

"path",

"client_users")))

if (args[["path"]]==""){

args[["path"]]

}

# other stuff here

# other stuff here

"""})

print jsonstr

我将打印出的字符串用完,并将其存储在String变量中,然后使用以下代码执行,但它根本不起作用。我正在传递path和client_users可变到上述R脚本。

public static void main(String[] args) throws IOException, InterruptedException {

// this is your script in a string

// String script = "#!/bin/bash\n\necho \"Hello World\"\n\n readonly PARAM1=$param1\n echo $PARAM1\n\nreadonly PARAM2=$param2\n echo $PARAM2\n\n";

String script = "above R Script here";

List commandList = new ArrayList<>();

commandList.add("/bin/bash");

ProcessBuilder builder = new ProcessBuilder(commandList);

builder.environment().put("path", "/home/david");

builder.environment().put("client_users", "1000");

builder.redirectErrorStream(true);

Process shell = builder.start();

// Send your script to the input of the shell, something

// like doing cat script.sh | bash in the terminal

try(OutputStream commands = shell.getOutputStream()) {

commands.write(script.getBytes());

}

// read the outcome

try(BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()))) {

String line;

while((line = reader.readLine()) != null) {

System.out.println(line);

}

}

// check the exit code

int exitCode = shell.waitFor();

System.out.println("EXIT CODE: " + exitCode);

}

上面的代码可以与bash shell脚本一起正常工作。我需要为R脚本做些特别的事情吗?我将对bash脚本和R脚本使用相同的代码。

这是我得到的错误:

/bin/bash: line 7: -: No such file or directory /bin/bash: line 10: syntax error near unexpected token `'jsonlite'' /bin/bash: line 10: `library('jsonlite')'

如果我删除commandList.add("/bin/bash");并添加,commandList.add("/bin/Rscript");则会看到以下错误:

Cannot run program "/bin/Rscript": error=2, No such file or directory

更新:-

我决定不使用上面的脚本,而是决定在r中使用简单的print hell脚本来查看是否可以通过Java执行它。

// this will print hello

String script = "#!/usr/bin/env Rscript\nsayHello

当我使用执行脚本时commandList.add("/bin/bash");,出现以下错误:

/bin/bash: line 2: syntax error near unexpected token `('

/bin/bash: line 2: `sayHello

但是,如果执行this commandList.add("/bin/sh");,则会出现此错误:

/bin/sh: 2: Syntax error: "(" unexpected

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值