6

I am using Python 3.4.

I have a Python script myscript.py :

import sys
def returnvalue(str) :
    if str == "hi" :
        return "yes"
    else :
        return "no"
print("calling python function with parameters:")
print(sys.argv[1])
str = sys.argv[1]
res = returnvalue(str)
target = open("file.txt", 'w')
target.write(res)
target.close()

I need to call this python script from the java class PythonJava.java

public class PythonJava 
{
    String arg1;
    public void setArg1(String arg1) {
        this.arg1 = arg1;
    }
public void runPython() 
    { //need to call myscript.py and also pass arg1 as its arguments.
      //and also myscript.py path is in C:\Demo\myscript.py
}

and I am calling runPython() from another Java class by creating an object of PythonJava

obj.setArg1("hi");
...
obj.runPython();

I have tried many ways but none of them are properly working. I used Jython and also ProcessBuilder but the script was not write into file.txt. Can you suggest a way to properly implement this?

Sushin K.Kumar
  • 149
  • 1
  • 3
  • 12
  • 2
    Bad idea to call a variable (in Python) `str` because it will mask the system string class of the same name. – cdarke Jul 29 '16 at 11:09

3 Answers3

6

Have you looked at these? They suggest different ways of doing this:

Call Python code from Java by passing parameters and results

How to call a python method from a java class?

In short one solution could be:

public void runPython() 
{ //need to call myscript.py and also pass arg1 as its arguments.
  //and also myscript.py path is in C:\Demo\myscript.py

    String[] cmd = {
      "python",
      "C:/Demo/myscript.py",
      this.arg1,
    };
    Runtime.getRuntime().exec(cmd);
}

edit: just make sure you change the variable name from str to something else, as noted by cdarke

Your python code (change str to something else, e.g. arg and specify a path for file):

def returnvalue(arg) :
    if arg == "hi" :
        return "yes"
    return "no"
print("calling python function with parameters:")
print(sys.argv[1])
arg = sys.argv[1]
res = returnvalue(arg)
print(res)
with open("C:/path/to/where/you/want/file.txt", 'w') as target:  # specify path or else it will be created where you run your java code
    target.write(res)
Community
  • 1
  • 1
mkaran
  • 2,528
  • 20
  • 23
  • i have changed the variable name and when i run the program i am getting the following error : java.io.IOException: Cannot run program "python C:/Demo/myscript.py": CreateProcess error=2, The system cannot find the file specified Can you help me with this? – Sushin K.Kumar Aug 03 '16 at 07:30
  • is C:/Demo/myscript.py the right path? if yes try `C:\\Demo\\myscript.py` even though forward slashes should not be an issue. I'll check it locally in a minute. – mkaran Aug 03 '16 at 07:37
  • Please check the edited answer, each command/ argument needs to be separate, my bad! I tried it and it works fine. – mkaran Aug 03 '16 at 08:01
  • same error if i am using `C:\\Demo\\myscript.py` and also the file exists in that path. Please find the error below `java.io.IOException: Cannot run program "python C:\Demo\myscript.py": CreateProcess error=2, The system cannot find the file specified` – Sushin K.Kumar Aug 03 '16 at 10:03
  • Check the updated answer :) `String[] cmd = { "python", // separate "C:/Demo/myscript.py", // separate this.arg1, };` – mkaran Aug 03 '16 at 10:10
  • no errors but the file is not running.So, I am not getting the output. – Sushin K.Kumar Aug 03 '16 at 11:11
  • the main problem is the file is not getting created while running from the java but it is getting created if I run it from cmd and that creation of file is the main issues that i am facing. – Sushin K.Kumar Aug 03 '16 at 11:22
  • Since you do not provide an absolute path for the file.txt, it is going to be created where your java program runs. If you specify a path `with open("C:\\file.txt", 'w') as target: target.write(res)` it will create it where you need to. Also, change your python code to the following: `def returnvalue(arg) : if str == "hi" : return "yes" return "no" print("calling python function with parameters:") print(sys.argv[1]) arg = sys.argv[1] res = returnvalue(arg)` – mkaran Aug 03 '16 at 11:37
  • I updated the answer because it is not easily visible in the comments. Let me know! – mkaran Aug 03 '16 at 11:43
  • can array data formats be passed like this from a java program to a certain python script ? – Arnav Das Aug 15 '20 at 17:02
3

Below is the python method with three sample arguments which can later be called through java.

#Sample python method with arguments
import sys
 
def getDataFromJava(arg1,arg2,arg3):
       
    arg1_val="Hi"+arg1
    arg2_val=arg2
    arg3_val=arg3
   
    print(arg1_val)
    print(arg2_val)
    print(arg3_val)
    
    return arg1_val,arg2_val,arg3_val
    
    
    
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]

getDataFromJava(arg1,arg2,arg3)

Below is the java code to invoke the above method with three sample arguments and also read console output of python script in java through InputStreamReader.

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

public class Test1 {
    
    public static String s;
    
    public static void main(String[] args) throws IOException {
        
        
        
        String pathPython = "Path_to_the_file\\test.py";
        String [] cmd = new String[5];
        cmd[0] = "python";
        cmd[1] = pathPython;
        cmd[2] = "arg1";
        cmd[3] = "arg2";
        cmd[4] = "arg3";
        Runtime r = Runtime.getRuntime();
        
        Process p = r.exec(cmd);
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((s=in.readLine()) != null){
            System.out.println(s);
            }
        
        
    }

}
Chandan
  • 704
  • 7
  • 20
2

calling python from java with Argument and print python output in java console can be done with below simple method:

String pathPython = "pathtopython\\script.py";
String [] cmd = new String[3];
cmd[0] = "python";
cmd[1] = pathPython;
cmd[2] = arg1;
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = in.readLine()) != null){
    System.out.println(s);
    }