본문 바로가기

JAVA/JAVA

[JAVA] Spring 에서 python 사용하기 - jython

 

 

이전에 작성한 글에서 jython 을 설치하였습니다.

https://binshuuuu.tistory.com/288

불러오는 중입니다...

 

이제 Spring + Maven 에 jython 을 연동해 봅시다.

 

1. Pom.xml


		<dependency>
			<groupId>org.python</groupId>
			<artifactId>jython-standalone</artifactId>
			<version>2.7.1</version>
		</dependency>

 

 * 가지고 있는 버전에 맞춰서 추가해주시면 됩니다. 저는 2.7.1 버전을 사용합니다.

https://mvnrepository.com/artifact/org.python/jython

 

Maven Repository: org.python » jython

Jython is an implementation of the high-level, dynamic, object-oriented language Python written in 100% Pure Java, and seamlessly integrated with the Java platform. It thus allows you to run Python on any Java platform. VersionRepositoryUsagesDate2.7.x2.7.

mvnrepository.com

Maven - Dependency 에 jython 을 추가해줌으로써, 간단하게 연동 준비를 할 수 있습니다.

* jython 을 설치하지 않고, 라이브러리를 추가해줌으로써, 기본 동작은 가능하지만, 외부모듈을 이용하는데에

제한적인 부분들이 있기때문에, 필요에 따라 설치하거나, 설치하지 않는 것을 선택하시면 됩니다.

 

 

그리고 Maven Intall ~ build 해줍니다.

 

2. 테스트

# test.py
def testFunc(a,b):
    print("TEST FUNC")
    c = a + b
    return c

# test.java
private static PythonInterpreter intPre;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String getTest() {
        intPre = new PythonInterpreter();
        intPre.execfile("src/main/clt/test.py");
        intPre.exec("print(testFunc(5,10))");

        PyFunction pyFuntion = (PyFunction) intPre.get("testFunc", PyFunction.class);
        int a = 10, b = 20;
        PyObject pyobj = pyFuntion.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println(pyobj.toString());

        return pyobj.toString();
    }

 

REST API 에서 Python Test.py 를 실행시켜보고, 해당 Return 값을 가져와 봅시다.

결과값

HTML RETURN VALUE

 

SYSTEM RETURN VALUE