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

【已解决】Python中使用相对路径导入库函数

Python crifan 4076浏览 0评论

现在已经写了自己的crifanLib的两个库文件:

crifanFile

crifanLogging

希望在另外的文件中去导入:

但是用:

<code>from .crifanLib import crifanFile, crifanLogging
</code>

出错:ModuleNotFoundError: No module named ‘__main__.crifanLib’; ‘__main__’ is not a package

用:

<code>from . import crifanLib
</code>

出错:

ImportError: cannot import name ‘crifanLib’

python relative import

4 PEP 328: Absolute and Relative Imports

coding style – What’s wrong with relative imports in Python? – Software Engineering Stack Exchange

The Definitive Guide to Python import Statements | Chris Yeh

Python 101: All about imports | The Mouse Vs. The Python

How to do relative imports in Python? – Stack Overflow

【总结】

此处的目录结构是:

<code>naturling
    processData
        __init__.py
        mysqlQa
            __init__.py
            crifanLib
                __init__.py
                crifanFile
                crifanLogging
</code>

(其中,无意间发现:

  • 去掉processData下面的__init__.py

  • 去掉mysqlQa下面的__init__.py

也是不影响下面的导入的)

用:

<code>from processData.mysqlQa.crifanLib import crifanFile, crifanLogging
</code>

即可导入:

转载请注明:在路上 » 【已解决】Python中使用相对路径导入库函数

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.172 seconds, using 22.23MB memory