1

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.

7
  • 1
    Can you simply try to import generated module and catch ImportError (if module's missing) or SyntaxError (if module is invalid)? Alternativly, ast.parse would raise an exception during parsing an invalid Python code. Commented Mar 4, 2016 at 12:45
  • 1
    What do you mean by invalid Python? Commented Mar 4, 2016 at 12:45
  • If you simply want to parse the module you could use the ast module's parse function. In fact there is a compile built-in function that can be used to do that. Commented Mar 4, 2016 at 12:46
  • @Rogalski Yeah... and what if that file is user provided and contains malicious code? Commented Mar 4, 2016 at 12:47
  • 1
    It gives an exception for me. What did you try for 'invalid Python code'? Commented Mar 4, 2016 at 12:50

1 Answer 1

5

There is no need to use py_compile. 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 module to parse the contents of the file, or directly call the 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.

Sign up to request clarification or add additional context in comments.

1 Comment

FYI: py_compile is also a standard library.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.