0

I have a python file that outputs 'hello world'.

print 'hello world'

I want to trigger this python script from my java class.

public String runPythonFile(String pathname) throws IOException{
    return Runtime.getRuntime().exec(pathname).toString();
}

Problem is my output is simply

java.io.BufferedOutputStream@776ec8df

instead of

hello world

any idea if i should be triggering it from java or outputting it from python differently?

Fearghal
  • 10,569
  • 17
  • 55
  • 97

1 Answers1

0

You misunderstand a few things here.

 return Runtime.getRuntime().exec(pathname).toString();

Look at the following piece of code exec(pathname) You pass the pathname argument to the exec method. However to execute a python file you should pass the pathname of the python script to the python executable. So the command would look like this:

python path/to/file

Note: If the path to the file contains spaces, make sure to wrap it in "double qoutes"

The second thing that you misunderstand is the following: exec(...).toString(). The exec method returns a Process, so calling the toString(), won't give you the output of the python script.

In order to get that output, we need to read the input stream of the executed process. You can get this input stream by calling Process#getInputStream()

Example

public static void main(String[] args) throws IOException, InterruptedException {                                            
      Process p = Runtime.getRuntime().exec(new String[] {"/bin/bash", "-c", "python /home/bram/Desktop/hello_world.py" });    
      p.waitFor();                                                                                                             

      try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {                                
          String line;                                                                                                         
          while ((line = br.readLine()) != null)  {                                                                            
             System.out.println(line);                                                                                        
          }                                                                                                                    
      }                                                                                                                      
}

p.waitFor() waits for the process to be completed.

After the process has terminated, we get the InputStream and pass it along to a BufferedReader for easy reading.

Note that I am using linux. If you are using windows, you could simply do Runtime.getRuntime().exec("pyton path/to/pythonfile")

Bram
  • 127
  • 1
  • 2
  • 7