最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python导入父级目录中的模块

Python crifan 1481浏览 0评论
在为自己的crifanLib的python写demo
尝试去导入父级目录中的crifanFile
然后试了试:..
from ..crifanFile import getFileFolderSize, formatSize
好像可以支持:
但是运行失败:
发生异常: ValueError
attempted relative import beyond top-level package
File "/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib/demo/crifanFileDemo.1.py", line 1, in <module> from ..crifanFile import getFileFolderSize, formatSize
所以去搜:
python import parent directory
python – Importing modules from parent folder – Stack Overflow
和:
python – Relative importing modules from parent folder subfolder – Stack Overflow
去试试:…

from ...crifanLib import crifanFile
结果:
问题依旧:

from ... import crifanFile
结果:问题依旧。
看到别人提示了:
Relative imports (as in from .. import mymodule) only work in a package.
python – Import file from parent directory? – Stack Overflow
https://stackoverflow.com/questions/16780014/import-file-from-parent-directory
用:
import sys
import os
curFolder = os.path.abspath(__file__)
parentFolder = os.path.dirname(curFolder)
parentParentFolder = os.path.dirname(parentFolder)
parentParentParentFolder = os.path.dirname(parentParentFolder)
sys.path.append(curFolder)
sys.path.append(parentFolder)
sys.path.append(parentParentFolder)
sys.path.append(parentParentParentFolder)

from crifanFile import getFileFolderSize, formatSize
是可以的:
看到google的动态提示:
所以再去搜:
python 3 import from parent directory
The Definitive Guide to Python import Statements | Chris Yeh
Python package import from parent directory – Stack Overflow
How to import a package located in its parent directory using absolute import in Python 3? – Stack Overflow
【总结】
在:
/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib/demo/crifanFileDemo.1.py
最后用:
import sys
import os
curFolder = os.path.abspath(__file__)
parentFolder = os.path.dirname(curFolder)
parentParentFolder = os.path.dirname(parentFolder)
parentParentParentFolder = os.path.dirname(parentParentFolder)
sys.path.append(curFolder)
sys.path.append(parentFolder)
sys.path.append(parentParentFolder)
sys.path.append(parentParentParentFolder)

from crifanFile import getFileFolderSize, formatSize
可以导入:
/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib
下面的:
/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib/crifanFile.py
然后就可以继续测试了。
注:
实际情况中,一般只需要parentFolder就够了
此处之所以继续导入parentParentFolder、parentParentParentFolder是因为此处的crifanFile内容导入了别的库,其所在路径是父级的父级,父级的父级的父级 的路径。

转载请注明:在路上 » 【已解决】Python导入父级目录中的模块

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.185 seconds, using 22.08MB memory