简体   繁体   中英

How to run a python script from javascript?

So I'm making a javascript discord bot, if's that's relevant at all.

I made a python script that scrapes one website and return a json object.

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?

Thanks in advance..

You might consider looking at Node.js's Child Process API to spawn and control a Python process. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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