Jython,仅使用 Java 中的 Python 方法?

2024-04-17

阅读和使用时本文 http://www.rexx.com/~dkuhlman/jython_course_03.html#example-the-jython-classes它假设我们有一个完整的对象定义,包含类和从 python 到 java 的映射(代理)对象。

是否可以仅从 python 中的一段代码导入方法(不在类内部定义,而是使用内部 python 类),而不将其包装在类定义中(不使用上述工厂范例)。

我想做一些from myPyFile import myMethod来自java,然后使用myMethod,直接来自java(也许作为静态方法?)?但如果这是可能的,我没有找到任何关于如何做到这一点的线索(文章中描述的接口内容可能仍然需要告诉 Java 如何使用 myMethod ?)

此致。

EDIT: 我现在正在处理Jython 2.5.2,所以它可能与版本相关并且将来会更容易?

EDIT :下面回复丹尼尔:

这是一个示例代码,用于重现我收到的错误,并从您有用的回复中获取一个有效的示例!

(好吧,添加一个关于从 a 映射回 Java 对象的其他问题yield-ed Python/Jython 结果)

(@Joonas,抱歉,我修改了我的代码,现在我无法退回到以前的错误)

import org.python.core.Py;
import org.python.core.PyList;
import org.python.core.PyTuple;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;

interface MyInterface {
    public PyList getSomething(String content, String glue, boolean bool);
}
class MyFactory {

    @SuppressWarnings("static-access")
    public MyFactory() {
        String cmd = "from mymodule import MyClass";
        PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());

        PySystemState sys = Py.getSystemState();
        sys.path.append(new PyString("C:/jython2.5.2/Lib"));

        interpreter.exec(cmd);
        jyObjClass = interpreter.get("MyClass");
    }

    public MyInterface createMe() {
        PyObject myObj = jyObjClass.__call__();
        return (MyInterface)myObj.__tojava__(MyInterface.class);
    }

    private PyObject jyObjClass;
}


public class Main {

    public static void main(String[] args) {

    /*
// with only :
    PythonInterpreter interpreter = new PythonInterpreter();

     i get : 
Exception in thread "main" Traceback (most recent call last):
  File "<string>", line 1, in <module>
LookupError: no codec search functions registered: can't find encoding 'iso8859_1'

which is probably due to the : 
#!/usr/bin/env python
# -*- coding: latin-1 -*-

// yes i am from France, so my - sorry for that - bad english ;) and have to deal with non 127 ascii chars :)
     */

    PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());

    PySystemState sys = Py.getSystemState();
    sys.path.append(new PyString("C:/jython2.5.2/Lib"));

    interpreter.exec("from mymodule import getSomething"); 
    PyObject tmpFunction = interpreter.get("getSomething"); 
    System.err.println(tmpFunction.getClass()); 
    MyInterface i = (MyInterface) tmpFunction.__tojava__(MyInterface.class); 
    System.err.println(i.getSomething("test", " - ", true));
    for (Object x : i.getSomething("test", " - ", true)) {
        System.out.println(x);
        // How can i get back an equivallent of the Python _"for (a, b) in getSomething:"_ 
        // with _"a"_ being PyUnicode or better String, and _"b"_ being boolean ?
    }

    // ^^ so adapting Daniel Teply solution works ! Thanks to him... 
    // BTW the part below did not work : but i may have missed or/and also mixed many things :/
    // i feel Jython damned hard to dive in :/ 
    // and really hope that the sample that i post and answers that i get will help others to swim!

    try {
        MyFactory factory = new MyFactory();
        MyInterface myobj = factory.createMe();

        PyList myResult = myobj.getSomething("test", " - ", true);
        System.out.println(myResult);
    }
    catch (Exception e) {
        System.out.println(e);
        // produce a : java.lang.ClassCastException: org.python.core.PySingleton cannot be cast to MyInterface
        // EDIT : see below last edit, this error may be due to my forgotten heritage from interface in the python code!
    }

    System.exit(-1);
    }
}

Python部分:(mymodule.py)

#!/usr/bin/env python
# -*- coding: latin-1 -*-

class MyClass:
    def __init__(selfself):
        pass
    def getSomething(self, content, glue = '', bool = True):
        for x in range(5):
            yield (glue.join(map(str, (content, x, chr(97 + x))))), bool
        #return list()

def getSomething(content, glue = '', bool = True):
    print "test"
    myclass = MyClass()
    return list(myclass.getSomething(content, glue, bool))

def main():
    test()

if __name__ == "__main__":
    main()

EDIT :

对于内部问题(内部评论),部分回答我自己:
(实际上我觉得我的答案和代码很丑陋,但它有效并且似乎可以取消-tuple我不知道是否有更好的 Jythonic 方式来做到这一点,如果有的话,我真的很感兴趣:))

for (Object x : i.getSomething("test", " - ", true)) {
    System.out.println(x);
    // How can i get back an equivallent of the Python _"for (a, b) in getSomething:"_ 
    // with _"a"_ being PyUnicode or better String, and _"b"_ being boolean ?

    // answering myself here :
    PyTuple mytuple = (PyTuple) x; // casting back x as PyTuple, can we have a java equivalent to _`(a, b) = x_ ? not sure...
    PyObject a = mytuple.__getitem__(0);
    PyObject b = mytuple.__getitem__(1);
    String aS = a.toString(); // mapping a unicode python string to java is as simple?
    boolean bB = b.toString().toLowerCase().equals("true");
    System.out.println(mytuple + "[" + aS + "][" + b + "][" + bB + "]");


EDIT:

回答我自己关于“产生一个:“java.lang.ClassCastException:org.python.core.PySingleton 无法转换为 MyInterface”...我的大部分误解和错误都是由于我忘记了从Python部分处理Java! (参见上面的代码,我对这个事实没有进行更正,因为这不是我的主要问题,而在其实际形式中,这是关于这个主要问题的有效答案,非常感谢丹尼尔和乔纳斯帮助我理解)。因此对于工厂范式,我们应该NOT忘记将足够的导入添加到其 Python 文件中:

from testjython.interfaces import MyInterface #// defining method inside a MyInterface.java

class MyClass(MyInterface):
    [...]

我遇到的另一个困难是正确处理导入和包。 顺便说一句,将此代码添加到上面的代码中将产生一个类型错误:无法转换为 org.python.core.PyList但这是另一个问题......


您可以使用PyObject.__call__(Object... args)调用任何可调用的 Python 对象。您可以从 java 端获取代表您的函数的 PyFunction,就像获取 python 员工类的示例一样。

或者,您可以通过调用将其隐藏在 java 端的单个方法接口后面__tojava__(Interface.class)在从 Python 解释器检索到的函数上。 详细示例(实际测试过!): 蟒蛇文件:

def tmp():
    return "some text"

java:

public interface I{
    public String tmp();
}

public static void main(String[] args) {
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.exec("from test import tmp");
    PyObject tmpFunction = interpreter.get("tmp");
    System.err.println(tmpFunction.getClass());
    I i = (I) x.__tojava__(I.class);
    System.err.println(i.tmp());

}

output:

class org.python.core.PyFunction
some text
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Jython,仅使用 Java 中的 Python 方法? 的相关文章

  • ftplib: 在 LIST 期间/之后出现 socket.error // ssl._sslobj.shutdown() / 连接超时

    我尝试使用客户端证书连接到 FTPS 服务器 我尝试了两台不同的服务器 我无法控制它们 但应该非常相似 连接建立 PWD 命令成功 在一台服务器上 LIST 命令成功 但在第二台服务器上 它产生正确的结果 文件列表 但之后 显然在 SSL
  • 隐藏控制台窗口

    problem 我开始使用 Python 和 Tkinter 设计 GUI 应用程序 当我使用 cxFreeze 冻结脚本时 然后当我在计算机上运行该 EXE 文件时 然后首先打开控制台窗口 在 Windows XP 中为黑色 DOS sh
  • 绘制顶部有函数线的直方图

    我正在尝试使用 SciPy 进行统计 使用 matplotlib 进行绘图 在 Python 中进行一些分布绘图和拟合 我在创建直方图等方面运气很好 seed 2 alpha 5 loc 100 beta 22 data ss gamma
  • 在 python 中检查堆栈中的局部变量

    我编写了一个小函数 它在堆栈中查找一级并查看其中是否有变量 但是我如何将这个函数变成一个可以在堆栈中一直查找直到找到一个局部变量并购买某个特定名称的函数 import inspect def variable lookup variable
  • Java正则表达式以数字和固定长度开头的字符串

    我制作了一个正则表达式来检查 String 的长度 所有字符都是数字并以数字开头 例如 123 以下是我的表情 REGEX 123 d 9 但它无法检查字符串的长度 它仅验证那些长度为 9 并以 123 开头的字符串 但如果我传递字符串 1
  • csharp类可以像java类一样“继承”xml文档吗?

    我正在向一些csharp代码添加注释 并且我正在使用 net 或其他东西 提供的xml语言 我有一个接口和一些实现类 我在界面中有一个方法 它有一个注释 在实现类中没有对实现方法进行注释 当人们在java中这样做时 javadoc在生成文档
  • 在Android应用程序中导入Java项目?

    即使 Java 项目中的某些类在普通 Android 项目中无法识别 我是否可以在 Android 项目中使用 Java 项目 例如javax xml包 我认为有两种可能性 使用该 java 项目创建一个 jar 并将其导入到 androi
  • 使用 python 对 Robot Framework 中的测试套件中的每个测试用例进行测试设置和拆卸

    我是机器人框架的新手 有人可以帮我看看是否可以为包含大约 20 个测试用例的测试套件中的每个测试用例进行测试设置和拆卸 有人可以用例子解释一下吗 这是一个例子 包含拆解的测试套件 如果你想最后执行每个测试用例 你可以错过它的拆卸 请阅读相应
  • 与 pandas 的时间序列相关性

    我有一些颗粒物传感器和 CSV 其时间序列如下 传感器A date value date 2017 11 30 00 00 00 30 11 17 0 00 49 2017 11 30 00 02 00 30 11 17 0 02 51 2
  • 使用 Scanner 类输入

    我从过去的经历中了解到的是nextInt or nextDouble 将继续搜索 直到在同一行或下一行中找到整数或双精度数 这并不重要 同时通过扫描器类读取字符串作为输入next 考虑空格之前的那些字符串并将光标保持在同一行 其中nextL
  • 如何阻止TreeItem选择?

    我正在与一个TreeTableView JavaFX 8 有一些树节点必须禁用才能选择 我已经尝试过选择活动 但它不起作用 请查找以下代码以获取更多信息 treeTableView getSelectionModel selectedIte
  • python matplotlib 无边框表格

    我在表格顶部有一个由以下示例生成的图 表格数据被随机数替换 实际绘图被一些任意函数替换 import numpy as np import matplotlib pylab as plt fig ax plt subplots ntp 17
  • AngularJS 和 Webpack 集成

    我正在寻找一些使用帮助webpack http webpack github io docs 对于大型 AngularJS 应用程序 我们使用基于功能的文件夹结构 每个功能 页面都有一个模块 并且它们有控制器 指令 我已经成功配置了 web
  • 有没有办法在 Eclipse 中自动附加非 JRE 包的 Javadoc?

    首先 这与 Java SE Javadocs 无关 效果很好 我们有一个基于 Java 的大型平台 包含大约 20 个 API 包 对于使用我们平台的用户 我们希望工具提示和其他此类内置文档支持能够像 Java API 那样工作 我们的 J
  • 带有 unicode 键的字典

    Python 中是否可以使用 Unicode 字符作为字典的键 我使用 Unicode 中的西里尔字母作为键 当尝试通过键获取值时 我得到以下回溯 Traceback most recent call last File baseCreat
  • python 中的 stdin 和 sys.argv 有什么区别? [复制]

    这个问题在这里已经有答案了 我在一次编码挑战中被扣分 该挑战指定我需要从 STDIN 读取 这是我的输入法 def init self input self dictionary with open input r as f reader
  • “[B”是什么样的 Java 类型?

    我正在尝试通过 Java 代码 Hibernate 从 MySQL DB 获取 MD5 加密密码 但我既得不到 Strong 也得不到任何合理的 Java 类型 我唯一收到的是这条无用的消息 java lang ClassCastExcep
  • 从Python中的一行中删除标签

    我有一个具有以下架构的文本 word1 word2 br word3 word4 br 我想删除最后一部分 并将我的结果存储在另一个文件中 我已尝试以下操作 仍然没有将结果保存在其他文件中 def main fileR open test
  • Maven 依赖项插件无法解析插件的手动指定依赖项

    我遇到了一个问题maven dependency plugin Maven版本3 2 3 maven dependency plugin版本2 10 我正在尝试引入插件依赖项 我创建了一个简单的项目
  • 从基类调用重写的方法?

    深入Python http diveintopython net object oriented framework userdict html Python 的原作者 Guido 是这样解释方法重写的 派生类可以重写其基类的方法 因为方法

随机推荐