简体   繁体   English

如何从javascript运行python脚本?

[英]How to run a python script from javascript?

So I'm making a javascript discord bot, if's that's relevant at all. 因此,我正在制作一个javascript discord机器人,如果这很重要的话。

I made a python script that scrapes one website and return a json object. 我制作了一个python脚本,可抓取一个网站并返回json对象。

How can I make a javascript function that runs the python script, and stores the json object, in order for me to access it's content? 我如何制作一个运行python脚本并存储json对象的javascript函数,以便我访问其内容?

Thanks in advance.. 提前致谢..

You might consider looking at Node.js's Child Process API to spawn and control a Python process. 您可能会考虑查看Node.js的子进程API,以生成并控制Python进程。 Here's a modified code snippet from the documentation that executes a Python script, collects it's output on standard out while it runs, and parses its output as JSON when the script exits. 这是执行Python脚本的文档的修改后的代码段,该代码段在运行时按标准输出收集其输出,并在脚本退出时将其输出解析为JSON。

const { spawn } = require('child_process');
const script = spawn('python', ['/path/to/script.py']);
const chunks = [];

// there is a data chunk from the script available to read
script.stdout.on('data', (data) => {
    chunks.push(data)
});

// no more data left to read, parse our JSON object
script.stdout.on('end', () => {
    let output_buf = Buffer.concat(chunks);
    let object = JSON.parse(output_buf.toString());
    ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM