您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为什么Python会编译模块而不是正在运行的脚本?

为什么Python会编译模块而不是正在运行的脚本?

文件在导入时进行编译。这不是安全的事情。简单来说,如果导入它,python将保存输出。见这个职位由Fredrik Lundh开发上Effbot。

>>>import main
# main.pyc is created

运行脚本时,python将 使用* .pyc文件。如果您有其他原因想要预编译脚本,则可以使用该compileall模块。

python -m compileall .
python -m compileall --help
option --help not recognized
usage: python compileall.py [-l] [-f] [-q] [-d destdir] [-x regexp] [directory ...]
-l: don't recurse down
-f: force rebuild even if timestamps are up-to-date
-q: quiet operation
-d destdir: purported directory name for error messages
   if no directory arguments, -l sys.path is assumed
-x regexp: skip files matching the regular expression regexp
   the regexp is searched for in the full path of the file

如果响应是的目录具有潜在的磁盘权限main.py,为什么Python会编译模块?

模块和脚本的处理方式相同。导入是触发输出保存的原因。

如果原因是收益将降至最低,请考虑脚本将被大量使用(例如在CGI应用程序中)的情况。

使用compileall不能解决此问题。*.pyc除非明确调用,否则python执行的脚本不会使用。格伦·梅纳德Glenn Maynard)回答中充分说明了这种做法带来的负面影响。

确实应该通过使用FastCGI之类的技术来解决CGI应用程序给出的示例。如果要消除编译脚本的开销,则可能也要消除启动python的开销,更不用说数据库连接开销了。

甚至可以使用一个简单的引导脚本python -c "import script",但是它们的样式令人怀疑。

Glenn Maynard提供了一些启发来纠正和改进此答案。

python 2022/1/1 18:29:26 有198人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶