2013-05-09 3 views
3

jython을 사용하면 파이썬 용으로 작성된 것처럼 자바 클래스 파일에서 자바 메소드를 호출 할 수 있지만 역순으로 사용할 수 있습니까?자바에서 파이썬 메소드를 호출 할 수 있습니까?

이미 파이썬으로 작성된 많은 알고리즘이 있는데, 이들은 파이썬과 자이 썬에서 잘 작동하지만 적절한 GUI가 부족합니다. 나는 GUI를 가져 와서 파이썬 라이브러리를 손상시키지 않을 계획이다. 자이 썬이나 파이썬으로 좋은 GUI를 쓸 수 없으며 파이썬으로 좋은 알고리즘을 쓸 수 없다. 그래서 내가 찾은 해결책은 자바의 GUI와 파이썬의 라이브러리를 병합하는 것이었다. 이것이 가능한가. 자바에서 파이썬의 라이브러리를 호출 할 수 있습니까?

+1

하지 아니, 그리고 점에 더 할 이유가 없다 같은 방식으로 . – Serdalis

+0

답변이 귀하의 필요에 맞는가요? 문제가 해결 된 경우 대답을 선택하십시오. 그러면 질문에 답이 표시되지 않습니다. 감사 – Dropout

답변

12

예, 할 수 있습니다 완료되었습니다. 일반적으로 PythonInterpreter 개체를 만든 다음이를 사용하여 파이썬 클래스를 호출하면됩니다.

자바 :

import org.python.core.PyInstance; 
import org.python.util.PythonInterpreter; 


public class InterpreterExample 
{ 

    PythonInterpreter interpreter = null; 


    public InterpreterExample() 
    { 
     PythonInterpreter.initialize(System.getProperties(), 
            System.getProperties(), new String[0]); 

     this.interpreter = new PythonInterpreter(); 
    } 

    void execfile(final String fileName) 
    { 
     this.interpreter.execfile(fileName); 
    } 

    PyInstance createClass(final String className, final String opts) 
    { 
     return (PyInstance) this.interpreter.eval(className + "(" + opts + ")"); 
    } 

    public static void main(String gargs[]) 
    { 
     InterpreterExample ie = new InterpreterExample(); 

     ie.execfile("hello.py"); 

     PyInstance hello = ie.createClass("Hello", "None"); 

     hello.invoke("run"); 
    } 
} 

파이썬 :

는 다음과 같은 예를 생각해

class Hello: 
    __gui = None 

    def __init__(self, gui): 
     self.__gui = gui 

    def run(self): 
     print 'Hello world!' 
1

자이 썬으로 자바 코드에서 파이썬 기능을 쉽게 호출 할 수있다. 파이썬 코드 자체가 자이 썬에서 실행되는 한, 즉 지원되지 않는 일부 c-extensions는 사용되지 않습니다.

그게 효과가 있다면 확실히 얻을 수있는 가장 간단한 해결책입니다. 그렇지 않으면 새로운 Java6 인터프리터 지원에서 org.python.util.PythonInterpreter를 사용할 수 있습니다.

내 머리의 상단에서 간단한 예 -하지만 난 희망을 작동합니다 : (에러가 간결하게 이루어지지 확인)

PythonInterpreter interpreter = new PythonInterpreter(); 
interpreter.exec("import sys\nsys.path.append('pathToModiles if they're 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); 

SRC Calling Python in Java?

관련 문제