October 22, 2024
Chicago 12, Melborne City, USA
Node.js

Syntax Error When Executing Simple Python Code with Node.js child_process.exec


I’m trying to execute a simple Python command from my Node.js application using the child_process.exec function, but I’m encountering a syntax error. Here’s the relevant code snippet:

const { exec } = require('child_process');

const Execute = (code) => {
    return new Promise((resolve, reject) => {
        exec(`python -c ${code}`, (err, stdout, stderr) => {
            if (err) {
                console.log(err);
                console.log(`Execution error: ${err.message}`);
                reject(err);
                return;
            }
            if (stderr) {
                console.log(`stderr: ${stderr}`);
            }
            console.log(`Output: ${stdout}`);
            resolve(stdout);
        });
    });
}

module.exports = { Execute };

When I try to execute the following Python code:
print("hello world")

I receive a syntax error:
SyntaxError: invalid syntax

The command generated is:
python -c print("hello world")
I expected the output to be:

hello world

Why am I getting a syntax error when executing valid Python code?
How can I properly execute Python code using the exec function in Node.js without encountering syntax errors?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video