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.
& 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.
& gt; & gt; & gt; import py_compile & gt; & gt; & gt; py_compile.main ([`File1.py`,` File2.py`, `File3.py`])
& gt; & gt; & gt; import compileall & gt; & gt; & gt; compileall.compile_dir (directoryname)
$ python -m py_compile File1.py File2.py File3.py ... pre>
Or to compile files interactively$ python -m py_compile - File1.py File2.py File3.py. ... ...
$ python -m compileall pre>
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.
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.