4

I want to call a python script from Java. My python version is 2.5 and Java is 6.

My current code:

try{
 Process p= Runtime.getRuntime().exec("path/dirs/file.py");
 p.waitFor();
 } catch (InterruptedException ex){
 System.out.println(ex.getMessage());}
 }

The error I receive is:

Java.IO.IOException: Cannot run program filename: CreateProcess error = 193, %1 is not a valid Win32 application

Razib
11.2k12 gold badges59 silver badges86 bronze badges
asked Jul 28, 2015 at 10:49
1
  • Windoze doesn't understand #!... in script files. There's no way it would work on all Windoze systems, you'd have to explicitly invoke Python executable and put script as argument to it. Commented Apr 5, 2017 at 18:26

4 Answers 4

3

Try to use PrecessBuilder -

try{
 String prg = "import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n";
 BufferedWriter out = new BufferedWriter(new FileWriter("test1.py"));
 out.write(prg);
 out.close();
 int number1 = 10;
 int number2 = 32;
 ProcessBuilder pb = new ProcessBuilder("python","test1.py",""+number1,""+number2);
 Process p = pb.start();
 BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
 int ret = new Integer(in.readLine()).intValue();
 System.out.println("value is : "+ret);
}catch(Exception e){System.out.println(e);}

See here from more detail.

answered Jul 28, 2015 at 10:55
Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way to integrate a Java application with Python is to use Jython.

I have used this successfully in the past to build scriptable java applications before we had access to Nashorn and it's ilk.

answered Jul 28, 2015 at 11:02

Comments

1

try this, This works for me

test_python.py

def addition(a,b):
 c=a+b
 return(c)

interpreterPython.java

package com.pythonconnect;
import org.python.util.PythonInterpreter;
public class interpreterPython {
 public static void main(String[] args) {
 System.setProperty("python.cachedir.skip", "true");
 PythonInterpreter interpreter = new PythonInterpreter();
 interpreter.execfile("test_python.py");
 interpreter.exec("print(addition(7,8))");
 }
}
answered Jun 8, 2017 at 17:33

Comments

0

You can run only a windows executable like a EXE or BAT file using the Runtime.exec function. You need to find a way to instantiate the Python interpreter and then give the file name using a .BAT File.

answered Jul 28, 2015 at 10:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.