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

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

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

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

>>>import main# main.pyc is created

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

compileall
模块

python -m compileall .
编译用法
python -m compileall --helpoption --help not recognizedusage: 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
问题答案编辑
  1. 如果响应是的目录具有潜在的磁盘权限

    main.py
    ,为什么Python会编译模块?

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

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

使用compileall不能解决此问题。

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

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

甚至可以使用一个简单的引导脚本

python -c "import script"
,但是它们的样式令人怀疑。

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



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5655645.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存