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

Electron打包后Python requests模块无法加载问题求助

问题描述

我的Electron应用中有一个Python文件,包含以下导入语句:

import requests
import shutil

在IDE中运行完全正常,但使用命令npx electron-packager ./ --platform=darwin --icon=src/img/logo.icns打包后,出现错误:
Uncaught Error: ModuleNotFoundError: No module named 'requests'
仅requests模块报错,shutil可正常使用,且我已在本地安装requests。我通过PythonShell模块在JS文件中调用该Python脚本,代码如下:

function version_checker(){
    form.classList.toggle('hide');
    circle.classList.toggle('show');
    let pyshell = new PythonShell(__dirname + '/version_checker.py');

    pyshell.on('message', function (message){
        console.log(message);
        if(message !== "same"){
            console.log("updating")
        }
        else{

            if(message !== "restart"){
                form.classList.toggle('hide');
                circle.classList.toggle('show');
            }
            else{}
        }
    })
    pyshell.end(function (err,code,signal) {
        if (err) throw err;
        console.log('The exit code was: ' + code);
        console.log('The exit signal was: ' + signal);
        console.log('finished');
    });
}

我不希望将Python文件编译为可执行文件,因为该脚本需要与JS文件交互。设备为M1 Pro MacBook,运行macOS Ventura系统,求问如何在打包应用时包含requests模块,或让requests模块在打包后的应用中正常工作?

解决方案

方法1:使用虚拟环境打包依赖

  1. 在项目根目录创建Python虚拟环境:
python3 -m venv .venv
  1. 激活虚拟环境并安装requests:
source .venv/bin/activate
pip install requests
deactivate
  1. 修改JS代码中PythonShell的配置,指定虚拟环境的Python解释器路径:
let pyshell = new PythonShell(__dirname + '/version_checker.py', {
  pythonPath: __dirname + '/../.venv/bin/python3' // 根据项目结构调整路径,确保打包后能找到
});
  1. 打包时将虚拟环境目录加入资源列表,修改electron-packager命令:
npx electron-packager ./ --platform=darwin --icon=src/img/logo.icns --extra-resource=.venv

方法2:手动指定依赖路径

  1. 先查询本地requests的安装路径:
pip show requests | grep Location
  1. 修改Python脚本开头,将依赖路径加入系统路径:
import sys
import os
# 替换为实际的依赖目录,或改为项目内的相对路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'libs'))
import requests
import shutil
  1. 将requests及其依赖包(如urllib3、certifi等)复制到项目的libs目录,打包时该目录会被自动包含进应用。

方法3:嵌入requests源码

  1. 下载requests的源码包(可通过pip download requests获取后解压),将解压后的requests文件夹放到Python脚本的同一目录下。
  2. 脚本的import requests会优先加载本地的源码文件夹,无需依赖系统环境,打包后直接随应用分发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:30:44