JavaScript 코드에서 Python 함수 호출
JavaScript 코드에서 Python 함수를 호출하고 싶습니다. JavaScript에는 원하는 작업을 수행 할 수있는 대안이 없기 때문입니다. 이것이 가능한가? 작동하도록 아래 스 니펫을 조정할 수 있습니까?
자바 스크립트 코드 :
var tag = document.getElementsByTagName("p")[0];
text = tag.innerHTML;
// Here I would like to call the Python interpreter with Python function
arrOfStrings = openSomehowPythonInterpreter("~/pythoncode.py", "processParagraph(text)");
~/pythoncode.py
자바 스크립트로 쉽게 작성할 수없는 고급 라이브러리를 사용하는 함수가 포함되어 있습니다.
import nltk # is not in JavaScript
def processParagraph(text):
...
nltk calls
...
return lst # returns a list of strings (will be converted to JavaScript array)
당신이 필요로하는 것은 당신의 pythoncode에 ajax 요청을하는 것입니다. jquery http://api.jquery.com/jQuery.ajax/ 를 사용하거나 javascript 만 사용할 수 있습니다.
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
로부터 document.getElementsByTagName
나는 당신이 브라우저에서 자바 스크립트를 실행하는 것 같아요.
브라우저에서 실행되는 자바 스크립트에 기능을 노출하는 전통적인 방법은 AJAX를 사용하여 원격 URL을 호출하는 것입니다. AJAX의 X는 XML 용이지만 요즘에는 모두가 XML 대신 JSON을 사용합니다.
예를 들어, jQuery를 사용하면 다음과 같이 할 수 있습니다.
$.getJSON('http://example.com/your/webservice?param1=x¶m2=y',
function(data, textStatus, jqXHR) {
alert(data);
}
)
서버 측에서 파이썬 웹 서비스를 구현해야합니다. 간단한 웹 서비스의 경우 Flask 를 사용하고 싶습니다 .
일반적인 구현은 다음과 같습니다.
@app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
Silverlight 를 사용하여 브라우저에서 IronPython (Python.Net의 일종)을 실행할 수 있지만 IronPython에 NLTK를 사용할 수 있는지는 모르겠습니다.
일반적으로 다음과 같은 ajax 요청을 사용하여이를 수행합니다.
var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();
텍스트 편집기 없이는 .txt 파일을 열 수없는 것처럼 Python 프로그램 없이는 JavaScript에서 .py 파일을 실행할 수 없습니다. 그러나 웹 API 서버 (아래 예제에서는 IIS)의 도움으로 모든 것이 숨이 막힐 것입니다.
Python을 설치하고 test.py 샘플 파일을 만듭니다.
import sys # print sys.argv[0] prints test.py # print sys.argv[1] prints your_var_1 def hello(): print "Hi" + " " + sys.argv[1] if __name__ == "__main__": hello()
웹 API 서버에서 메서드 생성
[HttpGet] public string SayHi(string id) { string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py"; Process p = new Process(); p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; p.Start(); return p.StandardOutput.ReadToEnd(); }
이제 JavaScript를 위해 :
function processSayingHi() { var your_param = 'abc'; $.ajax({ url: '/api/your_controller_name/SayHi/' + your_param, type: 'GET', success: function (response) { console.log(response); }, error: function (error) { console.log(error); } }); }
Remember that your .py file won't run on your user's computer, but instead on the server.
참고URL : https://stackoverflow.com/questions/13175510/call-python-function-from-javascript-code
'Development Tip' 카테고리의 다른 글
PHP의 연결 풀링 (0) | 2020.11.05 |
---|---|
ListPreference : 항목 값으로 문자열 배열을 사용하고 항목 값이 작동하지 않으므로 정수 배열을 사용합니다. (0) | 2020.11.05 |
지연 평가 및 시간 복잡성 (0) | 2020.11.04 |
jQuery.parseJSON 작은 따옴표와 큰 따옴표 (0) | 2020.11.04 |
십진수 값에 대한 Rails number_field 대안 (0) | 2020.11.04 |