Proper sys.path initialization when the main script is in a submodule

The first entry sys.pathis the directory of the current script, according to the docs . In the next setup, I would like to change this default value. Imagine the following directory structure:

src/
    core/
        stuff/
        tools/
            tool1.py
            tool2.py
    gui/
        morestuff/
        gui.py

Scripts tool*.pyand gui.pyare designed to run in the form of scripts, for example:

python src/core/tools/tool2.py
python src/gui/gui.py

Now all tools are imported from src.core.stuff, and a graphical interface is required gui.morestuff. This means that it sys.path[0]should point to src/, but by default it points to src/core/tools/or src/gui/.

I can configure sys.path[0]in each script (with a construction similar to the following, for example, at the beginning gui.py):

if __name__ == '__main__':
    if sys.path[0]: sys.path[0] = os.path.dirname(os.path.abspath(sys.path[0]))

, . -m:

python -m gui.gui

, src/.

, . __init__.py?

EDIT: Python 2.7:

~$ python -V
Python 2.7.3
+5
3

. . . , - .

, , ./src python. python.

PYTHONPATH

, python - PYTHONPATH. , - :

PYTHONPATH=/src python src/gui/gui.py

, , , , PYTHONPATH. , , . 3 , cron.

, . , src /usr/lib/python2.7/site-packages , site-packages.

, .

, , , . , python . . python. , .

, .pth - -. python , ( ) . .

virtualenv

- python. , , virtualenv pip, ( ) python.

virtualenv site-packages , , . virtualenv , python, , , .

, setup.py, pip ( python) virtualenv. :

!/usr/bin/env python
# -*- coding: utf-8 -*-

from distutils.core import setup


setup(
    name='myproject',
    package_dir={'myproject': 'src'},
    scripts=['src/gui/gui.py', 'src/core/tools/tool1.py', 'src/core/tools/tool2.py']
)

, , :

virtualenv env
env/bin/pip install -e setup.py

script, - :

env/bin/tool1.py
+4

script, , - -m. script sys.path script, , , . script , sys.path, . sys.path, .

python -m mypackage.mymodule , (src ), , Python. , , . src - .

, - PYTHONPATH, src, .

( ​​ .profile, .bashrc ) . , , , script.

+5

, PYTHONPATH

, Python sys.path, site, ( ) Python.

site.py...

# Prefixes for site-packages; add additional prefixes like /usr/local here
PREFIXES = [sys.prefix, sys.exec_prefix]

... , , , , sys.path, . .pth - site-packages.

, , " ", , .

, , .

. , Python - . Ubuntu...

~$ dpkg -L python-imaging | grep pth
/usr/share/pyshared/PIL.pth
/usr/lib/python2.7/dist-packages/PIL.pth

... but if your intention is to simplify the work of several parallel developers, each using their own system, you might be better off sticking to the current option of adding some “boilerplate” code for each Python module, which is designed to run as a script .

There may be another option, but it depends on what you are trying to achieve.

+1
source

All Articles