0

I have python script running under different python executable than default one.

I have python executables both in /usr/bin and in /mydir/mybins.

If I run, I get:

$which python
/usr/bin/python

And if run run.py:

# cat run.py
#!/usr/bin/env /mydir/mybins/python

import os
import sys

print(u"Python executable: %s" % sys.executable)
print(u"From within Python PATH=%s" % os.environ[u"PATH"])

I get

# ./run.py
Python executable: /mydir/mybins/python
From within Python PATH=/usr/bin:... (and no /mydir/mybins)

Why? Is this by design? How can I make it use /usr/bin/python without changing the code?

  • Is the line # cat run.py part of the run.py file? – andcoz Jun 13 at 13:48
  • ... that is not how #! /usr/bin/env is intended to be used. Are you sure you can't change the shebang? – muru Jun 13 at 13:50
  • 1
    The correct shebang is #!/usr/bin/env python, because this will trigger the program env with the argument python. – Panki Jun 13 at 13:50
5

The env utility will execute its argument as a command.

If the argument is not given with a path, as in env python, the command will be looked up in $PATH. This is usually what you want when using env in the #!-line of a script.

If the argument is given with a path, it will execute the command at that path.

In your #!-line, you execute a specific Python interpreter. The $PATH will never be searched. You might just as well have had

#!/mydir/mybins/python

as the env bit is in effect doing nothing.

To let the $PATH have effect, use

#!/usr/bin/env python

The first python executable found in $PATH will then be used.

An alternative is to bypass the #!-line completely by executing the script with an explicit interpreter on the command line:

$ python run.py

or,

$ /usr/bin/python run.py
0

As Kusalananda has said you are specifically telling your script to use /mydir/mybins/python. You want to know how to make it use /usr/bin/python without changing the code that points specifically to a different python?

You can accomplish this by removing /mydir/mybins/python and making a symlink to /usr/bin/python in its place. I strongly do not recommend this but instead recommend you change the hashbang in your script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.