Import file from parent directory?

I have the following directory structure:

application
tests
main.py
main.py

application/main.py contains some functions.

tests/main.py will contain my tests for these functions but I can't import the top level main.py. I get the following error:

ImportError: Import by filename is not supported.

I am attempting to import using the following syntax:

import main

What am I doing wrong?

157303 次浏览

您不能像这样从父目录/兄弟目录导入内容。您只能从系统路径上的目录、工作目录或包中的子目录导入内容。因为您没有 __init__.py文件,所以您的文件不会形成一个包,您只能通过将它们放置在系统路径上来导入它们。

您必须将应用程序目录添加到您的路径:

import sys
sys.path.append("/path/to/dir")
from app import object

或者来自 Shell:

setenv PATH $PATH:"path/to/dir"

如果你使用窗口: 在 窗户中向路径添加变量。

或者从命令行:

set PATH=%PATH%;C:\path\to\dir

请注意 PYTHONPATHPATHsys.path之间的区别。

首先,您需要将目录添加到包中,方法是添加 __init__.py文件:

application
tests
__init__.py
main.py
__init__.py
main.py

Then you should make sure that the directory above application is on sys.path. There are many ways to do that, like making the application infto a package and installing it, or just executing things in the right folder etc.

那么你的进口货就会起作用。

如果您希望您的脚本具有更强的可移植性,可以考虑自动查找父目录:

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# import ../db.py
import db

存在于同一目录中,. . 存在于父目录中 to import a file from parent directory you can use ..

从. . import 文件名(没有. py 扩展名)

要导入父目录的另一个子目录中的文件,可以尝试这样做:

sys.path.append(os.path.abspath('../other_sub_dir'))
import filename_without_py_extension

编辑: 缺少闭括号。

聚会迟到了——不幸的是,这里的大多数其他答案都不正确——除了 LennartRegebro's(和布伦巴恩的)是不完整的。为了将来的读者的利益-OP 首先应该像下面这样添加 __init__.py文件

root
application
__init__.py
main.py
tests
__init__.py
main.py

然后:

$ cd root
$ python -m application.tests.main

或者

$ cd application
$ python -m tests.main

直接从包内部运行脚本是一种反模式——正确的方法是使用根包的父目录中的 -m开关运行——这样就可以检测到所有的包,并且相对/绝对导入可以按预期工作。