Ignorant new Linux/Ubuntu/StackOverflow user here.
I have my scripts for users to run in a path like /home/user/Projects/scripts/. If that is the pwd, I can invoke a script like this:
~/Projects/scripts$ python2.7 scriptname.py
(I am using python 2.7 because of legacy code.)
I want the users to not be forced to set the pwd to that directory to run scripts, just let them run from /home/user after logging in. Like this:
~$ python2.7 scriptname.py
Also, there are several directories with scripts, I am simplifying for this example.
I edited bash.rc to set PYTHONPATH to include that directory, then logged back in. The environment variable is set, but I can't invoke the script from the home directory. I get
python2.7: can't open file 'script': [Errno2] No such file or directory
sys.path includes the path to the scripts directory. If I start python 2.7 from the home directory and import a script as a module, it finds it:
~$ python2.7
>> import script
>>
But I can't get the command line to find it.
If I include the entire path on the command line, it works:
~$ python2.7 /home/user/Projects/scripts/scriptname.py
Should I be able to do this? What am I doing wrong?
Instead of helping python find the script, you should let the shell find the scripts and let the script find python.
Edit the scripts to begin with the line
#!/usr/bin/env python2.7
or if you prefer, write the actual path to python 2.7 like this:
#!/path/to/the/python2.7
Make the scripts executable:
chmod +x scriptname.py
Add the directory containing the scripts to the variable PATH
(not PYTHONPATH
) by putting this in your bash.rc
(or .bashrc
etc.):
export PATH="$PATH:/home/user/Projects/scripts"
Start a new shell or terminal session.
Once you've done that, you'll be able to run your scripts by just typing
~$ scriptname.py
at the prompt.
scriptname.py
to scriptname
, since the end-users users don't need to worry about what interpreter to run it with.