jamierocks
jamierocks

Reputation: 695

How do I use Jython to script Java programs

I am working on a project, which will introduce programmable computers to Minecraft, similar to ComputerCraft, except using Python as opposed to lua.

I am aware of Jython, so thought it would be suitable to check if I could use that for my project, however couldn't find enough information (on their website and with a few searches) to be certain.

I am aware of the topic discussing using Java from within Jython, however this is not how I want my project to work. Those that have used Computercraft, know that you have only the libraries that Computercraft provides you, whereas the topic linked above has full access to.. well everything. In my use case, everything isn't possible. I also don't want from pycomputers.api import Colors, I want the 'colors' api to be used like colors.red.

Hopefully the above is possible, within Jython, if not I would love to know another Python interpreter (that can be used from Java), to make my project with.

Upvotes: 0

Views: 364

Answers (1)

randomusername
randomusername

Reputation: 8097

According to the docs if you want to embed the Jython into a java application then you have to invoke it with the PythonInterpreter class. It's pretty strait forward from there, just note that the overloads that provide a filename argument are for the name of the main executable file (this information is normally available through the sys module in regular old CPython).

Now in order to expose bindings in java to python (say to control the minecraft world), we need to add the jar files to sys.path as is described here, and if you want to control the sys.path value from within java then use

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

Note that the packages inside the jar files cannot be organized in the reverse url style. Instead, follow the instructions on package naming. Particularly make note of Naming Python Modules and Packages and if you follow the guidelines in Proper Python Naming then you will get the results you desire.

Finally we execute the code with

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

Upvotes: 2

Related Questions