Python精选200Tips:126-130

玩中学Python

运行系统:macOS Sonoma 14.6.1
Python编译器:PyCharm 2024.1.4 (Community Edition)
Python版本:3.12

往期链接:

1-5 6-10 11-20 21-30 31-40 41-50
51-60:函数 61-70:类 71-80:编程范式及设计模式
81-90:Python编码规范 91-100:Python自带常用模块-1
101-105:Python自带模块-2 106-110:Python自带模块-3
111-115:Python常用第三方包-频繁使用 116-120:Python常用第三方包-深度学习
121-125:Python常用第三方包-爬取数据

本文只介绍每个包主要做什么及一些比较经典的示例。对于包的进一步学习,推荐参考对应包的官方文档。

126 PyInstaller - 将 Python 程序打包成独立可执行文件的工具

pyinstaller版本6.10.0,官方文档

PyInstaller 是一个用于将 Python 程序打包成独立可执行文件的工具。它支持 Windows、macOS 和 Linux,能够将 Python 代码及其依赖项打包在一起,使得用户无需安装 Python 环境即可运行你的程序。主要特点:

  • 跨平台:支持多种操作系统。
  • 自动分析依赖:自动识别并包含所需的库和模块。
  • 支持多种格式:可以生成单个可执行文件或包含多个文件的目录。
  • 可自定义:允许用户自定义打包过程,例如添加图标或数据文件。

创建一个简单的图像处理应用,允许用户加载图像并将其转换为灰度图像。这个应用将使用 Pillow 库进行图像处理。

示例:图像变为灰度图像
项目结构

在这里插入图片描述

代码文件

main.py

import sys
import os
from PIL import Image

def convert_to_grayscale(image_path, output_path):
    """将图像转换为灰度并保存"""
    img = Image.open(image_path)
    gray_img = img.convert("L")
    gray_img.save(output_path)
    print(f"Saved grayscale image to {
     output_path}")

def main():
    if len(sys.argv) != 3:
        print("Usage: main.py <input_image_path> <output_image_path>")
        sys.exit(1)

    input_image = sys.argv[1]
    output_image = sys.argv[2]

    if not os.path.exists(input_image):
        print(f"Input file does not exist: {
     input_image}")
        sys.exit(1)

    convert_to_grayscale(input_image, output_image)

if __name__ == "__main__":
    main()

requirements.txt

Pillow

example.icns

打包后的图标,widows系统是.ico文件,macos系统是.icns文件

在这里插入图片描述

打包步骤

打开终端,并导航到 image_processor 目录

 cd /Users/anfany/Documents/OneLinePython/image_processor

运行 PyInstaller

pyinstaller --clean --windowed --onefile --icon=/Users/anfany/Documents/OneLinePython/image_processor/example.icns --name=ImageProcessor main.py

在 Windows 上,--add-data 的分隔符为 ;,而在 macOS/Linux 上应使用 :。

……
14698 INFO: Building EXE from EXE-00.toc completed successfully.
14701 INFO: checking BUNDLE
14701 INFO: Building BUNDLE because BUNDLE-00.toc is non existent
14701 INFO: Building BUNDLE BUNDLE-00.toc
14706 INFO: Signing the BUNDLE...
14746 INFO: Building BUNDLE BUNDLE-00.toc completed successfully.

查找生成的文件

查看 dist 目录,会发现 ImageProcessor.exe(Windows 系统)或 ImageProcessor( macOS/Linux 系统)。

运行可执行文件
./dist/ImageProcessor images/sample.jpg images/sample_gray.jpg
Saved grayscale image to images/sample_gray.jpg

在这里插入图片描述

127 PyYAML - YAML 解析和生成工具

PyYAML版本6.0.2,官方文档
PyYAML 是一个用于处理 YAML(YAML Ain’t Markup Language)的 Python 库。YAML 是一种人类可读的数据序列化格式,广泛用于配置文件和数据交换。PyYAML 允许你轻松地将 YAML 格式的数据加载到 Python 对象中,或将 Python 对象转储为 YAML 格式。

基本用法

  • 加载 YAML 数据

使用 yaml.load() 函数从 YAML 文件或字符串中读取数据。

  • 转储 YAML 数据

使用 yaml.dump() 函数将 Python 对象转换为 YAML 格式。

示例:读取配置内容
项目结构
yaml_example/
├── config.yaml
└── main.py
代码文件

config.yaml 内容

# 复杂配置文件示例
app:
  name: MyWebApp
  version: 1.0
  debug: true
  features:
    authentication: true
    payments: false
    notifications:
      email: true
      sms: false

database:
  type: postgresql
  host: localhost
  port: 5432
  username: myuser
  password: mypass
  dbname: mydatabase

logging:
  level: DEBUG
  handlers:
    - console
    - file
  file:
    path: /var/log/mywebapp.log
    max_size: 10MB
    backup_count: 5

api:
  endpoints:
    - path: /users
      method: GET
      description: Get user list
    - path: /users/{
   id}
      method: GET
      description: Get user by ID
    - path: /users
      method: POST
      description: Create a new user

main.py 内容

import yaml

def load_config(file_path):
    """加载 YAML 配置文件"""
    with open(file_path, 'r') as file:
        config = yaml.load(file, Loader=yaml.FullLoader)
    return config

def print_config(config):
    """打印配置内容"""
    print(f"应用名称: {
     config['app']['name']}")
    print(f"版本: {
     config['app']['version']}")
    print(f"调试模式: {
     config['app']['debug']}")
    
    print("功能开关:")
    for feature, enabled in config['app']['features'].items():
        print(f"  {
     feature}: {
     '开启' if enabled else '关闭'}")

    print("数据库配置:")
    print(f"  类型: {
     config['database']['type']}")
    print(f"  主机: {
     config['database']['host']}")
    print(f"  端口: {
     config['database']['port']}")
    print(f"  用户名: 
  • 26
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AnFany

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值