How to compile py to pyc?

This article is for Python beginners who wish to study how to compile Python souce code (.py files) to Python bytecode (.pyc files).

This article will introduce 3 methods to compile PY to PYC, all of which can be used on both Python2 and Python3.

1. import

import is a built-in Python statement, it can be used directly in any Python version.

Python automatically compiles Python source code when a module is imported, so the easiest way to create a PYC file is to import it, as following:

>>> import yourfilename # Import yourfilename.py file

The bad point by using this method is that it doesn’t only compile the module, it also executes it, which may not be what you want.

Following I will introduce another 2 methods which don't execute Python code, only compile it.

2. py_compile

py_compile is a standard library which is available both on Python2 and Python3.
It can be used directly without installing any third-party libraries.

This module is mainly for compiling single Python source file.

  • It can be run as a script in terminal:
    $ python -m py_compile yourfilename.py # Compile single Python source file,
    $ python -m py_compile yourfilename1.py yourfilename2.py # or compile multiple Python source files.
    
  • or, be called as an API in Python module:
    >>> import py_compile
    >>> py_compile.compile('yourfilename.py') # Compile single Python source file,
    >>> py_compile.main(['yourfilename1.py', 'yourfilename2.py']) # or compile multiple Python source files.
    

There are several arguments which can control the compilation (e.g. optimization level), please check the official documentation (Python2 or Python3).

3. compileall

compileall is also a standard library which is available both on Python2 and Python3.
It can be used directly without installing any third-party libraries.

This module is mainly for compiling all Python source files in a directory tree recursively, it also can compile single Python source file.

  • It can be run as a script in terminal:
    $ python -m compileall . # Recursively compile all Python source files in a directory tree,
    $ python -m compileall yourfilename.py # or compile single Python source file.
    
  • or, be called as an API in Python module:
    >>> import compileall
    >>> compileall.compile_dir('.') # Recursively compile all Python source files in a directory tree,
    >>> compileall.compile_file('yourfilename.py') # or compile single Python source file.
    

There are several arguments which can control the compilation (e.g. optimization level), please check the official documentation (Python2 or Python3).

Summary

This article introduced 3 methods to compile Python source file: import, py_compile and compileall, the latter the better for usage.

ATTENTION: PYC file is not security, do not protect your Python source code via PYC file, it can be very easily decompiled by a Python Decompiler.

Back to homepage or read more recommendations: