У меня есть Rscript в переменной String, и я хочу выполнить ее из программы Java и передать ей некоторую переменную. Если я выполняю автономный R script, он отлично работает. Я преобразовал это R script в одну строку, экранируя его все, используя программу Python, как показано ниже:
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
Я использую напечатанную строку и сохраняю ее в переменной String, а затем выполняю код ниже, и он вообще не работает. Я передаю переменную path и client_users выше R script.
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 script. Есть ли что-нибудь, что мне нужно сделать специально для R script? Я буду использовать тот же код для bash script и 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
Обновление: -
Вместо того, чтобы использовать мой выше script, я решил использовать простой print hell script в r, чтобы посмотреть, могу ли я выполнить его через Java или нет.
// this will print hello
String script = "#!/usr/bin/env Rscript\nsayHello <- function(){\n   print('hello')\n}\n\nsayHello()\n";
Когда я выполняю этот script с 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
