Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
added 1086 characters in body
Source Link
Bram
  • 127
  • 1
  • 2
  • 7

Just tested andYou 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 works:

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

Just tested and this works.

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

Source Link
Bram
  • 127
  • 1
  • 2
  • 7

Just tested and this works.

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")