这是我第一次真正坐下来尝试python 3,而且似乎失败得很惨。我有以下两个文件:

test.py config.py

py中定义了一些函数和一些变量。我将其归纳为以下几点:

config.py

debug = True

test.py

import config
print (config.debug)

我还有一个__init__.py

然而,我得到以下错误:

ModuleNotFoundError: No module named 'config'

我知道py3约定使用绝对导入:

from . import config

然而,这会导致以下错误:

ImportError: cannot import name 'config'

所以我不知道该怎么做……任何帮助都非常感激。:)


当前回答

根据我的经验,PYTHONPATH环境变量并不是每次都有效。

在我的例子中,我的pytest只在添加绝对路径时工作: sys.path.insert ( 0,“/用户/ bob /项目/回购/λ” )

其他回答

您可以使用这些语句来设置工作目录,这对我使用python3是有效的

import os
import sys
sys.path.insert(1, os.getcwd())

您可以简单地将以下文件添加到测试目录,然后python将在测试之前运行它

__init__.py file

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

尝试你的例子

from . import config

得到如下SystemError: /usr/bin/python3.4 test.py 回溯(最近一次调用): 文件"test.py",第1行,在 从。导入配置 SystemError:父模块未加载,不能执行相对导入


这对我来说很有用:

import config
print('debug=%s'%config.debug)

>>>debug=True

使用Python测试:3.4.2 - PyCharm 2016.3.2


除此之外,PyCharm还提供了导入此名称的功能。 你必须点击配置,然后出现一个帮助图标。

如果你使用的是python3 +,那么尝试添加下面的行

import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)

我看到很多答案导入了sys和os。这是GitHub副驾驶给我的一个没有提到的更短的:

import sys

sys.path.append(__file__.rsplit("/", 1)[0])

将此添加到我的python脚本顶部也解决了这个问题。