使用时命名空间已损坏设置.py并导致AttributeError:模块没有attribu

2024-05-15 16:54:44 发布

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

我编写了一个重用现有名称空间pki.server的小工具(包)。我把我的包命名为pki.server.healthcheck。旧的名称空间没有使用setuptools安装包,而我的包使用它。你知道吗

setup.py的内容

from setuptools import setup

setup(
    name='pkihealthcheck',
    version='0.1',
    packages=[
        'pki.server.healthcheck.core',
        'pki.server.healthcheck.meta',
    ],
    entry_points={
        # creates bin/pki-healthcheck
        'console_scripts': [
            'pki-healthcheck = pki.server.healthcheck.core.main:main'
        ]
    },
    classifiers=[
        'Programming Language :: Python :: 3.6',
    ],
    python_requires='!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*',
    setup_requires=['pytest-runner',],
    tests_require=['pytest',],
)

安装树(来自下面的场景1)如下所示:

# tree /usr/lib/python3.8/site-packages/pki/
├── __init__.py                     <---- Has methods and classes
├── cli
│   ├── __init__.py                 <---- Has methods and classes
│   ├── <some files>
├── server
│   ├── cli
│   │   ├── __init__.py             <---- Has methods and classes
│   │   ├── <Some files>
│   ├── deployment
│   │   ├── __init__.py             <---- Has methods and classes
│   │   ├── <some files>
│   │   └── scriptlets
│   │       ├── __init__.py         <---- Has methods and classes
│   │       ├── <some files>
│   ├── healthcheck
│   │   ├── core
│   │   │   ├── __init__.py         <---- EMPTY
│   │   │   └── main.py
│   │   └── pki
│   │       ├── __init__.py         <---- EMPTY
│   │       ├── certs.py
│   │       └── plugin.py
│   └── instance.py                 <---- Has class PKIInstance
└── <snip>

# tree /usr/lib/python3.8/site-packages/pkihealthcheck-0.1-py3.8.egg-info/
├── PKG-INFO
├── SOURCES.txt
├── dependency_links.txt
├── entry_points.txt
└── top_level.txt

我阅读了official documentation,并尝试了所有3种建议的方法。我看到了以下结果:

场景1:本机命名空间包

起初,一切似乎都很顺利。但是:

# This used to work before my package gets installed
>>> import pki.server
>>> instance = pki.server.instance.PKIInstance("pki-tomcat")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'pki.server' has no attribute 'instance'

现在,只有这个有效

>>> import pki.server.instance
>>> instance = pki.server.instance.PKIInstance("pki-tomcat")
>>> instance
pki-tomcat

场景2:pkgutil风格的命名空间包 由于我的其他__init__.py包含类和函数,因此我不能使用此方法

场景3:pkg\u资源风格的命名空间包 虽然不推荐使用这种方法,但我继续尝试,在我的setup.py中添加了namespace=pki.server.healthcheck。这使得所有pki.*模块都不可见

所以我确信场景1似乎是最接近我想要实现的。我读了一篇old post来了解python中import的工作原理。你知道吗

我的问题是:为什么在安装包之后,一个完美工作的代码段会中断?


Tags: andinstancepyimportserverinitsetup场景
1条回答
网友
1楼 · 发布于 2024-05-15 16:54:44

您的__init__.py文件需要导入这些文件。有两个选项absolute and relative imports

相对进口

pki/\uu初始化\ py:
from . import server

pki/server/\uu init\uuuuu.py:
from . import instance

绝对进口

pki/\uu初始化\ py:
import pki.server

pki/server/\uu init\uuuuu.py:
import pki.server.instance

相关问题 更多 >