温馨提示×

Ubuntu Python跨平台开发怎么做

小樊
39
2025-12-20 12:12:22
栏目: 编程语言

Ubuntu 上的 Python 跨平台开发实践

一 环境与依赖管理

  • 选择一种“主流程”并在团队内统一:
    • Conda:适合数据科学/多平台依赖,命令示例:conda create -n dev310 python=3.10 -y && conda activate dev310
    • venv + pip:更轻量、原生,命令示例:python3 -m venv .venv && source .venv/bin/activate
    • uv:极快的包与环境管理,命令示例:curl -LsSf https://astral.sh/uv/install.sh | sh && uv venv
  • 统一包源与工具:
    • pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
    • pip install -U pip ipython wheel pip-tools
  • 可复现性:
    • 生成锁定文件:pip-compile requirements.in -o requirements.txtpip freeze > requirements.txt
    • 从锁定文件安装:pip-sync requirements.txtpip install -r requirements.txt
  • 目录规范:项目与虚拟环境放在同一独立目录,便于迁移与备份。

二 编写跨平台代码

  • 路径与系统差异:
    • 使用 os.path.join / pathlib.Path 处理路径,避免硬编码斜杠。
    • os.sep、os.path.expanduser、os.path.abspath 处理分隔符与绝对路径。
  • 平台判定与条件分支:
    • 使用 sys.platform / platform.system() 判别系统,封装差异(如路径、命令、换行符)。
  • 子进程与命令执行:
    • 优先用 subprocess.run([…], check=True) 传列表,避免 shell=True 引发平台差异。
  • 文件与编码:
    • 打开文件显式指定 encoding=‘utf-8’,避免默认编码差异。
  • 第三方库选型:优先选择声明支持多平台的库(如 requests、Tkinter 等)。

三 测试与交付的一体化

  • 本地多环境:在 Ubuntu/WSL2/Windows 上分别跑通安装与测试,覆盖路径、编码、子进程等差异。
  • 自动化测试:使用 pytest 编写用例,结合 GitHub Actions/GitLab CI 做矩阵构建(如 ubuntu-latest、windows-latest、macos-latest)。
  • 容器化交付:用 Docker 定义多阶段构建与运行时,确保“构建一次,到处运行”。
  • 交付物:提供清晰的 READMErequirements.txt/conda env.yml.dockerignore 与示例脚本。

四 桌面与移动跨平台方案

  • 桌面 GUI:
    • Tkinter(标准库,跨平台)、PyQt/PySide(功能强,商业可用,跨平台)、Kivy(基于 OpenGL ES 2,适合触控与多媒体)。
  • 移动端:
    • Kivy + Python for Android(p4a) 可将应用打包为 APK;流程要点:准备 Android SDK/NDK,构建包含 Python 运行时与依赖 的发行版,再用 p4a 打包 APK。
  • 选择建议:重桌面体验优先 PyQt/PySide;重触控/移动优先 Kivy

五 GPU 与数据科学的跨平台要点

  • 驱动与工具链:
    • 检查 NVIDIA 驱动nvidia-smi;如需本地编译 CUDA 扩展,检查 nvcc --version
  • PyTorch 与 CUDA 匹配:
    • 原则:先确定驱动与 CUDA 版本,再安装匹配的 PyTorch 预编译包。
    • 示例(CUDA 12.1):pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121;仅 CPU:pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
  • 可用性验证脚本:
    • import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available())
  • 常见坑:
    • “CUDA driver version is insufficient”:升级 NVIDIA 驱动 并重启。
    • Windows 下 DLL 加载失败:安装 Microsoft C++ Redistributable,避免中文与空格路径。
    • SSLCertVerificationError:优先修复证书/网络,不长期使用 --trusted-host

0