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 ...