You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python包autocord发布PyPI后出现autocord.types导入失败问题

解决PyPI包安装后无法导入子模块的问题

问题场景

本地工作区直接使用autocord目录时,import autocord导入正常,但发布到PyPI后,其他环境安装后执行导入出现以下错误:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import autocord
  File "/home/runner/autocord-test/venv/lib/python3.10/site-packages/autocord/__init__.py", line 1, in <module>
    from .client import Client
  File "/home/runner/autocord-test/venv/lib/python3.10/site-packages/autocord/client.py", line 9, in <module>
    from .types.Me import Me
ModuleNotFoundError: No module named 'autocord.types'

项目目录结构:

autocord
├── types
│   ├── Message.py
│   ├── Attachment.py
│   ├── Deleted.py
│   ├── DmChannel.py
│   ├── Embed.py
│   ├── Me.py
│   └── Member.py
├── __init__.py
├── client.py
├── errors.py
└── op.py

client.py中的导入语句(相对导入):

from .types.Me import Me
from .types.Member import Member
from .types.Message import Message
from .types.Deleted import Deleted
from .types.DmChannel import DmChannel

当前使用的setup.py:

from setuptools import setup

with open("README.md", encoding="utf-8") as f:
    readme = f.read()

setup(
    name="autocord",
    version="1.4.8",
    author="walker",
    description="Discord API wrapper centered around automation",
    long_description=readme,
    long_description_content_type="text/markdown",
    packages=['autocord'],
    url="https://github.com/wa1ker38552/autocord",
    install_requires=["requests", "websocket_client"],
    python_requires=">=3.7",
    py_modules=["autocord"]
)

问题原因

  1. 子包未被打包:packages=['autocord']仅指定了根包,未包含子包autocord.types,导致types目录下的模块未被纳入PyPI包中。
  2. 配置冲突:py_modules=["autocord"]是多余配置,该参数用于指定单个Python文件模块,与packages管理包结构的逻辑冲突,会导致打包异常。

解决方案

1. 修改setup.py配置

使用find_packages()自动发现所有包含__init__.py的子包,同时移除多余的py_modules配置:

from setuptools import setup, find_packages

with open("README.md", encoding="utf-8") as f:
    readme = f.read()

setup(
    name="autocord",
    version="1.4.8",
    author="walker",
    description="Discord API wrapper centered around automation",
    long_description=readme,
    long_description_content_type="text/markdown",
    packages=find_packages(),  # 自动识别所有子包
    install_requires=["requests", "websocket_client"],
    python_requires=">=3.7"
)

2. 确保子包结构合法

检查autocord/types目录下是否存在__init__.py文件(可以是空文件),只有存在该文件,Python才会将这个目录识别为合法子包。如果没有,创建一个空的autocord/types/__init__.py即可。

3. 重新打包上传

  • 卸载本地旧版本:pip uninstall autocord
  • 重新构建包:python setup.py sdist bdist_wheel
  • 上传新版本到PyPI:使用twine工具上传dist/目录下的产物(twine upload dist/*)

完成以上步骤后,其他环境安装包即可正常导入autocord.types相关模块。

内容的提问来源于stack exchange,提问作者Walker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:22:46