1

This question already has an answer here:

I was trying to set up my Mac to run custom Python scripts from anywhere without having to type python [script.py] or the explicit file path.

The script is called "testscript". I put the script in my own bin directory (separate from /usr/local/bin), called /User/Patrick/bin, and added it to my path so when I type echo $PATH it comes up correctly like so:

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/User/patrick/bin:/usr/local/go/bin`. 

I already added the line #!/usr/bin/env python to the top of the file, I already did chmod 700 testscript, but I still can't call testscript from anywhere. Have things changed since OSX Yosemite?

marked as duplicate by bmike macbook May 22 at 0:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Case may matter, is it Patrick or patrick? Also, what error message are you getting? Does running it via ~/bin/testscript work? – nohillside Jan 26 '15 at 18:16
  • No @patrix, OS X is case-insensitive. – DisplayName Jan 26 '15 at 18:22
  • 1
    Ah, probably, yes. But it's /User**s**, at least here. – nohillside Jan 26 '15 at 18:39
  • @partix Yeah, thats right, certain UNIX tools are case sensitive. – DisplayName Jan 26 '15 at 19:45
  • @patrix Wow, that was it... I just noticed that on OSX it says "Users" instead of "User"... It works now, thanks. – Coach Pat Jan 26 '15 at 21:29
2

Make sure the script is executable. chmode +x filename

Make sure the script has the appropriate shebang line at the top: #!/usr/bin/env python

Double check the path, it should be /Users (note the s at the end)

1

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!

Not the answer you're looking for? Browse other questions tagged .