如何正确构造Python包,以便轻松导入?

2024-09-30 16:41:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个Python包,其中将包含可重用的代码、类等,这些代码和类将导入到我们的其他Python程序中。不过,我真的很难让导入正常工作,要么导入由于init.py中的更改而停止工作,要么我会得到一个导入错误

init.py:

from .util import configParser, writeToAppLog # currently trying this method...
from .itm import normaliseAgentVersion
# from . import util                          # would prefer this method so we don't have to define every single thing our module will "export"
# from . import itm

__all__ = ["util", "itm"]
注意:我希望避免使用任何类型的import *,因为它屏蔽了从…导入函数的位置。

test.py:

from . import itmlcm

itmlcm.normaliseAgentVersion("06.30.07.00")

上面的test.py脚本似乎可以工作,当然是在VS代码中。但是,它会产生以下错误:

Traceback (most recent call last):
  File ".\LCM\bin\test.py", line 4, in <module>
    from . import itmlcm
ImportError: attempted relative import with no known parent package

我们如何正确地构造它,以便开发包并将其导入到代码中使用


Tags: 代码frompytestimport程序init错误