programming language/Python
Python 에서 Javascript 코드 실행하기
__observer__
2018. 1. 19. 18:30
반응형
요즘 웹 서핑을 하다 보면 Javascript 로 된 괜찮은 소스코드들이 눈에 띄더군요.
이런 Javascript 코드 들을 PC 에서 실행하기 위해서는 보통 nodejs 를 설치해서 사용하곤 하는데~
오늘은 Python 에서 Javascript 를 실행시키는 방법에 대해 소개하려 합니다.
Python에서 Javascript 코드 실행을 위해서는 Windows CMD 창에서 아래와 같이 js2py 모듈을 설치 합니다.
pip install js2py
다음으로 아래 예제를 실행해 보면~ 굉장히 쉽게 알수 있을 겁니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import js2py | |
engTypeToKorJS=''' | |
function javascriptCode(a,b) { | |
var res = 0; | |
res = a + b; | |
console.log( res ); | |
return res; | |
} | |
''' | |
if __name__ == '__main__': | |
engTypeToKor = js2py.eval_js(engTypeToKorJS) | |
print engTypeToKor(1, 2) | |
코드 문자들을 js2py.eval_js() 함수를 사용하여 Python 내부에서 바로 사용 할 수 있습니다.
또는 Javascript 코드가 파일로 되어 있는 경우에는 다음과 같이 js2py.translate_file() 함수를 사용하면 Javascript 코드를 Python 코드로 변환해더 import 할 수도 있더군요.
js2py.translate_file('example.js', 'example.py')
js2py 모듈의 더 많은 예는 아래 주소를 참조하시기 바랍니다.
https://github.com/PiotrDabkowski/Js2Py
반응형