How to Compile Python .py file without Executing?
Python is scripting language. Whenever you run code, first of all, the code is getting converted into byte code and save it as a .pyc file. This is the usual case. But if you want to compile Python .py file without executing it, I will shares tricks to do that in this post.
Let’s know little more about .py file.
When does .pyc file get created?
We import modules in our program. If you are importing module first time, Python compiles the module code and create .pyc file. It is nothing but the bytecode file.
In another scenario, if there is any change in code, python compile code and save it as bytecode (.pyc file) before running a python script.
.pyc files is created in the same folder where the .py file exists.
These are all usual ways, Python compiles and generate the .pyc file.
Why does compiling .py to .pyc not happen?
But there may have certain scenarios or mishap when python does not generate .pyc file.
This may occur in case you don’t have write permissions for the directory where you are compiling the code. It can also happen when you don’t have enough space to store bytecode (.pyc file).
In this case, if you are running Python code, it may run existing (old) .pyc bytecode. This is the worst behavior to trace. I still remember when I faced this issue. I was updating my code in a python script, but when I run the code, I was amazed not to see any changes in output even after doing changes in the python script.
And here is a way to a get rid of it.
Compile Python .py file without Executing:
So let’s see how to create a .pyc file just with a simple command.
For this, you can use two module for compiling python script.
py_compile and compileall modules.
Import py_compile in your python code. There is a function called compile(). Pass the python file name that you want to compile as an argument. It will convert python script into the bytecode (.pyc file).
import py_compile py_compile.compile('abc.py')
This will compile the abc.py file and saved compiled bytecode in abc.pyc file. Python stores bytecode in the same directory where the abc.py file exists.
Sometimes you may need to compile all the python script within given directory. Then this method is good rather than compiling each file independently.
In that case, run the following command in given directory.
python -m compileall
It will compile all the files in current directory.
If you are not providing any of the directories in command, it compiles all the python script found in sys.path.
Note, it will just compile Python .py file without executing.
If you are Python developer, you can give a look for all python codes we have shared on this blog.
In this post, I have not covered anything related to compiler and interpreter as it is not part of the scope of this article. If you are interested, you can read the difference between Compiler and Interpreter.