How to extend sys.path using files?

不想你离开。 提交于 2020-01-04 15:46:20

问题


I'm using a python environment (iOS Pythonista) that does not have setuptools so setup.py within a python packages will not run. There is a site-packages dir that is added to sys.path. I'm looking for a clever way to gunzip packages from pypi into site-packages without having to move the actual package with the __init__.py into site-packages. I'd like to keep the folder with all the documentation in site-packages. Is there a way to use __init__.py or another python reserved file to extend the sys.path?

A simplified pypi package structure:

MyPackage-1.10.0/
    mypackage/
        __init__.py
        somethinga.py
    setup.py

Current way: Move mypackage into site-packages, discard the rest.

Or is there a way to use something like site-packages/__init__.py to add sys.path's for the package folders when site-packages is added to sys.path?


回答1:


You can create one ore more .pth files in site-packages; their contents will be added to sys.path when present.

From the site module documentation:

A path configuration file is a file whose name has the form name.pth and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to sys.path. Non-existing items are never added to sys.path, and no check is made that the item refers to a directory rather than a file. No item is added to sys.path more than once. Blank lines and lines beginning with # are skipped. Lines starting with import (followed by space or tab) are executed.

Use it to add the full or relative paths to package directories to sys.path.

For example, for your MyPackage-1.10.0 package, all you need is a MyPackage-1.10.0.pth file with the contents MyPackage-1.10.0 on a line by itself for Python to add the full directory path to sys.path.



来源:https://stackoverflow.com/questions/27696627/how-to-extend-sys-path-using-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!