child_process子进程执行python
main.js
const { spawn } = require('child_process');
const pythonScript = 'python_script.py';
const arg1 = 2;
const pythonProcess = spawn('python', [pythonScript, arg1]);
pythonProcess.stdout.on('data', (data) => {
console.log(`输出: ${data}`);
});
pythonProcess.on('close', (code) => {
if (code === 0) {
console.log('Python 脚本运行成功');
} else {
console.error(`Python 脚本运行失败,退出码: ${code}`);
}
});
python_script.py
import sys
def fn():
params = sys.argv[1]
print(f"python中接受到的参数为: {params}")
val = fn()
缺点是无法传递中文
python创建服务器使用网络通信
from flask import Flask, request, redirect, url_for, render_template
# 创建Flask服务
app = Flask(__name__)
# 访问URL:http://127.0.0.1:8080/home/hello
# 返回结果:{"data":"welcome to use flask.","msg":"hello"}
@app.route('/home/<name>')
def home(name):
return {
"msg": name,
"data": "welcome to use flask."
}
if __name__ == "__main__":
# 启动Flask服务,指定主机IP和端口
app.run(host='127.0.0.1', port=8080)
使用nodejs的node-pyrunner模块
Node-PyRunner模块用于nodejs与python交互,在nodejs中用node-pyrunner同步或者异步执行python脚本和调用python函数,在异步调用时允许python执行js脚本或调用js函数。
https://github.com/supercoderlee/node-pyrunner
npm install node-pyrunner