How to check python code's syntax error before running it

python, syntax-error

Solution

It's not a syntax error. `b=c` is perfectly valid syntax, whether or not `c` exists. In fact, some other module could have done

import __builtin__
__builtin__.c = 3

in which case there would be a built-in `c` variable with value 3 available to all modules, and your code would run fine.

For a somewhat less pathological example, if the file contains a `*` import such as

from numpy import *

the import will dump a whole bunch of names into the module's global namespace, and there's no way to tell what those names are. Even without `import *`, though, Python can't be sure that a reference to an unknown name is an error at compile time.

If you want to detect semantic errors such as this, you'll need a more complex analysis of the program. Integrating with an existing linter like `pylint`, as suggested by NPE, is likely to be more productive than writing your own tool. If you really want to do it yourself, you can parse the code with `ast.parse` and examine the AST, going statement by statement to see what variables exist at what points. You'll still never catch all bugs, but you'll find quite a few.

Problem

I am developing a tool which has to accept a file as an input, check syntax errors, compile it and do something after that. For example, I have a file run.py: ``` a=5 b=c print b ``` This should clearly show a syntax error while compiling because 'c' is not defined I tried to use ``` try: py_compile.compile("source_program/run.py", doraise=True) print "Compiled" except: print "Error while compiling" ``` I get the output "Compiled" instead of "Error while compiling" If I modify the run.py file as: ``` a=5 b=c/ #Instead of b=c print b ``` Then I get the output "Error while compiling" What don't I get an error message in the first case?

Original source