这是我第一次真正坐下来尝试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'

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


当前回答

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

__init__.py file

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

其他回答

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

__init__.py file

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

对我来说,简单地添加当前目录就可以了。

使用以下结构:

└── myproject
    ├── a.py
    └── b.py

a.py:

from b import some_object
# returns ModuleNotFound error

from myproject.b import some_object
# works

这个例子适用于Python 3.6。

我建议在PyCharm中运行->编辑配置,删除那里的所有条目,并尝试通过PyCharm再次运行代码。

如果不工作,检查你的项目解释器(设置->项目解释器)和运行配置默认值(run ->编辑配置…)。

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

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

如果你使用的是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)