主题
Python基础与自动化脚本
1. Python 概述
1.1 Python 简介
Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言。它由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。
Python 的设计哲学强调代码的可读性和简洁的语法(尤其是使用空格缩进划分代码块,而非使用大括号或者关键词)。Python 使开发者能够用更少的代码表达想法,不管是小型还是大型程序,该语言都试图让程序的结构清晰明了。
1.2 Python 的特点
- 易学易用:Python 语法简洁明了,接近自然语言,学习曲线平缓
- 解释执行:Python 是解释型语言,无需编译,直接执行
- 跨平台:Python 可以在各种操作系统上运行,如 Windows、Linux、macOS 等
- 丰富的库:Python 拥有庞大的标准库和第三方库,几乎可以实现任何功能
- 面向对象:Python 支持面向对象编程,但也支持函数式编程和过程式编程
- 动态类型:Python 是动态类型语言,变量无需声明类型
- 自动内存管理:Python 具有垃圾回收机制,自动管理内存
1.3 Python 的应用领域
- Web 开发:Django、Flask、FastAPI 等框架
- 数据科学:NumPy、Pandas、Matplotlib、SciPy 等库
- 人工智能:TensorFlow、PyTorch、scikit-learn 等库
- 自动化运维:系统管理、配置管理、监控等
- 网络爬虫:Scrapy、BeautifulSoup、Requests 等库
- 游戏开发:Pygame 等库
- 桌面应用:Tkinter、PyQt、wxPython 等库
- 嵌入式开发:MicroPython、CircuitPython 等
2. Python 环境搭建
2.1 Python 安装
2.1.1 在 Linux 上安装 Python
大多数 Linux 发行版默认安装了 Python,但可能不是最新版本。以下是在不同 Linux 发行版上安装 Python 的方法:
Ubuntu/Debian:
bash
# 更新包列表
sudo apt update
# 安装 Python 3.10
sudo apt install python3.10 python3.10-venv python3.10-dev
# 检查 Python 版本
python3 --versionCentOS/RHEL:
bash
# 安装 EPEL 仓库
sudo yum install epel-release
# 安装 Python 3.10
sudo yum install python3.10 python3.10-venv python3.10-devel
# 检查 Python 版本
python3 --versionFedora:
bash
# 安装 Python 3.10
sudo dnf install python3.10 python3.10-venv python3.10-devel
# 检查 Python 版本
python3 --version2.1.2 在 Windows 上安装 Python
- 访问 Python 官方网站 下载最新的 Python 安装包
- 运行安装包,勾选 "Add Python to PATH"
- 选择 "Customize installation",保持默认选项
- 选择安装路径,点击 "Install"
- 安装完成后,打开命令提示符,输入
python --version检查版本
2.1.3 在 macOS 上安装 Python
使用 Homebrew:
bash
# 安装 Homebrew(如果未安装)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安装 Python
brew install python
# 检查 Python 版本
python3 --version使用官方安装包:
- 访问 Python 官方网站 下载最新的 Python 安装包
- 运行安装包,按照提示完成安装
- 打开终端,输入
python3 --version检查版本
2.2 虚拟环境配置
虚拟环境是 Python 项目的隔离环境,可以避免依赖冲突。
2.2.1 使用 venv 创建虚拟环境
bash
# 创建虚拟环境
python3 -m venv venv
# 激活虚拟环境(Linux/macOS)
source venv/bin/activate
# 激活虚拟环境(Windows)
venv\Scripts\activate
# 退出虚拟环境
deactivate2.2.2 使用 pipenv 管理依赖
bash
# 安装 pipenv
pip install pipenv
# 创建虚拟环境并安装依赖
pipenv install requests
# 激活虚拟环境
pipenv shell
# 退出虚拟环境
exit2.2.3 使用 poetry 管理依赖
bash
# 安装 poetry
pip install poetry
# 初始化项目
poetry init
# 安装依赖
poetry add requests
# 激活虚拟环境
poetry shell
# 退出虚拟环境
exit3. Python 基础语法
3.1 变量与数据类型
3.1.1 变量
Python 中的变量不需要声明类型,直接赋值即可:
python
# 变量赋值
name = "John"
age = 30
height = 1.75
is_student = False
# 打印变量
print(name)
print(age)
print(height)
print(is_student)
# 变量重新赋值
name = "Jane"
age = age + 1
print(name)
print(age)3.1.2 数据类型
Python 支持多种数据类型:
| 数据类型 | 描述 | 示例 |
|---|---|---|
| 整数 (int) | 整数 | age = 30 |
| 浮点数 (float) | 小数 | height = 1.75 |
| 字符串 (str) | 文本 | name = "John" |
| 布尔值 (bool) | True 或 False | is_student = False |
| 列表 (list) | 有序可变序列 | numbers = [1, 2, 3] |
| 元组 (tuple) | 有序不可变序列 | coordinates = (10, 20) |
| 字典 (dict) | 键值对集合 | person = {"name": "John", "age": 30} |
| 集合 (set) | 无序唯一元素集合 | unique_numbers = {1, 2, 3} |
3.2 运算符
3.2.1 算术运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
+ | 加法 | a + b |
- | 减法 | a - b |
* | 乘法 | a * b |
/ | 除法 | a / b |
// | 整除 | a // b |
% | 取模 | a % b |
** | 幂运算 | a ** b |
3.2.2 比较运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
== | 等于 | a == b |
!= | 不等于 | a != b |
> | 大于 | a > b |
< | 小于 | a < b |
>= | 大于等于 | a >= b |
<= | 小于等于 | a <= b |
3.2.3 逻辑运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
and | 与 | a and b |
or | 或 | a or b |
not | 非 | not a |
3.2.4 赋值运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
= | 赋值 | a = b |
+= | 加法赋值 | a += b |
-= | 减法赋值 | a -= b |
*= | 乘法赋值 | a *= b |
/= | 除法赋值 | a /= b |
//= | 整除赋值 | a //= b |
%= | 取模赋值 | a %= b |
**= | 幂运算赋值 | a **= b |
3.3 控制流
3.3.1 条件语句
python
# if 语句
if age >= 18:
print("成年人")
elif age >= 13:
print("青少年")
else:
print("儿童")
# 三元运算符
status = "成年人" if age >= 18 else "未成年人"
print(status)3.3.2 循环语句
python
# for 循环
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历数字
for i in range(5):
print(i)
# 遍历字典
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 循环控制语句
for i in range(10):
if i == 5:
break # 跳出循环
if i % 2 == 0:
continue # 跳过当前循环
print(i)3.4 函数
3.4.1 函数定义与调用
python
# 函数定义
def greet(name):
"""打印问候语"""
print(f"Hello, {name}!")
# 函数调用
greet("John")
# 带返回值的函数
def add(a, b):
"""计算两数之和"""
return a + b
result = add(3, 5)
print(result)
# 默认参数
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("John")
greet("John", "Hi")
# 可变参数
def sum_numbers(*args):
return sum(args)
result = sum_numbers(1, 2, 3, 4, 5)
print(result)
# 关键字参数
def person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
person_info(name="John", age=30, city="New York")3.4.2 Lambda 函数
Lambda 函数是一种小型的匿名函数,使用 lambda 关键字定义:
python
# 定义 lambda 函数
double = lambda x: x * 2
print(double(5))
# 作为参数传递
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers)
# 排序
students = [("John", 20), ("Jane", 18), ("Bob", 22)]
students.sort(key=lambda student: student[1])
print(students)4. Python 数据结构
4.1 列表 (List)
列表是 Python 中最常用的数据结构之一,是有序可变的序列。
python
# 创建列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
# 访问元素
print(numbers[0]) # 第一个元素
print(numbers[-1]) # 最后一个元素
print(numbers[1:3]) # 切片
# 修改元素
numbers[0] = 10
print(numbers)
# 添加元素
numbers.append(6)
numbers.insert(1, 15)
print(numbers)
# 删除元素
numbers.remove(3)
del numbers[0]
last_element = numbers.pop()
print(numbers)
print(last_element)
# 列表方法
print(len(numbers)) # 长度
print(max(numbers)) # 最大值
print(min(numbers)) # 最小值
print(sum(numbers)) # 总和
print(fruits.index("banana")) # 索引
print(fruits.count("apple")) # 计数
# 列表排序
numbers.sort()
print(numbers)
fruits.sort(reverse=True)
print(fruits)
# 列表推导式
squares = [x ** 2 for x in range(10)]
print(squares)
# 过滤
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)4.2 元组 (Tuple)
元组是有序不可变的序列,使用圆括号表示。
python
# 创建元组
coordinates = (10, 20)
person = ("John", 30, "New York")
# 访问元素
print(coordinates[0])
print(person[1])
# 元组不可修改
# coordinates[0] = 15 # 会报错
# 元组方法
print(len(person))
print(person.count("John"))
print(person.index(30))
# 元组解包
x, y = coordinates
print(x, y)
name, age, city = person
print(name, age, city)
# 单元素元组
single_element = (42,)
print(type(single_element))4.3 字典 (Dictionary)
字典是键值对的集合,使用花括号表示。
python
# 创建字典
person = {"name": "John", "age": 30, "city": "New York"}
# 访问元素
print(person["name"])
print(person.get("age"))
print(person.get("gender", "Unknown")) # 带默认值
# 修改元素
person["age"] = 31
person["gender"] = "Male"
print(person)
# 删除元素
del person["gender"]
print(person)
# 字典方法
print(len(person))
print(person.keys()) # 键
print(person.values()) # 值
print(person.items()) # 键值对
# 遍历字典
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key}: {value}")
# 字典推导式
squares = {x: x ** 2 for x in range(5)}
print(squares)
# 过滤
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares)4.4 集合 (Set)
集合是无序唯一元素的集合,使用花括号表示。
python
# 创建集合
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "cherry"}
# 添加元素
numbers.add(6)
print(numbers)
# 删除元素
numbers.remove(3) # 元素不存在会报错
numbers.discard(10) # 元素不存在不会报错
print(numbers)
# 集合操作
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1.union(set2)) # 并集
print(set1.intersection(set2)) # 交集
print(set1.difference(set2)) # 差集
print(set1.symmetric_difference(set2)) # 对称差集
# 集合推导式
even_numbers = {x for x in range(10) if x % 2 == 0}
print(even_numbers)
# 集合方法
print(len(numbers))
print(1 in numbers)
print(10 not in numbers)5. Python 模块与包
5.1 模块
模块是 Python 文件,包含函数、类和变量。
5.1.1 创建模块
创建一个名为 math_operations.py 的文件:
python
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "除数不能为零"
PI = 3.141595.1.2 导入模块
python
# 导入整个模块
import math_operations
print(math_operations.add(3, 5))
print(math_operations.PI)
# 导入特定函数
from math_operations import add, subtract
print(add(3, 5))
print(subtract(10, 4))
# 导入所有函数
from math_operations import *
print(multiply(2, 6))
print(divide(10, 2))
# 导入模块并重命名
import math_operations as mo
print(mo.add(3, 5))5.2 包
包是包含多个模块的目录,必须包含一个 __init__.py 文件。
5.2.1 创建包
my_package/
├── __init__.py
├── math_operations.py
└── string_operations.py__init__.py 文件:
python
# __init__.py
from .math_operations import add, subtract
from .string_operations import reverse, capitalize
__all__ = ["add", "subtract", "reverse", "capitalize"]string_operations.py 文件:
python
# string_operations.py
def reverse(s):
return s[::-1]
def capitalize(s):
return s.capitalize()5.2.2 导入包
python
# 导入包
import my_package
print(my_package.add(3, 5))
print(my_package.reverse("hello"))
# 导入包中的模块
from my_package import math_operations
print(math_operations.multiply(2, 6))
# 导入包中的函数
from my_package import add, reverse
print(add(3, 5))
print(reverse("hello"))
# 导入所有函数
from my_package import *
print(subtract(10, 4))
print(capitalize("hello"))5.3 标准库
Python 标准库包含许多有用的模块:
5.3.1 常用标准库
| 模块 | 描述 | 示例 |
|---|---|---|
os | 操作系统接口 | os.getcwd(), os.listdir() |
sys | Python 解释器相关 | sys.version, sys.argv |
math | 数学函数 | math.sqrt(), math.pi |
random | 随机数生成 | random.randint(), random.choice() |
datetime | 日期和时间 | datetime.datetime.now() |
json | JSON 处理 | json.dumps(), json.loads() |
csv | CSV 文件处理 | csv.reader(), csv.writer() |
re | 正则表达式 | re.search(), re.findall() |
urllib | URL 处理 | urllib.request.urlopen() |
collections | 容器数据类型 | collections.Counter(), collections.defaultdict() |
5.3.2 标准库使用示例
python
# os 模块
import os
print(os.getcwd()) # 当前工作目录
print(os.listdir(".")) # 列出当前目录文件
os.mkdir("test") # 创建目录
os.rmdir("test") # 删除目录
# datetime 模块
import datetime
now = datetime.datetime.now()
print(now)
print(now.year, now.month, now.day)
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# random 模块
import random
print(random.randint(1, 100)) # 1-100 之间的随机整数
print(random.choice(["apple", "banana", "cherry"])) # 随机选择元素
# json 模块
import json
# 字典转 JSON
data = {"name": "John", "age": 30, "city": "New York"}
json_str = json.dumps(data)
print(json_str)
# JSON 转字典
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data["name"])
# re 模块
import re
text = "Hello, my email is john@example.com"
email = re.search(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", text)
if email:
print(email.group())6. Python 面向对象编程
6.1 类与对象
python
# 定义类
class Person:
# 类变量
species = "Homo sapiens"
# 初始化方法
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
# 实例方法
def greet(self):
return f"Hello, my name is {self.name}"
def celebrate_birthday(self):
self.age += 1
return f"Happy birthday! I'm now {self.age} years old"
# 类方法
@classmethod
def get_species(cls):
return cls.species
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建对象
person1 = Person("John", 30)
person2 = Person("Jane", 25)
# 访问实例变量
print(person1.name)
print(person2.age)
# 调用实例方法
print(person1.greet())
print(person1.celebrate_birthday())
# 访问类变量
print(Person.species)
print(person1.species)
# 调用类方法
print(Person.get_species())
# 调用静态方法
print(Person.is_adult(18))
print(Person.is_adult(16))6.2 继承
python
# 父类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some generic sound"
# 子类
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# 创建对象
dog = Dog("Rex")
cat = Cat("Whiskers")
print(dog.name)
print(dog.speak())
print(cat.name)
print(cat.speak())
# 多重继承
class A:
def method(self):
return "A.method"
class B:
def method(self):
return "B.method"
class C(A, B):
pass
c = C()
print(c.method()) # 按照 MRO (Method Resolution Order) 查找
print(C.mro()) # 查看方法解析顺序6.3 多态
python
# 多态示例
def animal_speak(animal):
print(animal.speak())
dog = Dog("Rex")
cat = Cat("Whiskers")
animal_speak(dog) # 输出 "Woof!"
animal_speak(cat) # 输出 "Meow!"
# 抽象类
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
# 多态使用
def print_shape_info(shape):
print(f"Area: {shape.area()}")
print(f"Perimeter: {shape.perimeter()}")
rectangle = Rectangle(5, 3)
circle = Circle(4)
print_shape_info(rectangle)
print_shape_info(circle)6.4 封装与属性
python
class Person:
def __init__(self, name, age):
self._name = name # 受保护的属性
self.__age = age # 私有的属性
# 属性 getter
@property
def name(self):
return self._name
# 属性 setter
@name.setter
def name(self, value):
if isinstance(value, str):
self._name = value
else:
raise ValueError("Name must be a string")
# 私有属性的 getter
@property
def age(self):
return self.__age
# 私有属性的 setter
@age.setter
def age(self, value):
if isinstance(value, int) and value >= 0:
self.__age = value
else:
raise ValueError("Age must be a non-negative integer")
person = Person("John", 30)
# 访问属性
print(person.name)
print(person.age)
# 修改属性
person.name = "Jane"
person.age = 31
print(person.name)
print(person.age)
# 尝试设置无效值
# person.age = -5 # 会报错
# person.name = 123 # 会报错
# 尝试直接访问私有属性
# print(person.__age) # 会报错
# 但可以通过名称修饰访问
print(person._Person__age)7. Python 自动化脚本实战
7.1 文件操作
7.1.1 文件读写
python
# 写入文件
with open("example.txt", "w") as f:
f.write("Hello, Python!\n")
f.write("This is a test file.\n")
# 读取文件
with open("example.txt", "r") as f:
content = f.read()
print(content)
# 逐行读取
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
# 追加内容
with open("example.txt", "a") as f:
f.write("Adding a new line.\n")
# 读取所有行
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)7.1.2 文件和目录操作
python
import os
import shutil
# 创建目录
os.makedirs("test_dir", exist_ok=True)
# 复制文件
shutil.copy("example.txt", "test_dir/")
# 复制目录
shutil.copytree("test_dir", "test_dir_copy", dirs_exist_ok=True)
# 移动文件
shutil.move("test_dir/example.txt", "test_dir_copy/")
# 删除文件
os.remove("test_dir_copy/example.txt")
# 删除目录
shutil.rmtree("test_dir")
shutil.rmtree("test_dir_copy")
# 遍历目录
for root, dirs, files in os.walk("."):
print(f"Root: {root}")
print(f"Dirs: {dirs}")
print(f"Files: {files}")
print()7.2 系统管理
7.2.1 执行系统命令
python
import subprocess
# 执行命令并获取输出
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
print(result.stderr)
print(result.returncode)
# 执行 shell 命令
result = subprocess.run("echo 'Hello, World!'", shell=True, capture_output=True, text=True)
print(result.stdout)
# 管道命令
cmd = "ps aux | grep python"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
print(result.stdout)7.2.2 监控系统状态
python
import psutil
# 安装 psutil
# pip install psutil
# CPU 信息
print("CPU 核心数:", psutil.cpu_count())
print("CPU 使用率:", psutil.cpu_percent(interval=1))
# 内存信息
memory = psutil.virtual_memory()
print("总内存:", memory.total / (1024 ** 3), "GB")
print("可用内存:", memory.available / (1024 ** 3), "GB")
print("内存使用率:", memory.percent, "%")
# 磁盘信息
disks = psutil.disk_partitions()
for disk in disks:
print(f"磁盘: {disk.device}")
print(f"挂载点: {disk.mountpoint}")
usage = psutil.disk_usage(disk.mountpoint)
print(f"总空间: {usage.total / (1024 ** 3):.2f} GB")
print(f"已用空间: {usage.used / (1024 ** 3):.2f} GB")
print(f"可用空间: {usage.free / (1024 ** 3):.2f} GB")
print(f"使用率: {usage.percent}%")
print()
# 网络信息
net_io = psutil.net_io_counters()
print("发送字节数:", net_io.bytes_sent)
print("接收字节数:", net_io.bytes_recv)
# 进程信息
print("当前进程 ID:", os.getpid())
print("父进程 ID:", os.getppid())
# 列出所有进程
for proc in psutil.process_iter(['pid', 'name', 'username']):
try:
print(proc.info)
except psutil.NoSuchProcess:
pass7.3 网络操作
7.3.1 HTTP 请求
python
import requests
# 安装 requests
# pip install requests
# GET 请求
response = requests.get("https://api.github.com/users/octocat")
print(response.status_code)
print(response.json())
# POST 请求
data = {
"name": "John",
"email": "john@example.com"
}
response = requests.post("https://httpbin.org/post", json=data)
print(response.json())
# 带参数的请求
params = {
"q": "python",
"sort": "stars"
}
response = requests.get("https://api.github.com/search/repositories", params=params)
print(response.json())
# 带 headers 的请求
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get("https://example.com", headers=headers)
print(response.text)
# 文件下载
url = "https://www.python.org/static/img/python-logo.png"
response = requests.get(url)
with open("python-logo.png", "wb") as f:
f.write(response.content)
print("文件下载完成")7.3.2 网络爬虫
python
import requests
from bs4 import BeautifulSoup
# 安装 BeautifulSoup
# pip install beautifulsoup4
# 爬取网页
url = "https://en.wikipedia.org/wiki/Python_(programming_language)"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 提取标题
print("标题:", soup.title.text)
# 提取段落
paragraphs = soup.find_all("p")
for i, p in enumerate(paragraphs[:3]):
print(f"段落 {i+1}: {p.text.strip()}")
# 提取链接
links = soup.find_all("a", href=True)
for i, link in enumerate(links[:5]):
print(f"链接 {i+1}: {link['href']} - {link.text.strip()}")
# 提取图片
images = soup.find_all("img")
for i, img in enumerate(images[:3]):
print(f"图片 {i+1}: {img['src']}")7.4 自动化任务
7.4.1 定时任务
python
import schedule
import time
# 安装 schedule
# pip install schedule
def job():
print("执行定时任务...", time.strftime("%Y-%m-%d %H:%M:%S"))
# 每小时执行一次
schedule.every().hour.do(job)
# 每天特定时间执行
schedule.every().day.at("10:30").do(job)
# 每 5 分钟执行一次
schedule.every(5).minutes.do(job)
# 运行调度器
while True:
schedule.run_pending()
time.sleep(1)7.4.2 邮件发送
python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 邮件配置
sender_email = "your_email@example.com"
receiver_email = "recipient@example.com"
password = "your_password" # 建议使用应用密码
smtp_server = "smtp.gmail.com"
smtp_port = 587
# 创建邮件
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Python 自动化邮件测试"
# 邮件正文
body = "Hello,\n\nThis is an automated email sent from Python."
message.attach(MIMEText(body, "plain"))
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, password)
text = message.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()
print("邮件发送成功")
except Exception as e:
print(f"邮件发送失败: {e}")7.5 系统监控脚本
python
import psutil
import time
import smtplib
from email.mime.text import MIMEText
# 监控配置
CPU_THRESHOLD = 80 # CPU 使用率阈值
MEMORY_THRESHOLD = 80 # 内存使用率阈值
DISK_THRESHOLD = 80 # 磁盘使用率阈值
CHECK_INTERVAL = 60 # 检查间隔(秒)
# 邮件配置
SENDER_EMAIL = "your_email@example.com"
RECEIVER_EMAIL = "recipient@example.com"
PASSWORD = "your_password"
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
def send_alert(subject, message):
"""发送告警邮件"""
msg = MIMEText(message)
msg["From"] = SENDER_EMAIL
msg["To"] = RECEIVER_EMAIL
msg["Subject"] = subject
try:
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(SENDER_EMAIL, PASSWORD)
server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, msg.as_string())
server.quit()
print("告警邮件发送成功")
except Exception as e:
print(f"告警邮件发送失败: {e}")
def check_system():
"""检查系统状态"""
# 检查 CPU
cpu_usage = psutil.cpu_percent(interval=1)
if cpu_usage > CPU_THRESHOLD:
send_alert(
"CPU 使用率告警",
f"CPU 使用率过高: {cpu_usage}%\n阈值: {CPU_THRESHOLD}%"
)
# 检查内存
memory = psutil.virtual_memory()
memory_usage = memory.percent
if memory_usage > MEMORY_THRESHOLD:
send_alert(
"内存使用率告警",
f"内存使用率过高: {memory_usage}%\n阈值: {MEMORY_THRESHOLD}%"
)
# 检查磁盘
disk = psutil.disk_usage('/')
disk_usage = disk.percent
if disk_usage > DISK_THRESHOLD:
send_alert(
"磁盘使用率告警",
f"磁盘使用率过高: {disk_usage}%\n阈值: {DISK_THRESHOLD}%"
)
# 打印当前状态
print(f"\n检查时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"CPU 使用率: {cpu_usage}%")
print(f"内存使用率: {memory_usage}%")
print(f"磁盘使用率: {disk_usage}%")
def main():
"""主函数"""
print("系统监控脚本启动...")
print(f"检查间隔: {CHECK_INTERVAL}秒")
print(f"CPU 阈值: {CPU_THRESHOLD}%")
print(f"内存阈值: {MEMORY_THRESHOLD}%")
print(f"磁盘阈值: {DISK_THRESHOLD}%")
while True:
check_system()
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
main()7.6 配置管理脚本
python
import yaml
import json
# 安装 pyyaml
# pip install pyyaml
# 读取 YAML 配置
def read_yaml_config(file_path):
with open(file_path, "r") as f:
return yaml.safe_load(f)
# 写入 YAML 配置
def write_yaml_config(file_path, config):
with open(file_path, "w") as f:
yaml.dump(config, f, default_flow_style=False)
# 读取 JSON 配置
def read_json_config(file_path):
with open(file_path, "r") as f:
return json.load(f)
# 写入 JSON 配置
def write_json_config(file_path, config):
with open(file_path, "w") as f:
json.dump(config, f, indent=2)
# 示例配置
config = {
"database": {
"host": "localhost",
"port": 5432,
"name": "mydb",
"user": "admin",
"password": "password"
},
"server": {
"host": "0.0.0.0",
"port": 8080,
"debug": False
},
"logging": {
"level": "info",
"file": "app.log"
}
}
# 写入配置
write_yaml_config("config.yaml", config)
write_json_config("config.json", config)
print("配置文件写入完成")
# 读取配置
yaml_config = read_yaml_config("config.yaml")
json_config = read_json_config("config.json")
print("\n从 YAML 读取的配置:")
print(yaml_config)
print("\n从 JSON 读取的配置:")
print(json_config)
# 访问配置项
print(f"\n数据库主机: {yaml_config['database']['host']}")
print(f"服务器端口: {json_config['server']['port']}")8. Python 性能优化
8.1 代码优化技巧
8.1.1 算法优化
选择合适的数据结构:根据使用场景选择合适的数据结构
- 列表:适合随机访问和顺序操作
- 字典:适合键值对查找
- 集合:适合去重和成员检查
减少循环次数:
python# 不好的写法 for i in range(len(items)): print(items[i]) # 好的写法 for item in items: print(item)使用生成器:
python# 列表推导式 squares = [x ** 2 for x in range(1000000)] # 占用大量内存 # 生成器表达式 squares = (x ** 2 for x in range(1000000)) # 内存占用小使用内置函数:内置函数通常用 C 实现,执行速度更快
python# 不好的写法 total = 0 for i in range(1000): total += i # 好的写法 total = sum(range(1000))避免重复计算:
python# 不好的写法 for i in range(1000): if i > len(items) / 2: # 每次循环都计算 len(items) / 2 pass # 好的写法 half_length = len(items) / 2 for i in range(1000): if i > half_length: pass
8.1.2 内存优化
使用
__slots__:减少类实例的内存占用pythonclass Person: __slots__ = ['name', 'age', 'city'] def __init__(self, name, age, city): self.name = name self.age = age self.city = city使用
weakref:避免循环引用pythonimport weakref class Node: def __init__(self, value): self.value = value self.parent = None self.children = [] def add_child(self, child): child.parent = weakref.ref(self) self.children.append(child)使用
sys.getsizeof():检查对象的内存占用pythonimport sys print(sys.getsizeof([])) # 空列表的内存占用 print(sys.getsizeof([1, 2, 3])) # 包含元素的列表的内存占用
8.1.3 I/O 优化
使用
with语句:自动管理文件句柄python# 好的写法 with open("file.txt", "r") as f: content = f.read()使用缓冲 I/O:
python# 不好的写法 with open("file.txt", "w") as f: for i in range(1000): f.write(f"Line {i}\n") # 每次都写入 # 好的写法 lines = [f"Line {i}\n" for i in range(1000)] with open("file.txt", "w") as f: f.writelines(lines) # 一次写入使用
mmap:处理大文件pythonimport mmap with open("large_file.txt", "r+b") as f: # 创建内存映射 mm = mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ) # 查找内容 if mm.find(b"search_term") != -1: print("Found search term") # 关闭内存映射 mm.close()
8.2 性能分析工具
8.2.1 cProfile 模块
python
import cProfile
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# 性能分析
cProfile.run('fib(30)')
# 保存分析结果
cProfile.run('fib(30)', 'profile_stats')
# 分析结果
import pstats
from pstats import SortKey
p = pstats.Stats('profile_stats')
p.strip_dirs().sort_stats(SortKey.CUMULATIVE).print_stats(10)8.2.2 timeit 模块
python
import timeit
# 测试代码执行时间
time_taken = timeit.timeit(
stmt="x = 1 + 1",
number=1000000
)
print(f"执行时间: {time_taken:.6f} 秒")
# 测试函数执行时间
def test_function():
return sum(range(1000))
time_taken = timeit.timeit(
stmt="test_function()",
setup="from __main__ import test_function",
number=10000
)
print(f"函数执行时间: {time_taken:.6f} 秒")
# 测试代码块
code_block = """
x = 0
for i in range(1000):
x += i
"""
time_taken = timeit.timeit(
stmt=code_block,
number=10000
)
print(f"代码块执行时间: {time_taken:.6f} 秒")8.2.3 memory_profiler 模块
python
from memory_profiler import profile
# 安装 memory_profiler
# pip install memory_profiler
@profile
def memory_intensive_function():
# 创建大列表
large_list = [i for i in range(1000000)]
# 处理列表
result = sum(large_list)
# 删除大列表
del large_list
return result
# 运行函数
result = memory_intensive_function()
print(f"结果: {result}")8.2.4 line_profiler 模块
python
from line_profiler import LineProfiler
# 安装 line_profiler
# pip install line_profiler
def slow_function():
total = 0
for i in range(1000):
for j in range(1000):
total += i * j
return total
# 创建行分析器
lp = LineProfiler()
# 包装函数
lp_wrapper = lp(slow_function)
# 运行函数
result = lp_wrapper()
# 打印分析结果
lp.print_stats()8.3 并行计算
8.3.1 多线程
python
import threading
import time
# 全局变量
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
with lock:
counter += 1
def decrement():
global counter
for _ in range(100000):
with lock:
counter -= 1
# 创建线程
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=decrement)
# 启动线程
thread1.start()
thread2.start()
# 等待线程完成
thread1.join()
thread2.join()
print(f"最终计数器值: {counter}")8.3.2 多进程
python
from multiprocessing import Process, Queue, Pool
import time
def square(n):
return n * n
# 使用进程池
if __name__ == "__main__":
# 创建进程池
with Pool(processes=4) as pool:
# 映射函数到数据
results = pool.map(square, range(10))
print(results)
# 使用进程队列
def worker(queue):
while True:
item = queue.get()
if item is None:
break
result = square(item)
print(f"处理 {item} -> {result}")
if __name__ == "__main__":
# 创建队列
queue = Queue()
# 创建进程
processes = []
for i in range(2):
p = Process(target=worker, args=(queue,))
p.start()
processes.append(p)
# 添加任务
for i in range(5):
queue.put(i)
# 添加终止信号
for _ in processes:
queue.put(None)
# 等待进程完成
for p in processes:
p.join()8.3.3 异步编程
python
import asyncio
async def task1():
print("开始执行任务 1")
await asyncio.sleep(2)
print("任务 1 完成")
return "任务 1 结果"
async def task2():
print("开始执行任务 2")
await asyncio.sleep(1)
print("任务 2 完成")
return "任务 2 结果"
async def main():
# 并行执行任务
task1_result, task2_result = await asyncio.gather(task1(), task2())
print(f"任务 1 结果: {task1_result}")
print(f"任务 2 结果: {task2_result}")
# 运行主协程
if __name__ == "__main__":
asyncio.run(main())9. 总结与展望
9.1 Python 的优势
- 简单易学:语法简洁明了,学习曲线平缓
- 生态丰富:拥有庞大的标准库和第三方库
- 跨平台:可以在各种操作系统上运行
- 多范式:支持面向对象、函数式和过程式编程
- 强大的社区:拥有活跃的社区支持和丰富的学习资源
- 广泛的应用:在 Web 开发、数据科学、人工智能等领域都有广泛应用
9.2 Python 的局限性
- 执行速度:相比编译型语言(如 C++、Go),执行速度较慢
- 内存消耗:相比其他语言,内存消耗较大
- 移动开发:在移动开发领域的应用相对较少
- 多线程性能:由于 GIL(全局解释器锁)的存在,多线程性能有限
- 打包后的文件大小:打包后的可执行文件较大
9.3 Python 的未来发展
- Python 4.0:计划中的 Python 4.0 版本,预计会带来更多改进
- 类型提示:类型提示的使用会越来越广泛,提高代码的可维护性
- 异步编程:异步编程会成为主流,特别是在 I/O 密集型应用中
- 机器学习和人工智能:Python 在机器学习和人工智能领域的应用会继续增长
- Web 开发:FastAPI 等现代 Web 框架会越来越受欢迎
- DevOps 和自动化:Python 在 DevOps 和自动化领域的应用会继续扩大
- 嵌入式开发:MicroPython 和 CircuitPython 会在嵌入式领域发挥更大作用
9.4 学习建议
- 基础先行:掌握 Python 基础语法和核心概念
- 实践为主:通过实际项目练习,巩固所学知识
- 学习标准库:熟悉 Python 标准库,提高开发效率
- 使用第三方库:根据需要学习和使用第三方库
- 代码风格:遵循 PEP 8 代码风格指南,编写规范的代码
- 版本管理:使用 Git 等版本控制工具管理代码
- 持续学习:关注 Python 的最新发展和最佳实践
- 参与社区:加入 Python 社区,分享知识和经验
9.5 资源推荐
- 官方文档:Python 官方文档
- 教程:
- 书籍:
- 《Python 编程:从入门到实践》
- 《流畅的 Python》
- 《Python cookbook》
- 《Effective Python》
- 在线练习:
- 社区:
通过本文的学习,您应该已经掌握了 Python 的基础语法和自动化脚本开发技能。Python 是一种功能强大且易于学习的编程语言,适合各种自动化任务和应用开发。随着您的不断实践和学习,您将能够使用 Python 解决更多复杂的问题,提高工作效率。