How To Make Python Script Executable

Creating an executable file from your Python script is an excellent way to share your code with others who may not
have Python installed on their systems. In this blog post, we will discuss the steps to make your Python scripts
executable on different platforms, such as Windows, macOS, and Linux. Let’s get started!

1. Adding a Shebang Line

Before converting your Python script into an executable, you must add a “shebang” line at the very beginning of
your script. This line tells the system which interpreter to use for running the script. For Python, you can use
the following shebang line:


#!/usr/bin/env python3

Note: If you are using Python 2, replace python3 with python in the shebang
line.

2. Making the Script Executable in Linux and macOS

If you are using a Linux or macOS system, follow these steps to make your Python script executable:

  1. Open a terminal and navigate to the directory where your script is stored using the cd
    command.
  2. Run the following command to make your script executable:

    chmod +x your_script.py

    Replace your_script.py with the name of your Python script.
  3. Now you can execute the script by running:

    ./your_script.py

3. Creating an Executable for Windows

To create an executable file for Windows, you can use a third-party tool called PyInstaller.
Follow these steps to create an executable using PyInstaller:

  1. Install PyInstaller using pip by running the following command in your command prompt:

    pip install pyinstaller
  2. Navigate to the directory containing your Python script using the cd command.
  3. Run the following command to create an executable file from your script:

    pyinstaller --onefile your_script.py

    Replace your_script.py with the name of your Python script.
  4. After the process is completed, you will find the executable file in the dist folder within
    the directory of your script.

Conclusion

In this blog post, we’ve discussed how to make your Python scripts executable on Windows, macOS, and Linux
platforms. This will allow you to share your Python programs with others more easily and enable them to run your
code without installing Python or any dependencies. Happy coding!