How to execute command with parameters?
Asked Answered
O

4

32

How am I to execute a command in Java with parameters?

I've tried

Process p = Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php -m 2"});

which doesn't work.

String[] options = new String[]{"option1", "option2"};
Runtime.getRuntime().exec("command", options);

This doesn't work as well, because the m parameter is not specified.

Orlandoorlanta answered 20/8, 2011 at 20:27 Comment(0)
M
30

See if this works (sorry can't test it right now)

Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php", "-m", "2"});
Mcnulty answered 20/8, 2011 at 20:40 Comment(1)
This should mention that this is important to set one String per command; parameter or value. So "-m 2" might not work. This need to be "-m", "2"Musetta
G
26

Use ProcessBuilder instead of Runtime#exec().

ProcessBuilder pb = new ProcessBuilder("php", "/var/www/script.php", "-m 2");
Process p = pb.start();
Guadalajara answered 20/8, 2011 at 20:35 Comment(1)
If that doesn't work: new ProcessBuilder("php", "/var/www/script.php", "-m", "2");Guadalajara
S
1

The following should work fine.

Process p = Runtime.getRuntime().exec("php /var/www/script.php -m 2");
Septet answered 20/8, 2011 at 20:34 Comment(0)
B
0

Below is java code for executing python script with java.

ProcessBuilder:

  • First argument is path to virtual environment
  • Second argument is path to python file
  • Third argument is any argumrnt you want to pass to python script
public class JavaCode {
    public static void main(String[] args) throws IOException {
        String lines = null;
        ProcessBuilder builder = new ProcessBuilder("/home/env-scrapping/bin/python",
                "/home/Scrapping/script.py", "arg1");
        Process process = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while ((lines = reader.readLine())!=null) {
            System.out.println("Line: " + lines);
        }
    }
}

First is virtual environment path

Broderic answered 1/9, 2022 at 6:35 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Bolivia

© 2022 - 2024 — McMap. All rights reserved.