How to call a Python script with arguments from Java class

北城以北 提交于 2019-12-13 14:33:45

问题


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:


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)


来源:https://stackoverflow.com/questions/38657109/how-to-call-a-python-script-with-arguments-from-java-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!