Skip to main content
 首页 » 编程设计

Python之py_compile 没有输出

2024年12月31日798°冷暖

我正在尝试检查 python 代码中的错误,我需要访问错误日志本身(我不能只检查是否创建了 .pyc 文件)。

我目前的流程是我有一个脚本来运行 python3 -m py_compile test.py,其中 test.py 是“aegsedrg”,没有别的(换句话说,无效的 Python 代码)。

运行python3 test.py时,结果报错(符合预期):

Traceback (most recent call last): 
  File "test.py", line 1, in <module> 
    aegsedrg 
NameError: name 'aegsedrg' is not defined 

但是,python3 -m py_compile test.py 没有返回任何错误(通过 stdout 或 stderr)。

这是在 Ubuntu 16.04 服务器上,我最近对它进行了升级和更新。我还完全重新安装了 Python 3。我认为这不是权限问题,test.py 是 777。

为什么 python3 -m py_compile test.py 什么都不返回?

-编辑-

我还尝试使用以下 python 脚本来执行此操作:

import py_compile 
print("Here") 
py_compile.compile("test.py") 
print("Here2") 

输出是“Here”,然后是“Here2”。

请您参考如下方法:

独立文件中的字符串 aegsedrg 本身(或任何其他非关键字字符串)不是语法错误。它可以是程序中别处定义的标识符。 py_compile 不执行编译后的文件,也无法捕获运行时错误(如 NameError)。

尝试在你的文件中写一些语法上不正确的东西,比如相同的字符串后跟一个问号:

py_compile.compile("test.py") 
  File "test.py", line 1 
    aegsedrg ? 
             ^ 
SyntaxError: invalid syntax