0

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?

1
  • The environment variable you're looking for is PATH, not PYTHONPATH. Commented May 22, 2024 at 12:32

1 Answer 1

0

Instead of helping python find the script, you should let the shell find the scripts and let the script find python.

  1. 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
  1. Make the scripts executable:

    chmod +x scriptname.py 
    
  2. 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"
    
  3. 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.

  1. Optional: At this point you can also rename scriptname.py to scriptname, since the end-users users don't need to worry about what interpreter to run it with.
Sign up to request clarification or add additional context in comments.

3 Comments

OK, makes sense - will I be able to hand the script command line options for argparse?
Yes, everything should work out the same.
... and yes, everything works out the same. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.