如何使用来自 Java 类的参数调用 Python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38657109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:37:57  来源:igfitidea点击:

How to call a Python script with arguments from Java class

javapythonpython-3.4

提问by Sushin K.Kumar

I am using Python 3.4.

我正在使用Python 3.4

I have a Python script myscript.py:

我有一个 Python 脚本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

我需要从 java 类调用这个 python 脚本 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

runPython()通过创建一个对象从另一个 Java 类调用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?

我尝试了很多方法,但没有一个能正常工作。我使用了 Jython 和 ProcessBuilder,但脚本没有写入 file.txt。你能提出一种正确实施的方法吗?

采纳答案by mkaran

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

你看过这些吗?他们提出了不同的方法来做到这一点:

Call Python code from Java by passing parameters and results

通过传递参数和结果从 Java 调用 Python 代码

How to call a python method from a java class?

如何从java类调用python方法?

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

编辑:只需确保将变量名称从 str 更改为其他名称,如 cdarke 所述

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

您的 Python 代码(将 str 更改为其他内容,例如 arg 并指定文件路径):

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)