Подтвердить что ты не робот

Импорт пакета Python из родительского каталога

У меня есть следующая структура исходного кода

/testapp/
/testapp/__init__.py
/testapp/testmsg.py
/testapp/sub/
/testapp/sub/__init__.py
/testapp/sub/testprinter.py

где testmsg определяет следующую константу:

MSG = "Test message"

и sub/testprinter.py:

import testmsg

print("The message is: {0}".format(testmsg.MSG))

Но я получаю ImportError: No module named testmsg

Не следует ли работать со структурой пакета? Я действительно не хочу расширять sys.path в каждом подмодуле, и я даже не хочу использовать относительный импорт.

Что я здесь делаю неправильно?

4b9b3361

Ответ 1

Все зависит от того, какой script вы запустите. Этот путь script будет автоматически добавлен в путь поиска python.

Сделайте следующую структуру:

TestApp/
TestApp/README
TestApp/LICENSE
TestApp/setup.py
TestApp/run_test.py
TestApp/testapp/__init__.py
TestApp/testapp/testmsg.py
TestApp/testapp/sub/
TestApp/testapp/sub/__init__.py
TestApp/testapp/sub/testprinter.py

Затем запустите TestApp/run_test.py:

from testapp.sub.testprinter import functest ; functest()

Тогда TestApp/testapp/sub/testprinter.py мог бы сделать:

from testapp.testmsg import MSG
print("The message is: {0}".format(testmsg.MSG))

Другие полезные подсказки здесь;

Ответ 2

Используйте относительный импорт, как показано ниже

from .. import testmsg

Ответ 3

У этого вопроса есть ответ - динамический импорт:

Как импортировать файл python в родительский каталог

import sys
sys.path.append(path_to_parent)
import parent.file1

Здесь что-то я сделал, чтобы что-то импортировать. Конечно, вы должны скопировать этот script в локальные каталоги, импортировать его и use путь, который вы хотите.

import sys
import os

# a function that can be used to import a python module from anywhere - even parent directories
def use(path):
    scriptDirectory = os.path.dirname(sys.argv[0])  # this is necessary to allow drag and drop (over the script) to work
    importPath = os.path.dirname(path)
    importModule = os.path.basename(path)
    sys.path.append(scriptDirectory+"\\"+importPath)        # Effing mess you have to go through to get python to import from a parent directory

    module = __import__(importModule)
    for attr in dir(module):
        if not attr.startswith('_'):
            __builtins__[attr] = getattr(module, attr)