我如何使用 Jython 编写 Java 程序的脚本

How do I use Jython to script Java programs

我正在做一个项目,它将把可编程计算机引入 Minecraft,类似于 ComputerCraft,除了使用 Python 而不是 lua。

我知道 Jython,所以我认为检查我是否可以将它用于我的项目是合适的,但是找不到足够的信息(在他们的网站上和一些搜索)来确定。

我知道讨论使用 Java from within Jython 的主题,但这不是我希望我的项目工作的方式。那些使用过 Computercraft 的人都知道,您只有 Computercraft 为您提供的库,而上面链接的主题可以完全访问……一切。在我的用例中,一切都是不可能的。我也不想要 from pycomputers.api import Colors,我希望 'colors' api 像 colors.red.

一样使用

希望以上是可能的,在 Jython 中,如果不是,我很想知道另一个 Python 解释器(可以从 Java 使用),使我的项目。

根据docs if you want to embed the Jython into a java application then you have to invoke it with the PythonInterpreter class。从那里开始非常困难,请注意提供 filename 参数的重载是针对 主可执行文件 的名称(此信息通常可通过 sys 常规旧 CPython 中的模块)。

现在为了将 java 中的绑定公开到 python(比如控制 minecraft 世界),我们需要将 jar 文件添加到 sys.pathhere,如果您想从 java 中控制 sys.path 值,则使用

PythonInterpreter pi = new PythonInterpreter();
pi.getSystemState().path.append(new PyString("path/to/java/modules.jar"));

请注意,jar 文件中的包 不能 以相反的 url 方式组织。相反,遵循 instructions on package naming. Particularly make note of Naming Python Modules and Packages and if you follow the guidelines in Proper Python Naming 然后你会得到你想要的结果。

最后我们执行代码

String source = ...;
pi.execute(pi.compile(source));