js如何调用python

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 服务器示例:

如知AI笔记 如知AI笔记

如知笔记——支持markdown的在线笔记,支持ai智能写作、AI搜索,支持DeepseekR1满血大模型

如知AI笔记 27 查看详情 如知AI笔记

import flaskapp = 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 发送请求并接收响应:

立即学习“Python免费学习笔记(深入)”;

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({ ... }));

以上就是js如何调用python的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/474369.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月8日 08:48:40
下一篇 2025年11月8日 08:49:32

相关推荐

发表回复

登录后才能评论
关注微信