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!

Torxed
  • 22,866
  • 14
  • 82
  • 131
Martin
  • 361
  • 4
  • 12
  • 1
    it's looking for the file from your current directory – Eamonn McEvoy Nov 17 '15 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. – Torxed Nov 17 '15 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 – Eric Renouf Nov 17 '15 at 15:33

2 Answers2

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.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
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.

Community
  • 1
  • 1
Torxed
  • 22,866
  • 14
  • 82
  • 131