Generating an Executable Python Bytecode - Python

When 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- ompilesthe module, and in case the permissions given to the user who is executing the command allow, a bytecompiled version of the module is saved in the disk for a later user. Note that it is a good idea tobytecompile 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

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])


Generating an Executable Python Bytecode

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:

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


syntax for usage as a script

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.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Python Topics