python - 对于有错误的代码,不会引发 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 - 在 c++ 或 python 中生成一个像样的视差图以在树莓派上实现的最佳方法(算法或函数)是什么?
- android - 分析 ANR 时需要考虑哪些关键字和关键点?
- c# - C#:找不到类型或命名空间名称“DEVMODE”
- android - 教程中的代码现在不起作用
- tfs - TFS 2018 API - 生成 PAT 或 SSH
- node.js - 节点红色 HTTP POST 参数
- apache-kafka - Kafka 流是否可以将输出写入两个不同的主题?
- bash - 无法通过 Bash 变量将带引号的标志传递给可执行文件
- sql-server - 用于还原数据库的具有可变日期和时间的文件名
- laravel - 如何访问对象属性?