Using py_compile.compile() from within a Python script
Question: I am trying to understand [the
docs](https://docs.python.org/2/library/py_compile.html).

MY Python script generates Python code which will be run much later, so I want
to check now if what I generated is valid.

The docs say `py_compile.compile(file[, cfile[, dfile[, doraise]]])` and

> If doraise is true, a PyCompileError is raised when an error is encountered
> while compiling file.

So, I tried

    
    
                    source = open(generatedScriptPath, 'rt').read() + '\n'
    
                    try:
                        import py_compile
                        x = py_compile.compile(source, '', '', True)
    
                    except py_compile.PyCompileError, e:
                        print str(e)
    

but that inner Except is never hit, instead, an outer except catches

> Traceback (most recent call last): File  
>  "H:/code/testgen/testGen.py", line 293, in  
>  x = py_compile.compile(source, '', '', True) File
> "C:\Python27\lib\py_compile.py", line 106, in compile  
>  with open(file, 'U') as f: IOError: [Errno 2] No such file or directory: '#
> This script was auto-generated ...

How do I fix this? Note that I am open to alternatives, I just want the
simplest possible way to ask " is the code which I just generated
syntactically valid Python?"


Answer: Read the error message: "No such file or directory". The first argument is
supposed to be a file name to open. Or read the docs: "The source code is
loaded from the file name /file/." You might prefer the "compile" builtin,
which can compile a string of Python.

