See All Titles |
![]() ![]() Generating an Executable Python BytecodeWhen loading a module, the Python interpreter first tries to load a byte-compiled version of the module (a .pyc or .pyo bytecode file) from the system. If it doesn't find one, it automatically byte-compiles the module, and in case the permissions given to the user who is executing the command allow, a byte-compiled version of the module is saved in the disk for a later user. Note that it is a good idea to bytecompile all files before giving Python access to users who cannot save in that source directory. Otherwise, the interpreter has to byte-compile the module every time the module is loaded, which can slow down program startup considerably. Even though a Python bytecode file can automatically be created when importing a module, you can manually create them whenever you need, as well. In order to explicitly byte-compile a source file (.py) to a .pyc (or .pyo) bytecode file, you just need to execute the following code: import py_compile pycompile.compile("anyfilename.py") As you can see, the py_compile module provides a function called compile() that does all the jobs. The general syntax for this function is compile(file [, cfile] [, dfile]) where, The compileall module can be used either as a script or as a module. It uses the py_compile module to byte-compile all installed files (or all files in selected directories). The following example compiles all files from the current directory: import compileall.py compileall.compile_dir(".", force=1) You can also use this module as a script, passing arguments to it. The syntax for usage as a script is as follows: python compileall [-l] [-f] [-d destdir] [directory ...] where,
The script reads the directories that are informed as arguments and compiles all the files that it finds there. If no directory arguments are given, the routine uses the sys.path variable. Note that the current version doesn't recur down into subdirectories of a package. Another implementation detail is that it only recurs into the maximum number of 10 levels. (This number is hard coded in the module's code.) Also note that to generate both .pyc and .pyo files, you will need to run Python twice—once without the -O flag and once with it.
|
Index terms contained in this sectionbyetcodeexecutable generating compile() function 2nd compileall module executable bytecode generating functions compile() 2nd generating executable bytecode modules compileall py_compile 2nd scripts as py_compile module 2nd scripts modules as syntax compile() function 2nd modules as scripts sys.path variable variables sys.path |
© 2002, O'Reilly & Associates, Inc. |