用Java调用Python? [英] Calling Python in Java?

查看:91
本文介绍了用Java调用Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用jython从java代码调用python函数,还是仅用于从python调用java代码?

I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python?

推荐答案

Jython:Java平台的Python - http://www.jython.org/index .html

Jython: Python for the Java Platform - http://www.jython.org/index.html

您可以使用Jython从Java代码轻松调用python函数。只要您的python代码本身在jython下运行,即不使用一些不受支持的c扩展名。

You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.

如果这对您有用,那就是当然,你可以得到最简单的解决方案。否则,您可以从新的Java6解释器支持中使用 org.python.util.PythonInterpreter

If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

一个简单的例子来自我的头脑 - 但应该工作我希望:(没有为简洁而做错误检查)

A simple example from the top of my head - but should work I hope: (no error checking done for brevity)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

这篇关于用Java调用Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆