Home > Mobile >  How do I make my python file executable from anywhere in my system and without having to say "p
How do I make my python file executable from anywhere in my system and without having to say "p

Time:01-24

I am trying to make my python3 file executable from any location in the terminal (on mac os) so that instead of:

python3 myFile.py argv1 argv2 argv 3

Instead you type

myFile argv1 argv2 argv3

I can make the file executable via ./myFile but that's not really what I'm looking for and I can't make it executable from anywhere in the system.

CodePudding user response:

To make it executable without saying python first, put

#!/usr/bin/env python

as the first line and make the file executable.

To make it executable from any location, put the script in a directory that's in your $PATH environment variable.

CodePudding user response:

Type which python3 to uncover where you have your python executable. In my case it is /usr/local/bin/python3 directory.

Your python file should contain a shebang referencing the executable as the first line in the file. So, for example:

#!/usr/local/bin/python3

Next, you must make sure that the file itself is executable.

Some files have different permissions (files can be read / write / execute and by different groups user / group / everyone). Execute on the terminal sudo chmod x your_python_file.py.

Finally, you should add the directory where your file script is saved to your system $PATH.

In your terminal execute:

cd $HOME && mkdir bin

Put your python script in this bin directory. Then add the bin directory to your system $PATH by running:

export PATH="$HOME/bin:$PATH"
  •  Tags:  
  • Related