虽然我认为这应该很简单,但我还是不能让它运行。
我的文件夹结构如下:
├── apartment
│ ├── src
│ ├── train_model
│ ├── __init__.py
│ ├── train_model.py
│ ├── utils.py
│ ├── interference.py
│ └── __init__.py在utils.py中,我尝试了:
from src.interference import create_sample错误: ModuleNotFoundError:没有名为“src”的模块
from .interference import create_sample错误: ImportError:尝试使用没有已知父包的相对导入
from interference import create_features_sampleModuleNotFoundError:没有名为“干扰”的模块
怎样才能让它发挥作用呢?我不太喜欢非节奏式的方式,因为它看起来很脏。
发布于 2020-02-12 10:29:04
以src/开头的结构显式地旨在不启用from src.intereference import ...的导入,您不应该将__init__.py文件放在src/文件夹中。
相反,下面是很好的解释和示例:https://blog.ionelmc.ro/2014/05/25/python-packaging/,下面是我推荐的内容:
- add a `setup.py` file at root of your folder (this is clearly not as hard as it seems)
- maybe create a virtual environment
- using `pip install -e .` (with trailing dot!) command
然后,简单地通过from interference import ...导入您的包
为了响应您的主要请求,您可以使用src/__init__.py更新from intereference import create_sample,以便在更高的级别公开这个函数,然后链式导入就可以工作了。但是,我不建议这样做,因为它使一切变得非常僵化。
发布于 2020-02-12 10:24:35
您需要将包含干扰的目录添加到PYTHONPATH。
您可以在sys.path中列出的“模块搜索路径”中使用OS依赖路径。因此,您可以轻松地添加父目录,如下所示:
import sys
sys.path.insert(0, '..')
from interference import create_features_sample请注意,前面的代码使用相对路径,因此必须在同一位置启动文件,否则可能无法工作。要从任何地方启动,您可以从Path模块中使用pathlib。
from pathlib import Path
import sys
path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)
from interference import create_features_samplehttps://stackoverflow.com/questions/60186055
复制相似问题