使用PythonInterpreter执行python代码
pom.xml依赖
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>
java中执行python片段
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a='hello world'; ");
interpreter.exec("print a;");
原理解析
1//初始化Python编译器
PythonInterpreter interpreter = new PythonInterpreter();
protected PythonInterpreter(PyObject dict, PySystemState systemState, boolean useThreadLocalState) {
this.cflags = new CompilerFlags();
this.closed = false;
this.globals = (PyObject)(dict != null ? dict : Py.newStringMap());
this.systemState = systemState != null ? systemState : Py.getSystemState();//1.2
this.setSystemState();
this.useThreadLocalState = useThreadLocalState;
PyModule module = new PyModule("__main__", this.globals);
this.systemState.modules.__setitem__("__main__", module);
if (Options.Qnew) {
this.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
}
Py.importSiteIfSelected();
}
1.1//PySystemState.initialize();
public static synchronized void initialize...{
preProperties = PrePy.getSystemProperties();
postProperties = new Properties();
ClassLoader context = Thread.currentThread().getContextClassLoader();
ClassLoader sysStateLoader = PySystemState.class.getClassLoader();
doInitialize(preProperties, postProperties, argv, classLoader, adapter);
}
1.2//doInitialize
public static synchronized PySystemState doInitialize...{
if (initialized) {
return Py.defaultSystemState;
} else {
initialized = true;
Py.setAdapter(adapter);
boolean standalone = false;
String jarFileName = Py.getJarFileName();
if (jarFileName != null) {
standalone = isStandalone(jarFileName);
}
initRegistry(preProperties, postProperties, standalone, jarFileName);
initBuiltins(registry);
defaultPath = initPath(registry, standalone, jarFileName);
defaultArgv = initArgv(argv);
defaultExecutable = initExecutable(registry);
initPackages(registry);
initConsole(registry);
Py.defaultSystemState = new PySystemState();
Py.setSystemState(Py.defaultSystemState);
if (classLoader != null) {
Py.defaultSystemState.setClassLoader(classLoader);
}
Py.initClassExceptions(getDefaultBuiltins());
new PySyntaxError("", 1, 1, "", "");
Py.defaultSystemState.__setattr__("_jy_console", Py.java2py(Py.getConsole()));
return Py.defaultSystemState;
}
}
2、//执行Python语法
interpreter.exec("a='hello world'; ");
public void exec(String s) {
this.setSystemState();
Py.exec(Py.compile_flags(s, "<string>", CompileMode.exec, this.cflags), this.getLocals(), (PyObject)null);
Py.flushLine();
}
2.1、//compile_flags
mod node = ParserFacade.parse(data, kind, filename, cflags);
private static mod parse...{
...
CharStream cs = new NoCloseReaderStream(reader);
BaseParser parser = new BaseParser(cs, filename, cflags.encoding);
return kind.dispatch(parser);
}
//mod,放入了解析后的Python信息
public abstract class mod extends PythonTree {
public static final PyType TYPE;
private static final PyString[] fields;
private static final PyString[] attributes;
...
}
2.2、//编译
public static PyCode compile_flags(mod node, String name, String filename, boolean linenumbers, boolean printResults, CompilerFlags cflags) {
return CompilerFacade.compile(node, name, filename, linenumbers, printResults, cflags);
}
PythonCompiler compiler = new LegacyCompiler();
public class LegacyCompiler implements PythonCompiler {
...
public static PyCode compile(mod node, String name, String filename, boolean linenumbers, boolean printResults, CompilerFlags cflags) {
try {
PythonCodeBundle bundle = compiler.compile(node, name, filename, linenumbers, printResults, cflags);
return bundle.loadCode();
} catch (Throwable var7) {
throw ParserFacade.fixParseError((ExpectedEncodingBufferedReader)null, var7, filename);
}
}
public PyCode loadCode() throws Exception {
return BytecodeLoader.makeCode(this.name, this.ostream().toByteArray(), this.filename);
}
...
}
public static PyCode makeCode(String name, byte[] data, String filename) {
try {
Class<?> c = makeClass(name, data);
Constructor<?> cons = c.getConstructor(String.class);
Object instance = cons.newInstance(filename);
PyCode result = ((PyRunnable)instance).getMain();
return result;
} catch (Exception var7) {
throw Py.JavaError(var7);
}
}
java中执行Python文件
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("src\\test\\java\\com\\jsq\\sayHello.py");
原理解析
//和片段差不多,只是从文件中读取出
java中执行Python文件中的方法(有参数输入)
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("src\\test\\java\\com\\jsq\\sayHello2.py");
PyFunction pyFunction = interpreter.get("func", PyFunction.class);
String b = "python";
PyObject pyObject = pyFunction.__call__(new PyString(b));
System.out.println(pyObject);
java中执行Python文件中的方法(无参数输入)
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("src\\test\\java\\com\\jsq\\sayHello3.py");
PyFunction pyFunction = interpreter.get("func", PyFunction.class);
PyObject pyObject = pyFunction.__call__();
System.out.println(pyObject);