如何使用来自 Java 类的参数调用 Python 脚本 [英] How to call a Python script with arguments from Java class

查看:74
本文介绍了如何使用来自 Java 类的参数调用 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Python 3.4.

我有一个 Python 脚本 myscript.py :

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()

我需要从java类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
}

并且我通过创建 PythonJava

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

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

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?

推荐答案

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

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

通过传递参数和结果

如何从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);
}

只需确保将变量名称从 str 更改为其他名称,如 cdarke 所指出的

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

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

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)

这篇关于如何使用来自 Java 类的参数调用 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆