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); } }); }
.py 파일은 사용자의 컴퓨터에서 실행되지 않고 서버에서 실행됩니다.
답변
프로세스를 통한 커뮤니케이션
예:
Python : 이 Python 코드 블록은 임의의 온도를 반환해야합니다.
# sensor.py
import random, time
while True:
time.sleep(random.random() * 5) # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5 # -5 to 15
print(temperature, flush=True, end='')
자바 스크립트 (Nodejs) : 여기서 파이썬 코드를 실행하기 위해 새로운 자식 프로세스를 생성 한 다음 인쇄 된 출력을 얻어야합니다.
// temperature-listener.js
const { spawn } = require('child_process');
const temperatures = []; // Store readings
const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {
// convert Buffer object to Float
temperatures.push(parseFloat(data));
console.log(temperatures);
});
답변
