Java用参数执行嵌入式Python

2024-10-04 11:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Python代码

#!/usr/bin/python

import sys

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

Java代码

^{pr2}$

电流输出

Number of arguments: 1 arguments.

Argument List: ['']

如何在代码中向该脚本传递参数?在


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

现在,如果您想执行嵌入在java中的a.py,那么如何传递参数hellow worldd?在


Tags: of代码py脚本number参数sysjava
1条回答
网友
1楼 · 发布于 2024-10-04 11:28:31

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

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

相关问题 更多 >