Java ProcessBuilder not able to run Python script in Java - java

null from bfr.readLine()
However, there is no problem if I run the python file directly on terminal by firing:
python C:/Machine_Learning/Text_Analysis/Ontology_based.py
The last line in my Python script is >> print(data)
The result of the following code is:
Running Python starts:
First Line: null
Picked up _JAVA_OPTIONS: -Xmx512M
package text_clustering;
import java.io.*;
public class Similarity {
/**
*
* #param args
*
*/
public static void main(String[] args){
try{
String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
//String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
ProcessBuilder pb = new ProcessBuilder("python", pythonPath);
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
}catch(Exception e){System.out.println(e);}
}
}

Usually when executing commands using ProcessBuilder, PATH variable is not taken into consideration. Your python C:/Machine_Learning/Text_Analysis/Ontology_based.py is directly working in your CMD shell because it can locate the python executable using the PATH variable. Please provide the absolute path to python command in your Java code. In below code replace <Absolute Path to Python> with the path to python command and its libraries. Usually it will something like C:\Python27\python in Windows by default
package text_clustering;
import java.io.*;
public class Similarity {
/**
*
* #param args
*
*/
public static void main(String[] args){
try{
String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
//String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
ProcessBuilder pb = new ProcessBuilder(Arrays.asList("<Absolute Path to Python>/python", pythonPath));
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
int exitCode = p.waitFor();
System.out.println("Exit Code : "+exitCode);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
}catch(Exception e){System.out.println(e);}
}
}

Reading from stdin returns null when the script is killed/dies. Do a Process#waitFor and see what the exitValue is. If it isn't 0 then it's highly probable that your script is dying.
I'd try making it work with a dumb script that only writes a value. Make sure that you print all error information from python.

try {
Process p = Runtime.getRuntime().exec(
"python D://input.py ");
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
p.waitFor();
} catch (Exception e) {
}

try {
ProcessBuilder pb = new ProcessBuilder("C:/Python27/python", "D://searchTestJava//input.py");
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null) {
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
} catch (Exception e) {
System.out.println(e);
}

I tried this one. This script runs a python file with the argument in Java. It also logs about which line, your program is executing. Hope this Helps.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class Test {
public static void main(String... args) throws IOException {
ProcessBuilder pb =
new ProcessBuilder("python","samples/test/table_cv.py","1.pdf");
pb.redirectErrorStream(true);
Process proc = pb.start();
Reader reader = new InputStreamReader(proc.getInputStream());
BufferedReader bf = new BufferedReader(reader);
String s;
while ((s = bf.readLine()) != null) {
System.out.println(s);
}
}
}

Related

How to execute a python file with some arguments in java

String command:
python FileName.py <ServerName> userName pswd<b>
Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line + "\n");
}
Code is neither terminating nor giving the actual results. ...
This May Be Helpful !
You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable.
#!/usr/bin/python
import sys
print 'Number of Arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.arv)
print('This is Python Code')
print('Executing Python')
print('From Java')
if you save the above file as script_python and then set the execution permissions using
chmod 777 script_python
Then you can call this script from Java Runtime.exec() like below
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ScriptPython {
Process mProcess;
public void runScript(){
Process process;
try{
process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"});
mProcess = process;
}catch(Exception e) {
System.out.println("Exception Raised" + e.toString());
}
InputStream stdout = mProcess.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8));
String line;
try{
while((line = reader.readLine()) != null){
System.out.println("stdout: "+ line);
}
}catch(IOException e){
System.out.println("Exception in reading output"+ e.toString());
}
}
}
class Solution {
public static void main(String[] args){
ScriptPython scriptPython = new ScriptPython();
scriptPython.runScript();
}
}

Get the windows running process description In java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
String line;
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); // <-- Parse data here.
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}
}
The output of this program shows the process list from windows task manager .....but i also need the Description of the running process ??? How do i get that???
tasklist.exe takes an optional parameter /v for verbose. This outputs the description
Example
taskmgr.exe 5648 Console 1 18,280 K Running 0:00:00 Windows Task Manager
You'll need to update your call to exec() to pass the "/v". Full example including parsing.
public static void main(String[] args) throws IOException {
String taskListExe = System.getenv("windir") + "\\system32\\" + "tasklist.exe";
Process p = Runtime.getRuntime().exec(new String[] { taskListExe, "/v" });
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
Pattern pattern = Pattern.compile("(.*?)\\s+(\\d+).*(\\d+:\\d+:\\d+)\\s+(.*?)");
String line;
while ((line = input.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
System.out.println(String.format("%s, pid = %s, description = %s", matcher.group(1), matcher.group(2),
matcher.group(4)));
}
}
input.close();
}
Output
firefox.exe, pid = 3152, description = cmd - Get the windows running process description In java - Stack Overfl
taskmgr.exe, pid = 5648, description = Windows Task Manager
System Idle Process, pid = 0, description = N/A

Executing "$ aarch64-linux-objdump -d a.out' in terminal throug java

I have made a cross compiler using gcc. Now I want the compile and run commands to be executed in a terminal through java program. Here is the code that I am using for this :
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Runterminal {
public static void main(String[] args) {
Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 test.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{
proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));
String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}
procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}
}
}
Now my first command is executing since I could see the a.out file being generated. The second command should dump the memory contents of file and it should print in in terminal but I am not seeing any output. Can anyone tell where I am going wrong?

running terminal command using java to clear terminal history

I want to get terminal history
So I did this
Runtime rt = Runtime.getRuntime();
pr = rt.exec("/bin/bash -c \"history -c\"");
pr.waitFor();
rt.exec("/usr/bin/xterm");
but there is problem with pr = rt.exec("/bin/bash -c \"history -c\""); , it's not clearing the previous history nither of xterm nor my normal terminal.
Also when I try to print the history it returns nothing (no errors)
p = Runtime.getRuntime().exec("/bin/bash -c \"history\"");
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("printing");
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
I also tried
String[] commands = new String[]{"/bin/sh","-c", "history -c" ,"xterm"};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
} catch (IOException e1) {
e1.printStackTrace();
}
still not clearing history.
You can remove the history file yourself by getting the $HISTFILE environment variable. This will always get the correct history file for different shells. I believe the issue you're having is that the you may be using a different shell or have changed your history file location.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RemoveShellHistory {
public static void main(String[] args) {
RemoveShellHistory obj = new RemoveShellHistory();
final String shellPath = System.getenv("SHELL");
String shell = shellPath.substring(shellPath.lastIndexOf("/")+1, shellPath.length());
final String home = System.getenv("HOME");
String command = "rm -v " + home + "/." + shell + "_history";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
Assuming that your java app runs by the same user possessing the .bash_history file:
To delete.
new File(System.getProperty("user.home"), ".bash_history").delete();
To clean (Handle the checked exception at your will).
FileWriter writer = new FileWriter(
new File(System.getProperty("user.home"), ".bash_history"));
writer.write("");
writer.close();

executing a java program in another java program using Runtime.exec() function

The following code snippet i had given is using exec function and executes hello program (simple "hello world" printing java program). But as soon as i execute the main program, print statement of instream.readline() simply returns NULL. Please try to sort out the problem. Hope the explanation is clear.
CODE:
Process process2=null;
BufferedReader inStream=null;
try
{
process2 = Runtime.getRuntime().exec("java hello");
}
catch(IOException e1)
{
System.err.println("Error on exec method");
e1.printStackTrace();
}
try
{
inStream = new BufferedReader(new InputStreamReader(process2.getInputStream() ));
System.out.println(inStream.readLine());
}
catch(IOException e1)
{
System.err.println("Error on inStream.readLine()");
e1.printStackTrace();
}
First of all your hello.java should be already compiled n the class file should present in the current directory where the program is located.
And for getting errors, you can get error stream from process class's object.
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String s="";
while ((s = stdError.readLine()) != null)
System.out.println(s);
Working with Eclipse/java7/windows
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProcessDemo {
public static void main(String[] args) throws Exception {
final String dir = System.getProperty("user.dir");
System.out.println("current dir = " + dir);
Runtime run = Runtime.getRuntime();
Process pr=run.exec("javac -d "+ dir +"\\src "+ dir+"\\src\\HelloDemo.java");
pr.waitFor();
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
String s;
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
System.out.println(s);
//read output
while ((line=buf.readLine()) != null)
System.out.println(line);
pr.destroy();
Runtime run1 = Runtime.getRuntime();
Process pr1=run1.exec("java -cp "+dir+"\\src HelloDemo");
BufferedReader stdError1 = new BufferedReader(new InputStreamReader(pr1.getErrorStream()));
BufferedReader buf1 = new BufferedReader(new InputStreamReader(pr1.getInputStream()));
//interpretting file n executing it line by line :D :P
pr1.waitFor();
String temp;
// read any errors from the attempted command
System.out.println("\n\nHere is the standard error of the command (if any):\n");
while ((temp = stdError1.readLine()) != null)
System.out.println(temp);
//read output
System.out.println(buf1.readLine());
while ((temp=buf1.readLine()) != null)
System.out.println(temp);
}
}

Categories

Resources