# 移动端还在手动打包吗?手把手教你基于 Python实现项目的自动打包与发布 站点:答源(https://www.dandroid.cn/) 原文:https://www.dandroid.cn/archives/22110 Canonical:https://www.dandroid.cn/archives/22110 作者:admin 发布日期:2024-09-30 最后更新:2024-09-30 01:49 分类:技术方案 内容类型:post 说明:本页是原文的纯文本镜像,供大模型与检索器完整读取;不含导航、广告、付费框。引用请以上方「原文」链接为准。 ## 正文 引言 在移动应用的开发过程中,频繁的打包、上传以及通知相关成员是一个相对繁琐且耗时的过程。为了简化这一流程,我编写了一个 Python 脚本,能够自动化完成分支切换、打包 Android 和 iOS 应用、上传文件到腾讯云 COS 并推送到企业微信。本文将介绍该脚本的实现细节,希望能够对开发者朋友们有所帮助。 1. 脚本功能概述 该脚本的主要功能包括: 自动切换到指定的 Git 分支。 使用 flutter 命令打包 Android 和 iOS 应用。 将打包好的应用上传至腾讯云 COS。 通过企业微信 webhook 将上传成功的消息推送给相关人员。 整个流程实现了打包与发布的全自动化,为开发者节省了大量时间,同时也避免了手动操作可能带来的失误。 2. 环境准备 2.1 依赖安装 在使用该脚本之前,请确保安装了以下依赖: Python:建议使用 Python 3.6 及以上版本。 qcloud_cos:腾讯云 COS 的 Python SDK。 需要开通腾讯云服务 Flutter SDK:确保 Flutter 环境已正确配置。 Git:用于版本控制和分支管理。 Android:根据需要自行配置。 iOS:根据需要自行配置。 安装 qcloud_cos SDK:(python安装库的方法,也可以通过开发工具配置,需要一定python基础) pip install qcloud_cos 2.2 配置环境变量 变量 | 含义 | target_branch | 仓库分支名 | pushUrl | 企业微信推送地址 | Access_id | 腾讯云 COS需要的参数 | Access_key | 腾讯云 COS需要的参数 | 在脚本中,我们使用了 CosConfig 腾讯云 COS来做包的服务器上传,使用企业微信机器人来推送到相关群。请在实际使用时结合公司自己的基建来灵活安排 3. 脚本实现详解 3.1 引入依赖和配置 首先,我们引入了脚本所需的 Python 模块,并进行了腾讯云 COS 的配置。 import datetime from qcloud_cos import CosConfig, CosS3Client import os import subprocess import threading import time pub_version = '1.0.0+1000000' target_branch = "your_branch" pushUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_webhook_key' client = CosS3Client(CosConfig(Region='your-region', Access_id='your-access-id', Access_key='your-access-key')) 3.2 切换分支 使用 subprocess 模块执行 Git 命令,实现自动切换到目标分支,并拉取最新代码: def switch_to_branch(): try: print("Switching to branch...") subprocess.run("git fetch --all", shell=True) print("git fetch --all...") subprocess.run(f"git checkout -f {target_branch}", shell=True) print("git checkout -f...") subprocess.run(f"git pull", shell=True) print("Pulling latest changes...") event.set() except Exception as e: print(f"Error in switch_to_branch: {e}") switch_thread = threading.Thread(target=switch_to_branch) switch_thread.start() event.wait() 3.3 打包应用 使用 Flutter 的命令行工具打包 Android 和 iOS 应用。我们在 aliases 字典中定义了常用的打包命令,然后通过 subprocess 执行。请结合自己项目使用相关打包脚本即可。 def execute_command(command): aliases = { "pkr": "flutter build apk --no-tree-shake-icons", "pki": "flutter build ipa --no-tree-shake-icons --export-options-plist /path/to/your/export-options.plist" } subprocess.run("pwd", shell=True) command = aliases.get(command) if not command: return "Unknown command" print(f"Starting to execute command: {command}") start_time = time.time() process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while True: output = process.stdout.readline() if output == b'' and process.poll() is not None: break if output: print(output.decode().strip()) error_output = process.stderr.read() if error_output: print(error_output.decode().strip()) end_time = time.time() elapsed_time = end_time - start_time print(f"Command execution completed. Time taken: {elapsed_time:.2f} seconds") if command == aliases["pkr"]: uploadAppAndroid() if command == aliases["pki"]: uploadAppIOS() 3.4 上传应用到腾讯云 COS 通过 client.upload_file 将打包好的 APK 和 IPA 文件上传到腾讯云 COS。上传成功后,将文件的下载链接通过企业微信 webhook 推送给相关人员。 def uploadAppAndroid(): parts = pub_version.split('+') version = parts[0] build = parts[1] now = datetime.datetime.now() timestamp = now.strftime("%Y%m%d%H%M") androidPath = f"https://your-cos-domain/ui/android/project/{version}/Publish_Market/{build}/v{version}-{timestamp}-redcity.apk" coskey = androidPath.split('https://your-cos-domain')[1] response = client.upload_file( Bucket='your-bucket-name', LocalFilePath='/path/to/your/apk/app-release.apk', Key=coskey, PartSize=10, MAXThread=10) print("market_url: " + response['Location']) sendWebhook(response['Location'], '安卓包', timestamp) def uploadAppIOS(): parts = pub_version.split('+') version = parts[0] build = parts[1] now = datetime.datetime.now() timestamp = now.strftime("%Y%m%d%H%M") iosPath = f"https://your-cos-domain/ui/android/project/{version}/Publish_Market/{build}/v{version}-{timestamp}-redcity.ipa" coskey = iosPath.split('https://your-cos-domain')[1] response = client.upload_file( Bucket='your-bucket-name', LocalFilePath='/path/to/your/ipa/redcity.ipa', Key=coskey, PartSize=10, MAXThread=10) print("market_url: " + response['Location']) sendWebhook(response['Location'], 'iOS包', timestamp) 3.5 发送企业微信通知 使用企业微信的 webhook,将打包成功的消息推送给相关人员。 关于企业微信机器人的学习使用,点击这里 def sendWebhook(url, package_type, timestamp): if(pushUrl != ''): content = f"{package_type} [n分支名:{target_branch}n时间:{timestamp}n下载链接(点击下载即可)]({url})" command = f"curl '{pushUrl}' -H 'Content-Type: application/json' -d '{{"msgtype": "markdown", "markdown": {{"content": "{content}"}}}}'" try: subprocess.run(command, shell=True, check=True) print("Webhook sent successfully.") except subprocess.CalledProcessError as e: print(f"Error sending webhook: {e}") 4. 运行脚本 将脚本文件保存为 auto_build.py。 将路径和 COS 配置替换为自己的配置项。 在终端中执行脚本: python auto_build.py 5. 总结 通过该脚本,我们实现了 Flutter 项目的自动打包、上传和通知的全流程自动化。它极大地减少了手动操作的步骤,并提升了开发效率。希望这篇文章对你有所帮助! 在实际使用中,你可以根据自己的需求对脚本进行进一步的定制和优化。Happy Coding! --- 由 答源 DAN 底座 1.4.1 生成 · 2026-11-22T15:18:40+00:00