running scripts through processbuilder

∥☆過路亽.° 提交于 2019-12-21 17:25:06

问题


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!


回答1:


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();



回答2:


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();


来源:https://stackoverflow.com/questions/4648435/running-scripts-through-processbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!