从 Python 脚本传递和接收数据

Passing and Receiving data from Python Script

我想 运行 来自我的 node-express 应用程序的 python 脚本(当命中端点时)。 我想将请求的主体作为命令行参数传递给 python 脚本(或者如果有任何其他方式)。

我还想要脚本 returns 返回的数据作为响应。

任何人都可以帮助我有效地实现这一目标。

你好
你可以在你的nodejs代码中使用“child_process”包和运行你的python脚本并与之通信 那是你的python代码

# hello.py

import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    text = "Hello number " + (random.random() * 100)
    print(text, flush=True, end='')

这将是您的 js 代码

const { spawn } = require('child_process');
const messages = []; // Store readings

const sensor = spawn('python', ['hello.py']);
sensor.stdout.on('data', function(data) {
    messages.push(parseFloat(data));

    // Log to debug
    console.log(messages);
});

如果您想将参数传递给您的 python 源代码,请执行此操作

const myList = ["foo", "bar", "baz"];
const { spawn } = require("child_process");
const python = spawn('python',["script.py", JSON.stringify(myList)]);

那将是您的 python 代码

# script.py

import sys, json
if __name__ == '__main__':
    my_list = json.loads(sys.argv[1])