Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to execute R script from java program?

I have a Rscript in a String variable and I want to execute it from Java program and pass some variable to it. If I execute that R script standalone, it works fine. I have converted that R script to one line by escaping it everything by using Python program as shown below:

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

I use the printed string out and store it in String variable and then I am executing with below code and it doesn't work at all. I am passing path and client_users variable to above 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);
}

Above code works fine with bash shell script. Is there anything I need to do special for R script? I will be using same code for bash script and R scripts as well.

And this is the error I am getting:

/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')' 

And if I remove commandList.add("/bin/bash"); and add commandList.add("/bin/Rscript"); then I see below error:

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

Update:-

Instead of using my above script, I decided to use simple print hell script in r to see whether I can execute it through Java or not.

// this will print hello
String script = "#!/usr/bin/env Rscript\nsayHello <- function(){\n   print('hello')\n}\n\nsayHello()\n";

When I execute this script with commandList.add("/bin/bash");, I get this error:

/bin/bash: line 2: syntax error near unexpected token `('
/bin/bash: line 2: `sayHello <- function(){'

But if I execute with this commandList.add("/bin/sh");, I get this error:

/bin/sh: 2: Syntax error: "(" unexpected
like image 830
user1950349 Avatar asked Sep 27 '22 17:09

user1950349


1 Answers

You will have to run /usr/bin/Rscript directly. Also, this program doesn't read scripts from the standard input (you have to specify the path to the script as an argument for Rscript), so you will have to:

  • Create a temp file
  • Write your script
  • Execute your script with Rscript
  • Delete your temp file (as a good programming practice)

As an example, this is a POC:

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

    // Your script
    String script = "#!/usr/bin/env Rscript\n" +
            "\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 code (exit code = 0 usually means "executed ok")
    System.out.println("EXIT CODE: " + exitCode);
}

As an alternative, and if your script has a "shebang" as the first line, you could do these changes:

  • set its executable attribute to "true"
  • use the path to the temp file as first element in the commandList (i. e. delete commandList.add("/usr/bin/Rscript");)

the part of the code to be modified would be:

...

// create a temp file and write your script to it
File 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 it
List<String> commandList = new ArrayList<>();
commandList.add(tempScript.getAbsolutePath());
ProcessBuilder builder = new ProcessBuilder(commandList);

...
like image 173
morgano Avatar answered Oct 18 '22 14:10

morgano