Python on Jar - Running python Script after process end in Java - java

I want to run a python script(tensorflow's Image label script) after RPi's camera module captures a photo using a jar file. I have tried both Runtime and ProcessBuilder, but it says no file or Directory found.
Here's my Code for the Runtime Code:
Process rt = Runtime.getRuntime().exec("python3 -m scripts.image-label.py");
rt.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
String read = in.readLine();
ML = read;
result resfin = new result();
resfin.setVisible(true);
And here's the code for my ProcessBuilder one:
ProcessBuilder builder = new ProcessBuilder("/home/pi/Desktop/ML/scripts/image-label.py");
Process np = builder.start();
np.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(np.getInputStream()));
String read = in.readLine();
ML = read;
result resfin = new result();
resfin.setVisible(true);
Am i doing something wrong? Or am i missing something? Any help would be appreciated!

I have tried with the following code, it is working fine, though I have not tried with -m "module" flag, since I do not know how to create a module file in python.
Found some of the issues with code:
1. You need to pass python3 as an argument to process builder as shown below
2. Provide an absolute path for a python file.
3. You can use either of Runtime or ProcessBuilder without an issue.
// Process rt = Runtime.getRuntime().exec("python3 -m /Users/<user-name>/demo/JavaNotepad/src/main/java/com/mypython.py");
ProcessBuilder builder = new ProcessBuilder("python3", "-m", "/Users/<user-name>/demo/JavaNotepad/src/main/java/com/mypython.py");
Process rt = builder.start();
int exitCode = rt.waitFor();
System.out.println("Process exited with : " + exitCode);
BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
BufferedReader err = new BufferedReader(new InputStreamReader(rt.getErrorStream()));
System.out.println("Python file output:");
String line;
BufferedReader reader;
if (exitCode != 0) {
reader = err;
} else {
reader = in;
}
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

Related

Call python script (part of Anaconda package) from Java

I am trying to trigger python code from a java scheduler. In standalone mode, we execute the python script via conda prompt, it takes arguments and returns value in JSON. How do I call this from a Java program and capture the output? Please help
You can use the Runtime to execute your command. Check the doc as well.
Here is an example how you can use it:
Process process = Runtime.getRuntime().exec("ls -al");
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String read;
while ((read = br.readLine()) != null) {
sb.append(read);
}
br.close();
System.out.println(sb.toString());
You should be using Java's ProcessBuilder to open a command line and execute your python script. Code should look like as follows (adapted to linux OS so change the command line if you're on Windows):
//create a command line to execute python script
ProcessBuilder builder = new ProcessBuilder("python", "scriptname.py", "param1", "param2", ...);
builder.redirectErrorStream(true);
Process p = builder.start();
//read output
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
//convert output to JSON
Gson gson = new Gson();
Type type = new TypeToken<YourType>(){}.getType();
YourType obj = gson.fromJson(line, type);

Failed to execute child process “'scriptName.sh” (No such file or directory)

String command= "/usr/bin/gnome-terminal.wrapper -e 'startDemonstrator.sh; bash'";
File workDir = new File("/home/malju/Desktop");
Process pr = Runtime.getRuntime().exec(command, null, workDir);
After I execute this line of code I get the error above. My script is located in the Desktop folder. I already tried adding ./startDemonstrator and full path. I always get the error above. What can be the reason be?
I am just trying to open a sh script after the terminal is opened.
First try like below:-
String command= "/home/malju/Desktop/startDemonstrator.sh";
Process pr = Runtime.getRuntime().exec(command);
p.waitFor();
If still not working try with below approach with ProcessBuilder.
String result = "";
String[] command = {"/home/malju/Desktop/startDemonstrator.sh"};
ProcessBuilder process = new ProcessBuilder(command);
Process p ;
try {
p = process.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
result = builder.toString();
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}

process builder doesn't print the console output using wmic

I was trying to print the version of chrome using process builder, this works fine with the command prompt when I executed wmic command directly in the windows command prompt, the same doesn't work with the process builder
String path= "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
String[] cmd = { "CMD", "/C", "wmic datafile where name="+path+" get Version /value" };
ProcessBuilder probuilder = new ProcessBuilder(cmd);
Thread.sleep(5000);
Process p = probuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String readline;
int i = 0;
while ((readline = reader.readLine()) != null) {
System.out.println(++i + " " + readline);
}
}
Expected
It has to print the following output: Version=55.0.2883.87
Suggest some solution
try with
String[] cmd = { "CMD", "/C", "wmic datafile where \"name='"+path+"'\" get Version /value" };
you need the path quoted like:
"name='C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'"
I think even you can execute directly the wmic without the cmd.
edit whole code snipped(double slashes are also needed in the wmic path):
Runtime rt = Runtime.getRuntime();
String path= "C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe";
Process p2=Runtime.getRuntime().exec("cmd /C wmic datafile where 'name=\""+path+"\"' get Version ");
BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p2.getErrorStream()));
String readline;
System.out.println("Output:\n");
while ((readline = reader.readLine()) != null) {
System.out.println(readline);
}
System.out.println("Errors:\n");
while ((readline = stdError.readLine()) != null) {
System.err.println(readline);
}

how to run basic command in linux using java?

I have a class file say, abc.class which got compiled from abc.java
While trying to execute this java program, I am not getting the output in my console.
I have executed this file in linux environment.
the file contains one of the line which draws importance :
Runtime rt = Runtime.getRuntime();
String a = "ls";
Process proc = null;
try {
proc = rt.exec(a);
}
Note : While executing the program, the prompt is not there and i think that might be the reason for 'ls' not getting executed through my program. I am not getting any error though.
I am concern that as soon as the file get execute I will get the list of file in the prompt.
Hope i make to clear you all guys about my issue.
Please can I have any input on this issue of mine. your valuable
Your command should be executed ,but your output is not printed as by default output will be not directed to your console , for getting output on your console, you just need to take input stream from your process and need to read it.
Runtime rt = Runtime.getRuntime();
String a = "ls";
Process proc = null;
try
{
proc = rt.exec(a);
proc.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line=" ";
while((line=reader.readLine())!=null)
{
output.append(line+"\n");
}
}
This works:
Runtime rt = Runtime.getRuntime();
String a = "/bin/ls";
Process proc = rt.exec(a);
proc.waitFor();
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader( is );
BufferedReader br = new BufferedReader( isr );
String line;
while( (line = br.readLine() ) != null ){
System.out.println( line );
}
br.close();
// to see errors:
System.out.println( "*** error output ***" );
InputStream isErr = proc.getErrorStream();
InputStreamReader isrErr = new InputStreamReader( isErr );
BufferedReader brErr = new BufferedReader( isrErr );
String line;
while( (line = brErr.readLine() ) != null ){
System.out.println( line );
}
brErr.close();

Writing the Output of an Operating System Command to the Console

I want to execute an operating system command in Java, and then print out it's returned value. Like this:
This is what I am trying...
String location_of_my_exe_and_some_parameters = "c:\\blabla.exe /hello -hi";
Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);
I tried putting a System.out.print() on the beginning of my Runtime... line, but it failed. Because, apparently, getRuntime() returns a Runtime object.
Now, the problem is, when I execute the "blabla.exe /hello -hi" command in command line, I got a result like: "You executed some command, hurray!". But, in Java, I got nothing.
I tried putting the return value into a Runtime object, to an Object object. However, they both failed. How can I accomplish this?
Problem Solved - this is my solution
Process process = new ProcessBuilder(location, args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Notice that Runtime.exec(...) returns a Process object. You can use this object to capture its input stream and retrieve whatever it prints to the standard output:
Process p = Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);
InputStream is = p.getInputStream();
// read process output from is
You can capture the output of a command using this:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
log.info(line);
}
//This will wait for the return code of the process
int exitVal = pr.waitFor();
UseProcessBuilder instead of Runtime.
Like:
Process process = new ProcessBuilder("c:\\blabla.exe","param1","param2").start();
Answer:
Process process = new ProcessBuilder("c:\\blabla.exe","/hello","-hi").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));

Categories