I can execute Linux commands like ls
or pwd
from Java without problems but couldn't get a Python script executed.
This is my code:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
Nothing happened. It reached SEND but it just stopped after it...
I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).
You would do worse than to try embedding jython and executing your script. A simple example should help:
If you need further help, leave a comment. This does not create an additional process.
@Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named)
Process.getOutputStream()
.You cannot use the PIPE inside the
Runtime.getRuntime().exec()
as you do in your example. PIPE is part of the shell.You could do either
.exec()
orYou can do something similar to the following