Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running scripts through processbuilder

I'm 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 the scripts. From what I understand, Processbuilder mostly runs native files (.exe on windows, etc.). However, I have heard a few things about running scripts (nonnative) files using Processbuilder. Unfortunately, everything I find on the subject is incredibly vague.

If someone could clarify a way to run nonnative scripts such as Python, Ruby, etc. I would be most grateful!

like image 908
Curlystraw Avatar asked Jan 10 '11 15:01

Curlystraw


1 Answers

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

For example, let's say you have a script in /home/myuser/py_script.py, and python is 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 basic example, you can get fancier with changing the working directory and change the environment.

You can also construct ProcessBuilder with a String array or a subtype of List<String>. The first item in the list should be the program/executable you want to run, and all the following items are arguments to the program.

String pbCommand[] = { "/usr/bin/python", "/home/myuser/py_script.py" };
ProcessBuilder pb = new ProcessBuilder(pbCommand);
Process p = pb.start();
like image 88
逆さま Avatar answered Oct 13 '22 19:10

逆さま