问题
Write a function to check if an input file contain syntactically correct Python code, if the input file does not contain syntactcally correct Pyhton code the function should print the following message:
<filename> does not contain syntactically correct Python codewhere
<filename>is the name of the input file . We suggest importing the py_compile module and using the compile function (with the parameter doraise = True) and the PyCompileError exception of this module.
I wrote this function, is it correct?:
def check(python_file):
try:
file = open(python_file, 'r')
py_compile.compile(python_file, doraise=True)
except py_compile.PyCompileError:
print("<"+python_file+"> does not contain syntactically correct Python code")
来源:https://stackoverflow.com/questions/49554798/pycompileerror-exception