How To Make A Python Script Executable

In this tutorial, you will learn how to make a Python script executable, meaning you can run the script simply by clicking on it, instead of opening a terminal and running the script using the python command. This can be especially helpful when running your script on other users’ systems, or if you aim to create a more user-friendly experience.

Step 1: Write a Simple Python Script

Create a simple Python script, and save it as hello_world.py with the following content:

This script will simply print ‘Hello, World!’ when executed.

Step 2: Add Shebang to Python Script

Add a shebang line at the beginning of your Python script. This line tells the system the path to the Python interpreter that should be used to execute the script.

Open hello_world.py in a text editor and add the following line at the beginning of the file:

The updated script should look like this:

Step 3: Make the Script Executable

Now, you need to make the Python script executable by adding execute permissions to the file. To do this, open a terminal, navigate to the directory containing hello_world.py, and run the following command:

This command gives execute permission to the owner of the file.

Step 4: Run the Executable Python Script

Now that the script is executable, you can run it by entering the following command in the terminal:

Alternatively, you can double-click the file, and the system will use the specified Python interpreter to execute the script (depending on your system’s configuration).

The output should look like this:

Hello, World!

Step 5: Create a Standalone Executable (Optional)

If you want to distribute your script without requiring users to have Python installed, you can create a standalone executable using the PyInstaller package. First, you need to install PyInstaller using the following command:

Once installed, use the following command to create a standalone executable:

This will generate an executable named hello_world (on Linux or macOS) or hello_world.exe (on Windows) in the dist directory. You can then distribute this executable without requiring users to have Python installed on their systems.

Conclusion

In this tutorial, you learned how to make a Python script executable by adding a shebang and giving the script execute permissions. This enables users to run the script with a simple click or command in the terminal. Optionally, you can create a standalone executable using PyInstaller to distribute your script without requiring Python installation.