js调用python:如何利用JS调用Python实现更高效的开发

JS调用Python的方法有很多,下面介绍一种基于Node.js的方法:安装Node.js,并安装node-python模块:

JS调用Python的方法有很多,介绍一种基于Node.js的方法:安装Node.js,并安装node-python模块:

JS调用Python的方法有很多,介绍一种基于Node.js的方法:

1. 安装Node.js,并安装node-python模块:


npm install node-python

2. 创建一个js文件,如test.js,内容如下:


const PythonShell = require('node-python');
 
// 创建一个PythonShell对象
let pyshell = new PythonShell('test.py');
 
// 向Python脚本发送数据
pyshell.send('Hello World!');
 
// 当Python脚本返回数据时,调用回调函数
pyshell.on('message', function (message) {
    console.log(message);
});
 
// 当Python脚本执行完毕时,调用回调函数
pyshell.end(function (err,code,signal) {
    if (err) throw err;
    console.log('The exit code was: ' + code);
    console.log('The exit signal was: ' + signal);
    console.log('finished');
    console.log('finished');
});

3. 创建一个Python文件,如test.py,内容如下:


#!/usr/bin/env python
import sys
 
# 获取JS发送的消息
message = sys.stdin.readline()
 
# 打印消息
print("Received message: " + message)
 
# 向JS发送消息
sys.stdout.write("Hello from Python!")
sys.stdout.flush()

4. 执行JS文件:


node test.js

上述代码执行后,可以看到输出:

Received message: Hello World!

Hello from Python!

The exit code was: 0

The exit signal was: null

finished

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(152)
python编写一个简单的程序:# 使用Python生成一个标题title = The Power of Pythonprint
上一篇
python爬虫抢购让你轻松享受优惠
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(69条)