osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Import module from a different subdirectory


Rich Shepard <rshepard at appl-ecosys.com> writes:
>> The project directory contains subdirectories, including gui/ (with the
>> tkinter views) and classes/ with the SQLAlchemy model.py.
> ...
> Second, in ~/.bash_profile I added two lines, the first is the project's
> root directory:
>
> PYTHONPATH=$HOME/development/bustrac
> export PYTHONPATH
>
> Testing this suggests that python is finding the path:
>
> $ python3
> Python 3.7.3 (default, Mar 26 2019, 06:40:28) [GCC 5.5.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import os
>>>> os.environ["PYTHONPATH"]
> '/home/rshepard/development/bustrac'

Test this by looking at "sys.path" instead:

>>> import sys
>>> sys.path

It is "sys.path" which actually controls the import machinery.

> ...
> Do I need to specify each bustrac/ subdirectory in the PYTHONPATH? If not,
> what am I still missing?

This depends on how you make the import.

"sys.path" is typically a sequence of folders. Python's
import machinery will look in those folders for modules/paackages for its
(absolute) imports.
Thus, if you use "import XXXX" or "from XXXX import ...",
then one of those folders should contain a module or package
named "XXXX".