使用compileall来预编译python代码

python中有一个compileall模块,此模块可以将指定目录下的.py文件编译成python的二进制文件.pyc或者.pyo文件。

compile_dir()可以遍历目录然后做二进制的编译。

如下代码:

import compileall

compileall.compile_dir('examples')

上面的代码,默认情况下,深度小于10的子目录都会被编译。如果目录中包含svn目录的话会将svn目录下的.py文件也编译了。

$ python compileall_compile_dir.py
Listing examples ...
Listing examples/.svn ...
Listing examples/.svn/prop-base ...
Listing examples/.svn/props ...
Listing examples/.svn/text-base ...
Listing examples/.svn/tmp ...
Listing examples/.svn/tmp/prop-base ...
Listing examples/.svn/tmp/props ...
Listing examples/.svn/tmp/text-base ...
Compiling examples/a.py ...
Listing examples/subdir ...
Listing examples/subdir/.svn ...
Listing examples/subdir/.svn/prop-base ...
Listing examples/subdir/.svn/props ...
Listing examples/subdir/.svn/text-base ...
Listing examples/subdir/.svn/tmp ...
Listing examples/subdir/.svn/tmp/prop-base ...
Listing examples/subdir/.svn/tmp/props ...
Listing examples/subdir/.svn/tmp/text-base ...
Compiling examples/subdir/b.py ...

要过滤不必要的目录,可以使用rx参数提供一个正则表达式来排除不需要的目录。

import compileall
import re

compileall.compile_dir('examples', 
rx=re.compile(r'/\.svn'))
$ python compileall_exclude_dirs.py
Listing examples ...
Compiling examples/a.py ...
Listing examples/subdir ...
Compiling examples/subdir/b.py ...

maxlevels参数可以控制目录树递归的层级数,例如,不需要递归可以将maxlevels参数设置为0

import compileall
import re

compileall.compile_dir('examples', 
maxlevels=0, 
rx=re.compile(r'/\.svn'))
$ python compileall_recursion_depth.py
Listing examples ...
Compiling examples/a.py ...

编译sys.path中包含的所有目录:

通过调用compile_path()可以编译sys.path中包含的所有目录

import compileall
import sys

sys.path[:] = ['examples', 'notthere']
print 'sys.path =', sys.path
compileall.compile_path()

上面的例子在编译之前重新设置了sys.path的值,这是为了防止compileall去尝试编译系统路径

$ python compileall_path.py
sys.path = ['examples', 'notthere']
Listing examples ...
Compiling examples/a.py ...
Listing notthere ...
Can't list notthere

在命令行中使用compileall

如下使用示例:

$ python -m compileall -h
option -h not recognized

用法:: 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 search for in the full path of the file

如下例子,忽略.svn目录:

$ python -m compileall -x '/\.svn' examples
Listing examples ...
Compiling examples/a.py ...
Listing examples/subdir ...
Compiling examples/subdir/b.py ...


  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值