python导入导入父孙子目录时失败

发布于 2025-01-28 00:32:30 字数 913 浏览 3 评论 0原文

我有以下目录结构:

C:\project\
|   __init__.py   
│
└───folder1
|   |    __init__.py
│   │
│   └───subfolder1
|       |   __init__.py
│       │   moduleA.py
│       │   moduleB.py
│   
└───folder2
    |   __init__.py
    └───subfolder2
        |   __init__.py
        │   myScript.py

在myScript.py文件中,我想从modulea.py导入类。我可以通过以下方式成功从模块中导入类:

import sys
import os

sys.path.append('C:/project/folder1')

from subfolder1.moduleA import ClassA

但是,当我尝试使用以下内容导入时,我会获得“ no Module no Module”:

import sys
import os

sys.path.append('C:/project')

from folder1.subfolder1.moduleA import ClassA

我已经检查了项目/目录中的所有文件的权限,并确保确保所有__ init __。py文件都是空的(我复制了__ INT __。不确定为什么事情不能正确导入。当前的工作目录(print(OS.GetCWD()))指示c:/project/project/folder2/subfolder2

这是在Windows 10机器上使用Python 2.7。

I have the following directory structure:

C:\project\
|   __init__.py   
│
└───folder1
|   |    __init__.py
│   │
│   └───subfolder1
|       |   __init__.py
│       │   moduleA.py
│       │   moduleB.py
│   
└───folder2
    |   __init__.py
    └───subfolder2
        |   __init__.py
        │   myScript.py

In the myScript.py file I want to import classes from moduleA.py. I can successfully import classes from moduleA in the following manner:

import sys
import os

sys.path.append('C:/project/folder1')

from subfolder1.moduleA import ClassA

However when I attempt to import using the following I get an ImportError "No module named moduleA":

import sys
import os

sys.path.append('C:/project')

from folder1.subfolder1.moduleA import ClassA

I've checked permissions on all files in the project/ directory as well as made sure all __init__.py files are empty (I copied the __init__.py from subfolder1 to all other __init__.py locations) and at this point I'm not sure why things are not importing correctly. Current working directory ( verified by print(os.getcwd()) ) indicates C:/project/folder2/subfolder2.

This is using Python 2.7 on a Windows 10 machine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沙沙粒小 2025-02-04 00:32:30

更新:我通过插入SYS.Path的路径而不是附加方法来解决问题。不知道为什么Python最初找不到模块,但这修复了:

sys.path.insert(0,'c:/project')

而不是

sys.path.append(' c:/project')

Update: I fixed the issue by inserting my path at the begninning of sys.path rather than appending it. No idea why Python couldn't find the module originally but this fixed it:

sys.path.insert(0, 'C:/project')

instead of

sys.path.append('C:/project')

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文