1.다운로드
jython 사용을 위해서는 먼저 파일을 다운받는다
https://www.jython.org/download
받은 jar 파일을 자바로 실행합니다
이게 만약 없다면
jar 자바로 실행 검색!
next 만하면서 쭉~ 진행
2. 환경변수
그리고나서
본인이 다운받은 jython 경로의 bin으로
환경변수 추가
3. dependency
스프링에서
pom.xml에
본인의 버전에맞게 dependency 추가
<!-- https://mvnrepository.com/artifact/org.python/jython -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.3</version>
</dependency>
그리고 나서 메이븐 업데이트!
4. 사용
test.py를 만듭니다
def testFunc(a,b):
c = a + b
return c
controller에 작성을 해줍니다
// 테스트
private static PythonInterpreter intPre;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String getTest() {
log.info("파이썬 코드 실행합니다 ");
System.setProperty("python.import.site", "flase");
intPre = new PythonInterpreter();
intPre.execfile("test.py의 경로를 입력");
intPre.exec("print('python running')");
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();
}
실행을하면 이렇게뜨고
return을 저렇게 받아서 그렇지 30이라는 값이 잘뜨는것을 확인할 수 있다.
완성!!
추가사항
1. Cannot import site module and its dependencies: No module named site 에러
컨트롤러에 이 코드가없으면
System.setProperty("python.import.site", "flase");
이런 에러가 뜬다
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is ImportError: Cannot import site module and its dependencies: No module named site
Determine if the following attributes are correct:
* sys.path: [C:...1.0.0-BUILD-SNAPSHOT\WEB-INF\lib\Lib, __classpath__, __pyclasspath__/]
This attribute might be including the wrong directories, such as from CPython
* sys.prefix: ...-1.0.0-BUILD-SNAPSHOT\WEB-INF\lib
This attribute is set by the system property python.home, although it can
be often automatically determined by the location of the Jython jar file
You can use the -S option or python.import.site=false to not import the site module
2. pip가 jython쪽으로 되어있어 cmd에서 원하는 명령어를 칠수없었다.
환경변수도 아래쪽에 위치하고 위쪽에 다른 파이썬 환경변수가 있었음에도 왜인지 자이썬이 우선시 명령어가 작동했다.
그래서 아까 추가한 환경변수에서 jython부분을 제거하고 진행했는데
코드가 잘 돌아간다....
3. cv2는 없다고 사용하지 못했다.
내가 자바에서 파이썬을 돌리고 싶었던 이유는
웹에서 이미지를 받아서 해당 이미지를 딥러닝 학습된 모델을 통해서 판별후 값을 반환하기 위해서 였지만 (딥러닝..)
자바쪽에서 파이썬의 import cv2를 인식하지 못하여 실패
플라스크와 스프링 연결을 통해서 시도해볼예정...
참고사이트
https://binshuuuu.tistory.com/289
[JAVA] Spring 에서 python 사용하기 - jython
이전에 작성한 글에서 jython 을 설치하였습니다. https://binshuuuu.tistory.com/288 불러오는 중입니다... 이제 Spring + Maven 에 jython 을 연동해 봅시다. 1. Pom.xml org.python jython-standalone 2.7.1 * 가지고 있는 버전
binshuuuu.tistory.com
'language > 자바' 카테고리의 다른 글
[java]try-with-resources (feat. autocloseable) (0) | 2022.11.09 |
---|---|
[java] Unreachable code 에러 (feat. dead code) (0) | 2022.11.03 |
[java] static 영역, heap 영역, stack 영역 (JVM) (0) | 2022.10.05 |
[java] + 연산 순서 (0) | 2022.07.25 |
[java] local variables , instance variables, class variables (지역변수, 인스턴스변수, 클래스변수) (0) | 2022.07.20 |