How do I generate a bytecode file in Python?



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 abc.py, that imports another module xyz.py. Now run the file abc.py , xyz .pyc will be generated because xyz is imported, but abc.pyc will not be generated because abc.py 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 (`abc.py`) 

    This will write .pyc to the same location as abc.py.

  2. Using py_compile. main () : compiles multiple files at the same time.
     & gt; & gt; & gt; import py_compile & gt; & gt; & gt; py_compile.main ([`File1.py`,` File2.py`, `File3.py`]) 
  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 File1.py File2.py File3.py ...  

    Or to compile files interactively

     $ python -m py_compile - File1.py File2.py File3.py. ... ... 
  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.

Links:
1. https://docs.python.org/3/library/py_compile.html
2.
https://docs.python.org/2/library/compileall.html
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 contribute.python.engineering or by posting an article contribute @ python.engineering. See your article appearing on the Python.Engineering homepage and help other geeks.