在 web 开发中,有时需要在 javascript (js) 代码中调用 python 代码以扩展 js 的功能或访问 python 特有的库和数据源。本篇文章将介绍几种在 js 中调用 python 的方法。
Node.js 是一个流行的 JavaScript 运行时环境,它允许你在服务器端执行 JavaScript 代码。在 Node.js 中,可以使用 child_process 模块调用 Python 代码。以下是一个示例:
<code class="js">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}`);
});</code>WebAssembly (WASM) 是一种二进制格式,允许在 Web 浏览器中运行编译后的代码。你可以使用 Python 编译器(如 Emscripten)将 Python 代码编译成 WASM 模块,然后在 JS 代码中加载和调用它。以下是一个示例:
<code class="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);
});</code>另一种方法是在服务器端运行一个 Python 脚本服务器,并使用 AJAX 调用(如 XMLHttpRequest)从 JS 代码向该服务器发送请求。以下是一个 Python 服务器示例:
<code class="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()</code>在 JS 中,你可以使用 XMLHttpRequest 发送请求并接收响应:
立即学习“Python免费学习笔记(深入)”;
<code class="js">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({ ... }));</code>以上就是js如何调用python的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号