没有为有错误的代码引发PyCompileError异常

2024-04-25 17:07:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎无法用带有真实错误的python代码生成此异常。你知道吗

我使用this question中的代码来检查我的工作。在这里,它只是稍微修改了一下:

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")

文件示例.py仅包含:

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

“prant”而不是“print”将是一个简单的语法错误,如果我运行“python”示例.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

如果我把剧本放在最上面编译器.py'然后运行'python'编译器.py它会说没有问题。你知道吗

我已经证实了编译器.py如果有不匹配的括号或引号,它会抱怨语法的正确性,因此它确实抓住了一些问题。但我希望能够以运行python的方式检测文件是否有错误示例.py“或者随便什么都行。基本上,如果它在用python运行时出错,我希望能够检测到。你知道吗

有办法吗?当出现语法错误时,为什么没有抛出PyCompileError呢?你知道吗


Tags: 文件py示例编译器isexamplecheck错误