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

PyInstaller打包后pyshorteners库无法使用的问题及替代方案咨询

解决PyInstaller打包pyshorteners的ModuleNotFoundError问题

问题原因

pyshorteners内部采用动态导入加载pyshorteners.shorteners模块,PyInstaller的静态依赖分析无法自动识别该模块,导致打包后的可执行文件缺失此依赖。

解决方法

方法1:打包时添加--hidden-import参数

直接在PyInstaller命令中手动指定缺失的模块:

pyinstaller --hidden-import pyshorteners.shorteners main.py

如果后续出现其他同类模块缺失错误,继续追加--hidden-import参数即可,例如--hidden-import pyshorteners.shorteners.tinyurl。

方法2:修改.spec文件

  1. 先生成默认的spec配置文件:
pyinstaller main.py
  1. 打开生成的main.spec文件,找到hiddenimports列表,添加缺失模块:
hiddenimports=['pyshorteners.shorteners'],
  1. 使用修改后的spec文件重新打包:
pyinstaller main.spec

方法3:在脚本中显式导入模块

在Python脚本开头添加显式导入语句,让PyInstaller的静态分析能检测到该依赖:

import pyshorteners.shorteners

# 原有业务代码
def Shorten_Link(link):
    shortener = pyshorteners.Shortener()
    return shortener.tinyurl.short(link)

之后正常执行PyInstaller打包命令即可。

简便替代方案

如果仅需TinyURL的链接缩短功能,可以直接调用其公开API,无需依赖pyshorteners库,示例代码如下:

import requests

def Shorten_Link(link):
    try:
        resp = requests.get(f"http://tinyurl.com/api-create.php?url={link}")
        resp.raise_for_status()
        return resp.text
    except requests.exceptions.RequestException as e:
        print(f"链接缩短失败: {str(e)}")
        return None

该方式仅依赖requests库,PyInstaller可自动识别其依赖,打包时不会出现模块缺失问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:07:28