Java使用参数执行嵌入式Python [英] Java execute Embedded Python with parameters

查看:119
本文介绍了Java使用参数执行嵌入式Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中执行嵌入式python.

I want to execute Embedded python in Java.

Python代码

#!/usr/bin/python

import sys

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

Java代码

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

当前输出

参数数量:1个参数.

Number of arguments: 1 arguments.

参数列表:['']

如何在代码中将参数传递给此脚本?

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

您通过$python a.py hellow worldd在终端中运行脚本.

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

现在是否要执行嵌入在Java中的a.py,如何传递参数hellow worldd?

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

推荐答案

将参数解析为脚本?我不知道那是什么意思.您是要传递一个名为argv的Java对象,还是要用另一个字符串替换脚本中的字符串? 通常,我们谈论的是将实例传递给解释器/脚本引擎而不是脚本,脚本只是包含代码的txt文件,您可以像这样传递Java对象.

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

这篇关于Java使用参数执行嵌入式Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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