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?

1
  • 2
    Bad idea to call a variable (in Python) str because it will mask the system string class of the same name. Commented Jul 29, 2016 at 11:09

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

10 Comments

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?
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.
Please check the edited answer, each command/ argument needs to be separate, my bad! I tried it and it works fine.
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
Check the updated answer :) String[] cmd = { "python", // separate "C:/Demo/myscript.py", // separate this.arg1, };
|
4

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);
    }

Comments

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);
            }
        
        
    }

}

Comments

Your Answer

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.