How to validate the syntax of a Python script?
Question: I just want the simplest possible way for my Python script to ask "is the
Python code which I just generated syntactically valid Python?"

I tried:

    
    
    try:  
        import py_compile  
        x = py_compile.compile(generatedScriptPath, doraise=True)  
        pass  
    
    except py_compile.PyCompileError, e:
        print str(e)
        pass
    

But even with a file containing invalid Python, the exception is not thrown
and afterwards `x == None`.


Answer: There is no need to use
[`py_compile`](https://docs.python.org/3/library/py_compile.html). It's
intended use is to _write a bytecode file_ from the given source file. In fact
it will fail if you don't have the permissions to write in the directory, and
thus you could end up with some false negatives.

To just parse, and thus validate the syntax, you can use the
[`ast`](https://docs.python.org/2/library/ast.html) module to
[`parse`](https://docs.python.org/2/library/ast.html#ast.parse) the contents
of the file, or directly call the
[`compile`](https://docs.python.org/2/library/functions.html#compile) built-in
function.

    
    
    import ast
    
    def is_valid_python_file(fname):
        with open(fname) as f:
            contents = f.read()
        try:
            ast.parse(contents)
            #or compile(contents, fname, 'exec', ast.PyCF_ONLY_AST)
            return True
        except SyntaxError:
            return False
    

Be sure to _not_ execute the file, since if you cannot trust its contents (and
if you don't even know whether the file contains valid syntax I doubt you can
actually trust the contents even if you generated them) you could end up
executing malicious code.

