1

Say I have the following tree:

~/python
  ├── one
      └── toto.py
  └── two
      └── toto.py

Even after export PATH=$PATH:~/python, I can't seem to be able to run python one/toto.py and python two/toto.py from anywhere else than ~. Is there a way to do that? Thanks!

3
  • 1
    it's looking for the file from your current directory Commented Nov 17, 2015 at 15:26
  • File "opens" doesn't not coexist within the same rule set as file executions. To open a file you will need at the very least a relative path like ~/python/one/toto.py. the $PATH variable is parsed by the shell itself when trying to find executables. You could create a python script that you mark as executable that tries to do this for you. by using os.path.abspath(...) to and use sys.path to find modules that it can import and "hand over" to. Commented Nov 17, 2015 at 15:33
  • The PATH variable will only affect where the shell finds the executable, python in your case. It doesn't affect where python will look for files to run Commented Nov 17, 2015 at 15:33

2 Answers 2

3

One way you might be able to accomplish what you want is to use PYTHONPATH instead of PATH. Then, you can tell the interpreter to run a module instead of the script directly. For example:

$ export PYTHONPATH=$PYTHONPATH:~/python
$ python -m one.toto
$ python -m two.toto

Note that we don't include the extension and the separator has changed from / to . because we're now dealing with python modules, not filesystem paths.

Sign up to request clarification or add additional context in comments.

Comments

1

As mentioned in the comments.

$PATH in Linux is used to find a executable. In this case that's Python.
After this executable is found, it will be executed "in" the current working directory and work from there.

Meaning when Python gets the parameter one/toto.py it will start looking from ./ after your folder and file.

You could create a wrapper script, place that under /usr/bin/mywrap.py, mark it as a executable and utilize for path in sys.path: and try to find your module and dynamically import it and do a "hand over" to it.

There is no magic in the Python binary that will travers $PATH since this is a shell variable used to find binaries in the operating system. Much like PATH in windows is used for the same purpose.

Comments

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.