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.
4 Answers 4
See if this works (sorry can't test it right now)
Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php", "-m", "2"});
answered Aug 20, 2011 at 20:40
Chris Stratton
40.5k6 gold badges89 silver badges120 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
AxelH
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"Use ProcessBuilder instead of Runtime#exec().
ProcessBuilder pb = new ProcessBuilder("php", "/var/www/script.php", "-m 2");
Process p = pb.start();
answered Aug 20, 2011 at 20:35
Matt Ball
361k102 gold badges655 silver badges725 bronze badges
1 Comment
Matt Ball
If that doesn't work:
new ProcessBuilder("php", "/var/www/script.php", "-m", "2");The following should work fine.
Process p = Runtime.getRuntime().exec("php /var/www/script.php -m 2");
answered Aug 20, 2011 at 20:34
Codemwnci
55.1k10 gold badges101 silver badges130 bronze badges
Comments
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
answered Sep 1, 2022 at 6:35
Sardar Fahad Ashfaq
918 bronze badges
1 Comment
Community
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.
lang-java