Marjoram Marjoram - 6 months ago 22
Java Question

Trying to call python file from java

I am trying to run a python file from java.

I have tried

ProcessBuilder pb = new ProcessBuilder("python", "pythonfile.py");
Process p = pb.start();


but that didn't work. No errors were given, but the file does not run.

I also tried

Runtime.getRuntime().exec("python pythonfile.py");


And got the same thing. No errors, but the file does not run.

Although it shouldn't matter, this is the .py file I am trying to run:

import winsound
Freq = 1500 # Set Frequency To 1500 Hertz
Dur = 500 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)
print "this file ran!!!"


Nothing is printed and no noise is heard. For various reasons, I am unable to use Jython, so please focus on this problem. Thanks!

Solution: As pointed out by Rahul Jha, my problem was that I had my python file in the incorrect folder. Thank you!!

Answer

Use BufferedReader to show your output.

import java.io.*;
class Test {
public static void main(String args[]) {
    try {
        Process p = Runtime.getRuntime().exec(
                "python Test.py ");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        System.out.println(in.readLine());
    } catch (Exception e) {
    }
}

}

and my python file is Test.py

print "Hello World Python.";
Comments