How do I generate a bytecode file in Python?

File handling | Python Methods and Functions

Bytecode is loaded at runtime in Python and interpreted by the virtual machine, which is a piece of code that reads each instruction in the bytecode and performs any specified operation.

The bytecode is automatically generated in the volume the same directory as the .py file when the python module is imported for the first time, or when the source is later than the currently compiled file. The next time the program is run, the Python interpreter will use this file to skip the compilation step.

Running the script is not considered a import and no .pyc file will be generated. For example, let's write a script file, that imports another module Now run the file , xyz .pyc will be generated because xyz is imported, but abc.pyc will not be generated because is not imported.

But there are built-in modules and commands py_compile and compileall that make it easier to create a pyc file.

  1. Using the py_compile.compile : The py_compile module can manually compile any module. One way is to interactively use the py_compile.compile function in this module:
     & gt; & gt; & gt; import py_compile & gt; & gt; & gt; py_compile.compile ('') 

    This will write .pyc to the same location as

  2. Using py_compile. main () : compiles multiple files at the same time.
     & gt; & gt; & gt; import py_compile & gt; & gt; & gt; py_compile.main (['','', '']) 
  3. Using the compileall.compile_dir () function: compiles every python file present in the provided directory.
     & gt; & gt; & gt; import compileall & gt; & gt; & gt; compileall.compile_dir (directoryname) 
  4. Using py_compile in terminal:
     $ python -m py_compile ... 

    Or to compile files interactively

     $ python -m py_compile - ... ... 
  5. Using compileall in a terminal: This command will automatically recursively navigate to subdirectories and create .pyc files for all python files it finds.
     $ python -m compileall 

Note . The compileall and py_compile module is part of the python standard library, so you don't need to install anything extra to use it.

3. Effbot

This article courtesy of Shubham Bansal . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See your article appearing on the Python.Engineering homepage and help other geeks.