繁体   English   中英

无法从另一个目录导入文件,该目录从同一目录导入文件(int Python)

[英]Can't import file from another directory which imports a file from the same directory (int Python)

所以我的项目结构如下:

project/
    src/
        __init__.py
        utils.py
        model.py
    usage.py

我现在想从 utils.py 和 model.py 中的 class 导入函数到我的 usage.py 中。 但是 model.py 本身从 utils.py 导入函数。

所以我正在做以下事情:

# usage.py

from src.model import Model
from src.utils import onehot_to_string

但我收到错误,它无法将函数从 utils.py 导入 model.py:

File "usage.py", line 11, in <module>
    from src.model import *
  File "/project/src/model.py", line 7, in <module>
    from utils import onehot_to_string
ImportError: cannot import name 'onehot_to_string' from 'utils' (/lib/python3.7/site-packages/utils/__init__.py)

我想我这里缺少一些基本的 Python 包装知识。 有人可以帮我吗? :)

对于文件/函数/变量导入,请使用此 sys 方法

import sys
# insert at 1, 0 is for other usage
sys.path.insert(1, '/path/to/application/app/folder')

看起来 python 在module.py中找不到您的utils文件。 然后它继续在路径中搜索utils并找到它,因为您可能已经安装了一些库名称 utils。 那么这个utils文件没有onehot_to_string function。

尝试将 model.py 中的from utils import onehot_to_stringfrom.utils import onehot_to_string model.py使用相对导入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM