Fro*_*its 5 python java graalvm
我在GraalVM中运行Java来使用它来执行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;
Run Code Online (Sandbox Code Playgroud)
问题是python代码应该如何接收"参数".graal文档说明如果这是JS,我会做这样的事情:
const args = Interop.import('arguments');
Run Code Online (Sandbox Code Playgroud)
确实,这很有效.python等价物可能是:
import Interop
args = Interop.import('arguments')
def main():
return args
main()
Run Code Online (Sandbox Code Playgroud)
这失败了,因为没有这样的模块.我找不到如何从外部语言层获取这些参数的文档,只有pythongraal上的文档以及如何使用python传递给其他东西.
小智 6
有关这方面的一些信息,请访问http://www.graalvm.org/docs/reference-manual/polyglot/.
您正在寻找的模块被调用polyglot.该操作import_value在Python中调用,因为它import是一个关键字.
您可以使用以下方法从多语言绑定中导入:
import polyglot
value = polyglot.import_value('name')
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这是几乎相同的在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);
}
}
Run Code Online (Sandbox Code Playgroud)