Jython, use apenas um método do Python de Java?

Ao ler e usarEste artigo Ele assume que temos uma definição completa de objeto com objetos de classe e mapeamento (proxy) de python para java.

É possível importar somente um método (não definido dentro de uma classe, mas usando a classe python interna) de um pedaço de código em python sem envolvê-lo em uma definição de classe (sem usar o paradigma de fábrica descrito acima).

Eu gostaria de fazer algum tipo defrom myPyFile import myMethod de java e, em seguida, use myMethod, diretamente do java (talvez como um método estático?)? Mas, se isso for possível, não encontrei nenhuma pista de como fazer isso (o material da interface descrito no artigo ainda pode ser necessário para dizer ao Java como usar o myMethod).

Cumprimentos.

EDITAR : Agora estou lidando comJython 2.5.2, então pode ser dependente da versão e muito mais fácil no futuro?

EDITAR: Abaixo em resposta a Daniel:

Aqui está um código de exemplo, para reproduzir o erro que recebo, e também obter um exemplo de trabalho da sua resposta útil!

(Bem e adicione um pouco de outra pergunta sobre o mapeamento de volta para objetos Java de umprodução -ed resultado Python / Jython)

(@Joonas, Desculpe, modifiquei meu código e agora não posso voltar ao erro que costumava ter)

<code>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);
    }
}
</code>

Parte do Python: (mymodule.py)

<code>#!/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()
</code>

EDITAR :

Respondendo parcialmente a mim mesmo, pela pergunta interna (comentários internos):
(na verdade eu sinto que minha resposta e código são feios, mas funciona e parece estar ok paratupla Eu não sei se existe uma maneira Jythonic melhor para fazê-lo, se assim for, estou realmente interessado :))

<code>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 + "]");
</code>


EDITAR:

Respondendo-me à parte sobre "produzir um:"java.lang.ClassCastException: org.python.core.PySingleton não pode ser convertido em MyInterface"... a maioria dos meus equívocos e erros, devido ao fato de eu ter esquecido de lidar com o Java da parte do Python! (veja meu código acima, não o deixo sem correção sobre este fato porque não era minha pergunta principal, e em sua forma atual, é uma resposta funcional sobre essa questão principal, muito obrigado a Daniel e Joonas que me ajudaram a entender). Então, para o paradigma de fábrica, deve-seNÃO esqueça de adicionar a importação adequada ao seu arquivo Python:

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

class MyClass(MyInterface):
    [...]
</code>

Uma outra dificuldade que eu tive foi lidar corretamente com a importação e os pacotes. BTW, adicionando este código para o código superior irá produzir umTypeError: não é possível converter para org.python.core.PyList mas esta é outra preocupação ...

questionAnswers(2)

yourAnswerToTheQuestion