0

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?

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

5 Comments

Do I need to install anything?
Actually, when I run it in app.js, it works. But when it's in a app,get('/', it doesn't work
Did you hit the endpoint on your local host or make any other get request to the base? You'll need to actually make a request to the server if you want to bind it to a get endpoint
Yes. The issue was having async in the function. That's it. Thanks. Does require('child_process').spawn have to get called every time, or can I put it above the file?
Should be fine at the top of the file :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.