5

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!

ergosys
49.2k5 gold badges53 silver badges72 bronze badges
asked Jan 10, 2011 at 15:35

2 Answers 2

6

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();
answered Jan 10, 2011 at 15:40
Sign up to request clarification or add additional context in comments.

Comments

0

To avoid having to manually enter the entire location of the script, which may also result in portability issues, 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();
answered Apr 14, 2015 at 6:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.