How do I make a python file executable on macOS Sierra?

Try the following and let me know how you go:

  1. Ensure the first line of your Python script is #!/usr/bin/env python
  2. Change the extension of the file to .command (i.e. If the file you want to make executable is called Test.py, change it to Test.command)
  3. In Terminal make the Python script file executable by running chmod +x Test.command (obviously the Test.command will be whatever your file is from Step 2 above).

By following the above steps, you should be able to double-click your Python script within macOS Sierra and it will open a terminal window and run the script.


Install pyinstaller: pip install pyinstaller

Create executable: pyinstaller --onefile yourscriptname.py

This worked for me on MacOS Mojave 10.14.2


Which python are you targeting?

Did you install it with brew? It uses a different path.

which python3 or which python

Choose the one you want

Copy that output

Paste it at the top of your python file

add a #! in front of that path so it looks something like

#!/usr/local/bin/python3

Make sure to change the file permissions

chmod +x filename

Put that file in a folder that is in your path

Not sure if your folder is in your path?

echo $path

How to add that folder to your path?

Find your path first

echo $HOME

If you are using bash or zsh you might have something like this

In ~/.bash_profile or ~/.bashrc or ~/.zshrc at the bottom of your file

export PYTHON_UTILS="$HOME/code/python/utils"

export PATH="$PYTHON_UTILS:$PATH"

Consider removing the .py from your file bc it is not needed in this case

Close and open your terminal, which is sourcing your file by its path

And now you should be able to treat your python file similar to a bash command

You don't need to use python3 filename.py to run the file, you can just use filename

From anywhere on your filesystem!

Tags:

Python

Macos