如何从另一个邻居子包或上层包导入python包文件

问题描述

我有一个像这样的python目录结构...

|- outerNewFolder
    |- filesFolder
        |- __init__.py
        |- innerPy.py
    |- filesFolder2
        |- __init__.py
        |- innerPy2.py
    |- __init__.py
    |- outerPy.py

在innerPy2.py文件中,我试图从innerPy.py导入函数

这是两个文件

innerPy.py

def innerFunction():
    return "Inner worked"

innerPy2.py

from outerNewFolder.filesFolder import innerPy

print(innerPy.innerFunction())

在innerPy2.py文件目录的cmd中运行-> python innerPy2.py 会给我这个错误

Traceback (most recent call last):
  File "innerPy2.py",line 1,in <module>
    from outerNewFolder.filesFolder import innerPy
ModuleNotFoundError: No module named 'outerNewFolder'

我正在使用python 3.7.7

最令人困惑的部分是,当我从Visual Studio Code的终端运行此代码时,它给了我错误。但是,如果我在pycharm上运行它,它将正常工作。我有什么想念的,还是从终端运行代码所必需的?

相对路径也不起作用。像这样更改innerPy2.py,

innerPy2.py

from ..filesFolder import innerPy

print(innerPy.innerFunction())

我得到的错误

Traceback (most recent call last):
  File "innerPy2.py",in <module>
    from ..filesFolder import innerPy
ImportError: attempted relative import with no kNown parent package

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)