首页 > 解决方案 > 对于有错误的代码,不会引发 PyCompileError 异常

问题描述

我似乎无法使用带有真正错误的 python 代码生成此异常。

我使用这个问题的代码来检查我的工作。在这里,只是稍微修改了一下:

import py_compile

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")
   
    else:
       print("Compiled " + python_file + " with no issues.")
   
check("example.py")

文件 example.py 仅包含:

print ("This is fine.")
prant ("This should be an error.")

'prant' 而不是 'print' 将是一个简单的语法错误,如果我运行 'python example.py' 然后我看到:

This is fine.
Traceback (most recent call last):
  File "example.py", line 2, in <module>
    prant ("This should be an error.")
NameError: name 'prant' is not defined

如果我在顶部调用脚本“compiler.py”然后运行“python compiler.py”,它会说没有问题。

我已经验证,如果存在不匹配的括号或引号,compiler.py 会抱怨语法正确性,因此它确实会遇到一些问题。但我希望能够以与运行“python example.py”或其他任何方式相同的方式检测文件何时出现错误。基本上,如果在使用“python”运行它时出现错误,我希望能够检测到它。

有没有办法做到这一点?为什么出现语法错误时不抛出 PyCompileError?

标签: python

解决方案


推荐阅读