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.