Running scripts through processbuilder

I am trying to run Python, Ruby, C, C ++ and Java scripts from a java program, and Processbuilder was suggested to me as a good way to run scripts. As far as I understand, Processbuilder basically runs its own files (.exe on windows, etc.). However, I have heard several things about running scripts (non-native) files using Processbuilder. Unfortunately, everything I find on this subject is incredibly vague.

If someone can clarify the way to run non-standard scripts like Python, Ruby, etc., I would really appreciate it!

+5
source share
2 answers

You can check the documentation ProcessBuilderin Sunoracle , but basically you can run the interpreter for the scripting language and pass the script you want to run it.

For example, let's say you have a script in /home/myuser/py_script.py, and pythonis located in/usr/bin/

class ProcessRunner
{
    public static void main(String [] args)
    {
        ProcessBuilder pb = new ProcessBuilder("/usr/bin/python", "/home/myuser/py_script.py");
        Process p = pb.start();
    }
}

An extremely simple example, you can become a favorite in changing the working directory and changing the environment.

You can also build ProcessBuilderwith an array Stringor subtype List<String>. The first item in the list should be the program / executable that you want to run, and all of the following items are the arguments of the program.

String pbCommand[] = { "/usr/bin/python", "/home/myuser/py_script.py" };
ProcessBuilder pb = new ProcessBuilder(pbCommand);
Process p = pb.start();
+6
source

To avoid having to manually enter the entire location of the script, which can also lead to portability problems, here's what I did:

String pwd = System.getProperty("user.dir");

ProcessBuilder pb = new ProcessBuilder("/usr/bin/python", pwd+'/'+scriptName, arg1, arg2);
Process p = pb.start();
0

All Articles