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

上传至PyPI的自定义Python包无法正常导入调用该如何解决?

问题解决步骤

问题根源

你遇到的调用异常、安装报错由两个配置错误导致:

  1. __init__.py的导入逻辑错误,没有把目标函数暴露到包的顶层命名空间
  2. 误移动setup.py到内层目录,导致打包/安装逻辑失效

具体调整方案

  1. 还原setup.py位置
    把移到内层testsimpleprinter文件夹的setup.py放回到项目根目录(也就是TestSimplePrinter文件夹下),setup.py本身就要求放在项目根目录,移动后会导致打包、安装流程找不到配置文件报错。

  2. 修改__init__.py内容
    把内层testsimpleprinter文件夹下的__init__.py原来的内容:

from testsimpleprinter import testsimpleprinter

修改为以下任意一种写法即可:

  • 相对导入写法(推荐,适配性更高)
    from .testsimpleprinter import testsimpleprinter
    
  • 绝对导入写法
    from testsimpleprinter.testsimpleprinter import testsimpleprinter
    

原写法的问题是Python解析导入时,会优先匹配到同层级的testsimpleprinter.py模块,而不是模块内的函数,导致你导入包后tsp.testsimpleprinter指向的是模块文件,不是函数,需要多写一层才能调用到内部的函数。修改后会直接把函数暴露到包的顶层命名空间。

  1. 重新打包上传
    修改完配置后,升级setup.py里的版本号(避免和已上传的旧版本冲突),重新执行打包、上传PyPI的操作。本地测试时先卸载旧版本的包,再重新安装新版本,即可验证调用效果:
import testsimpleprinter as tsp
tsp.testsimpleprinter("Hello")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:57:03