In this tutorial, we will learn how to compile a Python script on Linux. Compiling a Python script refers to converting plain-text Python script (.py file) into a binary (or executable) file.
The advantage of this is that the recipients of the executable won’t be able to easily read or edit the source code. We will use the PyInstaller utility, which allows you to create a standalone executable from your Python script.
With this tool, you can share your Python app without requiring users to have Python installed on their systems.
Step 1: Install PyInstaller
First, we need to install PyInstaller on our Linux system. You can install it using pip, the package installer for Python. Run the following command to install PyInstaller:
1 |
pip install pyinstaller |
If you don’t have pip installed on your system, you can follow this guide to install it.
Step 2: Write a Python script
Now that we have PyInstaller installed on our system, let’s write a Python script that we want to compile. For this tutorial, we will create a simple script called hello_world.py
. Create the script using your favorite text editor and add the following code:
1 2 3 4 5 |
def main(): print("Hello world!") if __name__ == '__main__': main() |
Save the file as hello_world.py
.
Step 3: Compile the Python script
With the Python script created, we can now use PyInstaller to compile it into an executable. Open your terminal and navigate to the directory where you saved the hello_world.py
file.
Run the following command to compile your Python script:
1 |
pyinstaller --onefile hello_world.py |
The --onefile
option is to tell PyInstaller to create a single executable file instead of creating a folder containing multiple files.
After the compilation is done, you will see a dist
folder created in the same directory as your Python script. Inside the dist
folder, you will find an executable file named hello_world
. This is the compiled version of your Python script.
Step 4: Run the compiled executable
Now that we have the compiled executable, we can test it. Open your terminal, navigate to the dist
folder, and run the compiled executable with the following command:
1 |
./hello_world |
If everything is done correctly, you should see the output:
Hello world!
Conclusion
In this tutorial, we learned how to install PyInstaller, write a simple Python script, compile that script into an executable, and finally run the compiled executable.
This process is helpful if you want to share your Python applications without requiring users to have Python installed on their systems or if you want to protect your source code from being easily read or edited.