Java execute Embedded Python with parameters

让人想犯罪 __ 提交于 2019-12-24 15:33:12

问题


I want to execute Embedded python in Java.

Python code

#!/usr/bin/python

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

Java Code

    StringWriter writer = new StringWriter(); // ouput will be stored here
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptContext context = new SimpleScriptContext();

    context.setWriter(writer); // configures output redirection
    ScriptEngine engine = manager.getEngineByName("python");

    engine.eval(new InputStreamReader(Main.class.getResourceAsStream("/py/a.py")), context);
    System.out.println(writer.toString());

current output

Number of arguments: 1 arguments.

Argument List: ['']

How can I pass parameters to this script in my code?


You run the script in terminal by $python a.py hellow worldd.

now if you want to execute a.py embedded in java, how you can pass the arguments hellow worldd?


回答1:


Parsing parameters to a script? I'm not sure what you mean by that. Do you mean pass a java object called argv, or do you mean replace a string in your script with another? Typically we talk about passing instances to the interpretor/script engine not the script, the script is just a txt file containing code, you can pass in java objects like this.

public class ExampleEmbeddingJython
{

    public static class Arg {
        int a = 3;

        public Arg(int a)
        {
            this.a = a;
        }

        public String toString()
        {
            return "a = " + a;
        }

        public int getA()
        {
            return a;
        }
    }

    public static void main(String[] args) throws PyException
    {
        PythonInterpreter interp = new PythonInterpreter();
        interp.set("arg", new Arg(42));
        interp.exec("print arg");
        interp.exec("x = arg.getA()+2");
        PyObject x = interp.get("x");
        System.out.println("x = " + x);
        System.out.println("Goodbye, cruel world");
    }
}


来源:https://stackoverflow.com/questions/31228021/java-execute-embedded-python-with-parameters

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