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/temp.py';
fs.writeFile('/tmp/temp.py', formular, (err) => {
// throws an error, you could also catch it here
if (err) throw err;
// success case, the file was saved
console.log('/tmp/temp.py');
});
const pySyntaxChecker = spawn('python', ['py_checker.py', tempPyFile], {capture: ['stdout', 'stderr']});
pySyntaxChecker.stdout.on('data', (data) => {
console.log(data);
res.end('ok')
});
pySyntaxChecker.stderr.on('data', (data) => {
console.log(data);
res.end(data)
});
Python code to check the syntax:
import py_compile
import sys
try:
print(py_compile.compile(sys.argv[1]))
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!