Как импортировать класс Python, который находится в каталоге выше?

Менеджеры знают все.

. По моему опыту, менеджеры не добились этого, зная код обычно. Неважно, что вы им скажете, это слишком долго, не правильно или слишком дорого.

И еще одно, что следует из первого:

Никогда не время делать все правильно, но всегда есть время сделать это снова

Хороший друг-инженер однажды сказал, что в гневе описать ситуацию, когда руководство уменьшило его оценки вдвое, вытащил из него недооцененную версию, а затем дал ему вдвое больше времени для доработки, потому что она не удалась. Это довольно обычная вещь в мире коммерческого программного обеспечения.

И тот, который пришел в голову сегодня при попытке настроить маршрутизатор только с веб-интерфейсом:

Веб-интерфейсы предназначены для присосок

CLI на предыдущем версия прошивки была ой как приятно. Эта версия имеет веб-интерфейс, который пытается скрыть всю сложность сети от невежественных ИТ-дроидов и даже не может правильно настроить VLAN.

176
задан CharlesB 25 February 2013 в 15:28
поделиться

2 ответа

Inside a package hierarchy, use two dots, as the import statement doc says:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328 deals with absolute/relative imports.

163
ответ дан 23 November 2019 в 20:22
поделиться

@gimel's answer is correct if you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on __file__ to find out the parent directory (a couple of os.path.dirname calls will do;-), then (if that directory is not already on sys.path) prepend temporarily insert said dir at the very start of sys.path, __import__, remove said dir again -- messy work indeed, but, "when you must, you must" (and Pyhon strives to never stop the programmer from doing what must be done -- just like the ISO C standard says in the "Spirit of C" section in its preface!-).

Here is an example that may work for you:

import sys
import os.path
sys.path.append(
    os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))

import module_in_parent_dir
73
ответ дан 23 November 2019 в 20:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: