Ayush Sharma
Ayush Sharma

Reputation: 77

Error in calling Python file from Java code and getting the result

I have to use results from python executed code in Java. I have downloaded jython jars. I fetch below part of code from Internet. But the errorreflected is python: can't open file 'IBM.py': [Errno 2] No such file or directory. Where does it searches for the file ? My file is created in pycharm projects.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CallPython {

    /**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
     String s = null;
    // TODO Auto-generated method stub
    Process p = Runtime.getRuntime().exec("python IBM.py");
    System.out.println("ayush");
     BufferedReader stdInput = new BufferedReader(new 
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(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);
        }
}}

Upvotes: 0

Views: 345

Answers (1)

Rehan Javed
Rehan Javed

Reputation: 436

Your IBM.py file is in the pycharm projects folder, and java code is finding the IBM.py file in the project folder where the java code is, so that's why it is giving error.

If you created a Java Project in any IDE, then copy the file IBM.py and paste it in the java project folder and then run this code, it will execute properly. :)

If you just have a CallPython.java file and you don't created it in the Java Project on any IDE, then paste the IBM.py in the same folder where CallPython.java exists.

Upvotes: 1

Related Questions