2

I am currently writing a Discord bot in Node.js and i am wondering if there is any way to run a python program from Node.js.

I have far more experience programming in python and although I would prefer to write the bot in python it would be far to slow.

The bot is made to interface with a game or windows, for example: Someone types "!flipscreen" The Node.js bot replies and the python script that it runs sends data to the client running on your pc to rotate the screen.

Any advice is appreciated, thank you.

Edit: I am just trying to run a python file it doesn't have to be in the same terminal it could open a new window.

  • 2
    You can run your python program on a different port on your server and send requests with node.js to it and wait for a response. – RnD Mar 12 '19 at 12:45
  • Possible duplicate of [How to call a Python function from Node.js](https://stackoverflow.com/questions/23450534/how-to-call-a-python-function-from-node-js) – Marcos Casagrande Mar 12 '19 at 12:49

1 Answers1

1

NodeJS has child process package. Using which you can invoke python script.

Sample code :

const { spawn } = require('child_process');
const pp = spawn('python', ['script.py']);

pp.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

pp.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

pp.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

You can find more example in the documentation page.

Akhil Thayyil
  • 9,263
  • 6
  • 34
  • 48