Python优化模块

2024-05-14 14:57:39 发布

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

Python可以在优化模式(-O)下运行脚本,关闭assert之类的调试,如果我还记得删除docstring的话。我没见过它真的用过,也许它只是过去时代的产物。正在使用吗?为何?

为什么Python 3中没有删除这个无用的东西?


Tags: 脚本模式assertdocstring时代产物
3条回答

如果只分发包含.pyo文件的存档表单,则可以节省少量内存和磁盘空间。(如果您经常使用assert,并且可能使用复杂的条件,那么节省的成本就不是微不足道的,而且还可以扩展到运行时间)。

所以,它绝对不是无用的,当然它是被使用的(如果你将一个Python编码的服务器程序部署到大量的N台服务器机器上,为什么要浪费N*X字节来保存没有人能够访问的docstring?!)。当然,如果能省更多的钱会更好,但是,嘿——不要浪费,不要浪费!-)

因此,在Python3中保留这个功能(无论如何,它提供起来都很简单,你知道;-)几乎是一件轻而易举的事情——为什么还要在后者的采用困难中添加“epsilon”?-)

在不同的Linux发行版中,预打包的软件通常是用-O编译的字节。例如,对于python应用程序,如果来自Fedora packaging guidelines

In the past it was common practice to %ghost .pyo files in order to save a small amount of space on the users filesystem. However, this has two issues: 1. With SELinux, if a user is running python -O [APP] it will try to write the .pyos when they don't exist. This leads to AVC denial records in the logs. 2. If the system administrator runs python -OO [APP] the .pyos will get created with no docstrings. Some programs require docstrings in order to function. On subsequent runs with python -O [APP] python will use the cached .pyos even though a different optimization level has been requested. The only way to fix this is to find out where the .pyos are and delete them.

The current method of dealing with pyo files is to include them as is, no %ghosting.

python-O当前执行以下操作:

  • 完全忽略断言
  • 将特殊内置名称__debug__设置为False(默认为True)

当被称为python-OO时

  • 从代码中删除docstring

我不知道为什么每个人都忘了提到__debug__问题;也许是因为我是唯一使用它的人:if __debug__构造在-O下运行时根本不会创建字节码,我发现这非常有用。

相关问题 更多 >

    热门问题