使用 graal python 从 java 获取外部环境参数
Getting outer environment arguments from java using graal python
我 运行 Java 在 GraalVM 中使用它来执行 python。
Context context = Context.create();
Value v = context.getPolyglotBindings();
v.putMember("arguments", arguments);
final Value result = context.eval("python", contentsOfMyScript);
System.out.println(result);
return jsResult;
问题是 python 代码应该如何接收 "arguments"。 graal 文档指出,如果这是 JS,我会这样做:
const args = Interop.import('arguments');
确实如此。 python 等价物可能是:
import Interop
args = Interop.import('arguments')
def main():
return args
main()
这失败了,因为没有这样的模块。我找不到关于如何从外部语言层获取这些参数的文档,只有关于 pythongraal 以及如何使用 python 传递给其他东西的文档。
可在 http://www.graalvm.org/docs/reference-manual/polyglot/.
获取有关此内容的一些信息
您要查找的模块名为 polyglot
。
该操作在Python中称为import_value
,因为import
是关键字。
您可以使用以下方法从多语言绑定中导入:
import polyglot
value = polyglot.import_value('name')
顺便说一句,它在 JavaScript 中几乎相同:Polyglot.import(name)
(出于兼容性原因,Interop
仍然有效)
一个完整的例子:
import org.graalvm.polyglot.*;
class Test {
public static void main(String[] args) {
Context context = Context.newBuilder().allowIO(true).build();
Value v = context.getPolyglotBindings();
v.putMember("arguments", 123);
String script = "import polyglot\n" +
"polyglot.import_value('arguments')";
Value array = context.eval("python", "[1,2,42,4]");
Value result = context.eval("python", script);
System.out.println(result);
}
}
我 运行 Java 在 GraalVM 中使用它来执行 python。
Context context = Context.create();
Value v = context.getPolyglotBindings();
v.putMember("arguments", arguments);
final Value result = context.eval("python", contentsOfMyScript);
System.out.println(result);
return jsResult;
问题是 python 代码应该如何接收 "arguments"。 graal 文档指出,如果这是 JS,我会这样做:
const args = Interop.import('arguments');
确实如此。 python 等价物可能是:
import Interop
args = Interop.import('arguments')
def main():
return args
main()
这失败了,因为没有这样的模块。我找不到关于如何从外部语言层获取这些参数的文档,只有关于 pythongraal 以及如何使用 python 传递给其他东西的文档。
可在 http://www.graalvm.org/docs/reference-manual/polyglot/.
获取有关此内容的一些信息您要查找的模块名为 polyglot
。
该操作在Python中称为import_value
,因为import
是关键字。
您可以使用以下方法从多语言绑定中导入:
import polyglot
value = polyglot.import_value('name')
顺便说一句,它在 JavaScript 中几乎相同:Polyglot.import(name)
(出于兼容性原因,Interop
仍然有效)
一个完整的例子:
import org.graalvm.polyglot.*;
class Test {
public static void main(String[] args) {
Context context = Context.newBuilder().allowIO(true).build();
Value v = context.getPolyglotBindings();
v.putMember("arguments", 123);
String script = "import polyglot\n" +
"polyglot.import_value('arguments')";
Value array = context.eval("python", "[1,2,42,4]");
Value result = context.eval("python", script);
System.out.println(result);
}
}