JS 調用 Python 的方法
簡介
在 web 開發中,有時需要在 javascript (js) 代碼中調用 python 代碼以擴展 js 的功能或訪問 python 特有的庫和數據源。本篇文章將介紹幾種在 js 中調用 python 的方法。
使用 Node.js
Node.js 是一個流行的 JavaScript 運行時環境,它允許你在服務器端執行 JavaScript 代碼。在 Node.js 中,可以使用 child_process 模塊調用 Python 代碼。以下是一個示例:
const { exec } = require('child_process'); exec('python script.py', (error, stdout, stderr) => { if (error) { console.error(`error: ${error.message}`); return; } console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); });
登錄后復制
使用 WebAssembly
WebAssembly (WASM) 是一種二進制格式,允許在 Web 瀏覽器中運行編譯后的代碼。你可以使用 Python 編譯器(如 Emscripten)將 Python 代碼編譯成 WASM 模塊,然后在 JS 代碼中加載和調用它。以下是一個示例:
fetch('script.wasm') .then(response => response.arrayBuffer()) .then(buffer => WebAssembly.instantiate(buffer)) .then(({ instance }) => { // 調用 Python 函數 const result = instance.exports.my_python_function(); console.log(result); });
登錄后復制
使用 Python 腳本服務器
另一種方法是在服務器端運行一個 Python 腳本服務器,并使用 AJAX 調用(如 XMLHttpRequest)從 JS 代碼向該服務器發送請求。以下是一個 Python 服務器示例:
import flask app = flask.Flask(__name__) @app.route('/my_python_function', methods=['POST']) def my_python_function(): data = flask.request.get_json() result = my_python_function(data) return flask.jsonify({'result': result}) app.run()
登錄后復制
在 JS 中,你可以使用 XMLHttpRequest 發送請求并接收響應:
const xhr = new XMLHttpRequest(); xhr.open('POST', '/my_python_function'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { const result = JSON.parse(xhr.responseText).result; console.log(result); }; xhr.send(JSON.stringify({ ... }));
登錄后復制