检查 Python 脚本是否使用另一个 Python 脚本编译

Joh*_*ine 2 python compilation python-3.x

我知道py_compile.compile("file.py")会编译file.py。

但是我可以在运行该命令的同一代码中以某种方式检查编译是否成功吗?

我想基本上有一个 if 条件,具体取决于编译是否成功。是否可以使用 py_compile 模块?或者我可以使用更好的东西吗?

小智 5

你可以这样做:

import py_compile
try:
    py_compile.compile("file.py", doraise=True)
except py_compile.PyCompileError:
    print("Compilation failed!")
Run Code Online (Sandbox Code Playgroud)

与 Python 一样,寻求宽恕比请求许可更好。