Sometimes , we need to check the python script syntax in a NodeJS application. For eg: a formular is stored in a database (via NodeJS application) as a python script syntax, then we use python eval() function to execute that python function.

# invalid syntax, lack of ) in the end of the line
"(20000 if x <= 4 else 20000 + (x - 4) *5000 "

We can use NodeJS child process to call to python (py_compile module) to check the syntax only (not exec)

    const formular = "(20000 if x <= 4 else 20000 + (x - 4) *5000 ";
    const tempPyFile = '/tmp/';

    fs.writeFile('/tmp/', formular, (err) => {
        // throws an error, you could also catch it here
        if (err) throw err;
        // success case, the file was saved

    const pySyntaxChecker = spawn('python', ['', tempPyFile], {capture: ['stdout', 'stderr']});

    pySyntaxChecker.stdout.on('data', (data) => {

    pySyntaxChecker.stderr.on('data', (data) => {

Python code to check the syntax:

import py_compile
import sys

except IndexError as e:
    raise e

Here is the result:

Full code on github:

Hope this will help anyone facing with the same use case to me!