Jessica
Jessica

Reputation: 9830

Python function not loading in node.js

I'm trying to run a python function with arguments from node.js.

When I run process.stdout.on nothing happens. Here's the full code:

Node.js

app,get('/', async (req, res) => {
    const spawn = require('child_process').spawn; // Should this be called every time, or can I just put it with my other `require` statements?
    var process = await spawn('python', [
        '../../python/hello.py',
        'Hello',
        'World'
    ]);
    process.stdout.on('data', function(data) {
        console.log(data.toString());
        // res.send(data.toString()); // When I do this, the website never loads
    });
    res.send('test');
});

Python

import sys

print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])

I'm running the node app via nodemon, and I'm not seeing any results. (I'm new to python, so I don't know if anything has to be running while the node app is running.

It doesn't seem like the python file is loading. How can I get it to load?

Upvotes: 0

Views: 591

Answers (1)

Amethystx87
Amethystx87

Reputation: 488

The issue seems to be that you're using await for spawn- I ran the following similar code and had output printed to the console:

app.js

const spawn = require('child_process').spawn;
const process = spawn('python', ['./script.py', 'Hello', 'World']);
process.stdout.on('data', (data) => console.log(data.toString()));

script.py

import sys
print("Python")
print("First: " + sys.argv[1])
print("last: " + sys.argv[2])

Upvotes: 1

Related Questions