1. python-shell 설치
딥러닝 모델같은 파이썬 프로그램을 웹 프로젝트에서 사용하고 싶을때가 있다
node.js에서 파이썬 프로그램을 사용할 수 있는 모듈이 존재하는데
python-shell을 먼저 설치
$npm install python-shell
2. 기본 구조
기본 구조는 다음과 같다
PythonShell.run(파일경로, options, function)
const { PythonShell } = require('python-shell');
PythonShell.run('./makeup.py',options,function(err,results) {
if (err) {
throw err;
}
console.log(results);
})
여기서 options는 파일 실행할때 설정할 옵션을 넣는 객체인데 여러가지가 있다
찾아보면 될거고 자세한건 생략하고
var options = {
mode: 'text',
pythonPath: "",
pythonOptions: ['-u'],
scriptPath: "",
args:[req.files[0].filename,req.files[1].filename]
}
여기서 중요한건 2가지
mode는 파이썬 파일 수행 결과를 어떻게 받아올지 결정하는 부분이고
text와 json이 존재한다고함
args는 파이썬 파일에 넘겨줄 인자를 말한다
3. 파이썬으로 넘겨주는 인자 args
파이썬으로 넘겨주는 인자 args는 파이썬 파일에서 어떻게 받는가?
os 모듈에서 os.sys.argv로 받는다
근데 내가 args로 2개를 보냈는데..
var options = {
mode: 'text',
pythonPath: "",
pythonOptions: ['-u'],
scriptPath: "",
args:[req.files[0].filename,req.files[1].filename]
}
그러면 첫번째 값은 os.sys.argv[0]에 있고 두번째 값은 os.sys.argv[1]에 있나??
그렇지는 않다
실제로 찍어보면 다음과 같이 나온다

0번째 os.sys.argv[0]에는 파일 이름이 있고 1번째 os.sys.argv[1]과 2번째 os.sys.argv[2]에 넘겨준 인자값이 있다
4. 파이썬에서 응답
파이썬에서 응답은 print를 통해 넘겨준다
//makeup.py
...
output_img = postprocess(output[0])
plt.imsave('./images/output.jpg',output_img)
print('./images/output.jpg')
위와 같은 파일을 실행했을때... 실제 응답 결과 console.log(results)에 의한 결과는..

text 모드로 했을때 위와 같은 결과를 얻고 json으로 하면 에러남... json형태로 print찍어야하는듯?? 해보지는 않았음
5. 참조
express 서버에서 python 코드 실행하기 : 네이버 블로그 (naver.com)
express 서버에서 python 코드 실행하기
python-shell 설치 https://www.npmjs.com/package/python-shell index.js predict.py
blog.naver.com
node.js python-shell을 활용하여 python 실행 (meonggae.blogspot.com)
node.js python-shell을 활용하여 python 실행
IT 분야에 대해 공부하는 멍개의 블로그 입니다.
meonggae.blogspot.com
'프로그래밍 > node.js' 카테고리의 다른 글
react & node.js 개발 -get요청으로 서버에 데이터 보내는 방법 (0) | 2023.01.31 |
---|---|
react & node.js 개발 -static 이용해서 클라이언트에서 서버의 이미지 파일 접근하기- (0) | 2023.01.25 |
react&node.js 개발 -image 데이터 서버에 저장하는 방법 배우기 (0) | 2023.01.22 |
react&node.js 개발 - 로그인하면서 JWT 토큰 발급받고 유저 정보 알아내기 (0) | 2023.01.22 |
node.js 프로그래밍에서 axios 504에러날때 시도할부분 (0) | 2023.01.19 |