Importing module from another subdirectory

dieter dieter at handshake.de
Thu Apr 25 02:07:24 EDT 2019


Rich Shepard <rshepard at appl-ecosys.com> writes:
>> bustrac/
>>    README.rst
>>    bustrac.py*
>>    controller/
>>    classes/
>          model.py
>>    scripts/
>>    gui/
>          test_act_de.py
>
> test_act_de.py tries to import model.py from the classes package:
> from classes import model as m
>
> Running in bustrac/ produces this error:
>
> $ python3 gui/test_act_de.py Traceback (most recent call last):
>   File "gui/test_act_de.py", line 1, in <module>
>     from classes import model as m
> ModuleNotFoundError: No module named 'classes'

The means that "test_act_de.py" has not extended "sys.path"
appropriately.


Repeated again:
"sys.path" controls where (absolute) imports look for
modules/packages to be imported. It is (typically)
a sequence of folders containing modules/packages.
It is initialized by the envvar "PYTHONPATH" (if it exists)
and python specific folders (e.g. to access Python's runtime library
and installation specific extensions).

When Python starts a script ("gui/test_act_de.py" in your case),
it automatically extends "sys.path" with the folder containing
the script ("gui" in your case).


If Python needs to find modules elsewhere, you must
extend "sys.path" to tell it where it should look.



More information about the Python-list mailing list