从父目录导入脚本

如何导入驻留在父目录中的模块(python 文件) ?

两个目录都有一个 __init__.py文件,但我仍然不能从父目录导入一个文件?

在此文件夹布局中,脚本 B 试图导入脚本 A:

Folder A:
__init__.py
Script A:
Folder B:
__init__.py
Script B(attempting to import Script A)

脚本 B 中的以下代码不起作用:

import ../scriptA.py # I get a compile error saying the "." is invalid
175645 次浏览

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
├── __init__.py
├── moduleA.py
└── subpackage
├── __init__.py
└── moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.