Compiling python source code into byte-code

Normally, when a python module is imported, python automatically generate a .pyc file containing the compiled byte code. The next time the same program is run, the compilation step can thus be skipped.

However, in order to manually pre-compile the python modules even before running them, here are two ways of doing it:

  1. Use a python script.

    To compile a single file / module, use the py_compile module.

    import py_compile
    if __name__ == "__main__":


    To compile all files in a directory, use the compileall module.

    import compileall
    if __name__ == "__main__":


  2. Execute on a shell / command line.

    The compileall module can also be invoked as a script. On the command line, type:

    python -m compileall Lib\