Hello. How can sys.path add relative paths to find modules?

    2 answers 2

    Interested, asked Google. http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html

    For example, to add the directory / home / me / mypy in the path, just run:

     import sys sys.path.append("/home/me/mypy") 

    There is also the PYTHONPATH environment variable in which you can specify a list of directories separated by ':' for sys.path

    There was such a question on stackoverflow , read. It should be enough to add an empty __init__.py to the directory ./src and import src.modulllll to your program for the module modulllll (the current directory in the search is). Or sys.path.append('src') and import modulllll

    • Thank you, but I would like to know how to work with relative paths. For example, if you write sys.path.append ("./ src"), where src is a directory with some modules, these modules are not imported. Are there any other options for importing modules not from the current directory? - Olegas
    • Posted in reply - alexlz

    The sys.path [0] contains the path to the directory in which the script is located, so the relative paths (and absolute paths too) can be added like this:

     import sys import os sys.path.append(os.path.join(sys.path[0], '../../modules'))