简体   繁体   English

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

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

So my project structure is the following:所以我的项目结构如下:

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

I now want to import functions from utils.py and a class in model.py into my usage.py.我现在想从 utils.py 和 model.py 中的 class 导入函数到我的 usage.py 中。 But the model.py itself imports functions from utils.py.但是 model.py 本身从 utils.py 导入函数。

So I am doing the following:所以我正在做以下事情:

# usage.py

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

But I am getting the error that it couldnt import functions from utils.py into the model.py:但我收到错误,它无法将函数从 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)

I think I am lacking of some basic Python packaging knowledge here.我想我这里缺少一些基本的 Python 包装知识。 Can someone help me out?有人可以帮我吗? :) :)

for file/function/variables importing use this sys method对于文件/函数/变量导入,请使用此 sys 方法

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

Looks like python can't find your utils file in module.py .看起来 python 在module.py中找不到您的utils文件。 Then it proceeds to search for utils in path and finds it as you have probably installed some library name utils.然后它继续在路径中搜索utils并找到它,因为您可能已经安装了一些库名称 utils。 Then this utils file has no onehot_to_string function.那么这个utils文件没有onehot_to_string function。

Try to change your from utils import onehot_to_string to from.utils import onehot_to_string in model.py to use relative import.尝试将 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