1

I am using MacOSX Yosemite, I am trying to execute a python code without always typing the path or getting into the folder. I tried the following :

1) Added the line #! /usr/local/bin/python (after finding where the python is found)
2) sudo chmod a+x full_file_path

But this does not work for me. Nor

 export PYTHONPATH=full_file_path

How else can I execute the python script without actually getting into the directory. I cannot also execute the script without using ./ the chmod does not change the access to executable. Which as far as I have seen many forums. It should.

user89
  • 129
  • 1
  • 3
  • 11

2 Answers2

0

You need to add full_file_path to your shell PATH variable. It is your shell that does the searching for the script, not Python. Only when the script has been found, is Python being started:

export PATH="full_file_path:$PATH"

You can add that line to your .bash_profile or .profile file in your home directory to make this addition permanent.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Perfect ! I was in a misunderstanding from reading some forums. Thanks :) – user89 Dec 06 '14 at 12:44
  • But exporting the `PATH` is only temporary, I can't execute python script again if I close the terminal. Is there no possibility to make it permanent. So that shutdown or closing the terminal doesn't affect it? – user89 Dec 06 '14 at 12:49
  • @user89: add it to your `.profile` file in your home directory. – Martijn Pieters Dec 06 '14 at 12:51
  • I tried as your suggestion but it doesn't work. I did add the path to .profile and logged out and tried to access the file but couldn't but I did the same in the command line and it worked but only until I close the terminal. I am unsure what is the issue here.. – user89 Dec 06 '14 at 13:13
  • i did export PATH=full_path_to_file in terminal. It works for that terminal session. But adding the same to .profile does not work. Is there any reason behind it? – user89 Dec 06 '14 at 13:14
  • @user89: are there any other `PATH` exports in your `.profile` or `.bash_profile`? Did you put the `.profile` file in the correct location? Only *new* terminal sessions will see the `.profile` change unless you use `source ~/.profile` to explicitly load the contents. – Martijn Pieters Dec 06 '14 at 13:43
0

Run these commands without the $ signs in the front:

$ ls -l /full/directory/progname.py
$ chmod +x /full/directory/progname.py
$ ls -l /usr/local/bin/python 
$ export PATH="$PATH:/full/directory"
$ progname.py 

If any of the ls commands display an error message, then you are looking for the file in the wrong place, and you have to find the correct location, and update the command accordingly.

It's important to note that /usr/local/bin/python can also be wrong, for example some systems have the Python interpreter in /usr/bin/python.

pts
  • 80,836
  • 20
  • 110
  • 183