How do I make my python file executable from anywhere in my system and without having to say "python3" and ".py" before and after the file name

Solution 1:

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.

Solution 2:

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"