我在一個String變量中有一個Rscript,我想從Java程序執行它,並將一些變量傳遞給它。如果我獨立執行該R腳本,它可以正常工作。我已經轉換的R腳本於一行通過轉義它通過使用Python程序一切,如下所示:無法從java程序執行R腳本?
import json
jsonstr = json.dumps({"script": """\
#!/usr/bin/Rscript
# read the data file
library('jsonlite')
library('rpart')
args <- as.list(Sys.getenv(c(
"path",
"client_users")))
if (args[["path"]]==""){
args[["path"]] <- "."
}
# other stuff here
# other stuff here
"""})
print jsonstr
我用印刷串出,並將其存儲在字符串變量,然後我正在與下面的代碼執行,並根本不起作用。我正在將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<String> 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中使用簡單的打印地獄腳本,而不是使用我的上面的腳本來查看我是否可以執行它呃Java或不。
// this will print hello
String script = "#!/usr/bin/env Rscript\nsayHello <- function(){\n print('hello')\n}\n\nsayHello()\n";
當我執行這個腳本commandList.add("/bin/bash");
,我得到這個錯誤:
/bin/bash: line 2: syntax error near unexpected token `('
/bin/bash: line 2: `sayHello <- function(){'
但是,如果我用這個commandList.add("/bin/sh");
執行,我得到這個錯誤:
/bin/sh: 2: Syntax error: "(" unexpected