【万字总结】Python实用速查表:日常任务的高效编程指南
Python实用速查表:日常任务的高效编程指南
一、引言
这份速查表源于实际需求。
我将各个部分划分为逻辑连贯的区域,这些区域通常协同工作。如此一来,可以迅速跳转到感兴趣的部分,并找到与特定任务或主题最为相关的内容。
这其中包括文件操作、API交互、电子表格处理、数学计算以及对列表和字典等数据结构的操作。此外,我还会着重介绍一些实用的库,以增强您的Python工具包,这些库在Python的常见应用领域中广泛使用。
二、使用文件
1. 读取文件
要读取文件的全部内容:
# 使用 with 语句打开文件,确保文件正确关闭
with open('example.txt', 'r') as file:
# 读取文件全部内容到 content 变量
content = file.read()
print(content)
2. 写入文件
要将文本写入文件,覆盖现有内容:
# 以写入模式('w')打开文件,这会覆盖原有内容
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
3. 追加到文件
要将文本添加到现有文件的末尾:
# 以追加模式('a')打开文件,新内容会添加到文件末尾
with open('example.txt', 'a') as file:
file.write('\nAppend this line.')
4. 将行读入列表
要将文件逐行读入列表:
# readlines() 方法读取所有行并返回一个列表
with open('example.txt', 'r') as file:
lines = file.readlines() # 每一行作为列表中的一个元素
print(lines)
5. 迭代文件中的每一行
要处理文件中的每一行:
# 直接迭代文件对象,这种方式更节省内存
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # strip() 移除行末的换行符
6. 检查文件是否存在
要在执行文件操作之前检查文件是否存在:
import os
# os.path.exists() 检查文件或目录是否存在
if os.path.exists('example.txt'):
print('File exists.')
else:
print('File does not exist.')
7. 将列表写入文件
要将列表的每个元素写入文件中的新行:
# 准备要写入的行列表
lines = ['First line', 'Second line', 'Third line']
# 以写入模式打开文件
with open('example.txt', 'w') as file:
for line in lines:
file.write(f'{line}\n') # 每行末尾添加换行符
8. 对多个文件使用with块
要使用with
块同时处理多个文件:
# 同时打开源文件和目标文件
with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
content = source.read() # 读取源文件内容
destination.write(content) # 写入目标文件
9. 删除文件
要安全删除文件(如果存在):
import os
# 先检查文件是否存在,再删除
if os.path.exists('example.txt'):
os.remove('example.txt') # 删除文件
print('File deleted.')
else:
print('File does not exist.')
10. 读取和写入二进制文件
要以二进制模式读取和写入文件(对图像、视频等有用):
# 以二进制读取模式('rb')打开源文件
with open('image.jpg', 'rb') as file:
content = file.read()
# 以二进制写入模式('wb')创建副本
with open('copy.jpg', 'wb') as file:
file.write(content)
三、使用简单的HTTP API
1. 基本GET请求
要使用GET请求从API端点获取数据:
# 导入requests库用于HTTP请求
import requests
# 发送GET请求并获取响应
response = requests.get('https://api.example.com/data')
data = response.json() # 将响应解析为JSON格式
print(data)
2. 带有查询参数的GET请求
要发送包含查询参数的GET请求:
import requests
# 定义查询参数字典
params = {'key1': 'value1', 'key2': 'value2'}
# 发送带参数的GET请求
response = requests.get('https://api.example.com/search', params=params)
data = response.json()
print(data)
3. 处理HTTP错误
要优雅地处理可能的HTTP错误:
import requests
# 发送请求
response = requests.get('https://api.example.com/data')
try:
# 检查响应状态码,如果不是2xx则抛出异常
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.HTTPError as err:
print(f'HTTP Error: {err}')
4. 设置请求的超时时间
要为API请求设置超时以避免无限期挂起:
import requests
try:
# timeout=5 表示如果服务器5秒内没有响应就抛出异常
response = requests.get('https://api.example.com/data', timeout=5)
data = response.json()
print(data)
except requests.exceptions.Timeout:
print('The request timed out')
5. 在请求中使用标头
要在请求中包含标头(例如,用于授权):
import requests
# 定义请求头,包含授权信息
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
# 发送带有自定义头的请求
response = requests.get('https://api.example.com/protected', headers=headers)
data = response.json()
print(data)
6. 带有JSON有效负载的POST请求
要使用带有JSON负载的POST请求将数据发送到API端点:
import requests
# 准备要发送的JSON数据
payload = {'key1': 'value1', 'key2': 'value2'}
# 设置Content-Type头
headers = {'Content-Type': 'application/json'}
# 发送POST请求,自动将payload转换为JSON
response = requests.post('https://api.example.com/submit', json=payload, headers=headers)
print(response.json())
7. 处理响应编码
要正确处理响应编码:
import requests
# 发送请求
response = requests.get('https://api.example.com/data')
# 设置响应的编码为utf-8
response.encoding = 'utf-8'
# 获取解码后的文本内容
data = response.text
print(data)
8. 将会话与请求一起使用
要使用session对象向同一主机发出多个请求,以提高性能:
import requests
# 创建会话对象,在多个请求之间复用连接
with requests.Session() as session:
# 为所有请求设置通用的头信息
session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})
# 使用会话发送请求
response = session.get('https://api.example.com/data')
print(response.json())
9. 处理重定向
要处理或禁用请求中的重定向:
import requests
# allow_redirects=False 禁止自动跟随重定向
response = requests.get('https://api.example.com/data', allow_redirects=False)
print(response.status_code) # 如果有重定向会返回3xx状态码
10. 流式处理大型响应
要流式传输大型响应以块形式处理,而不是将其全部加载到内存中:
import requests
# stream=True 启用流式传输
response = requests.get('https://api.example.com/large-data', stream=True)
# 以1KB为单位逐块处理响应内容
for chunk in response.iter_content(chunk_size=1024):
process(chunk) # 处理每个数据块
四、使用列表
1. 创建列表
要创建一个列表:
# 创建一个包含四个元素的基本列表
elements = ['Earth', 'Air', 'Fire', 'Water']
2. 追加到列表
要将新元素追加到列表末尾:
# append() 方法将元素添加到列表末尾
elements.append('Aether')
3. 插入到列表
要在列表中的特定位置插入元素:
# insert(位置, 元素) 在指定位置插入新元素
elements.insert(1, 'Spirit') # 在索引1处插入'Spirit'
4. 从列表中删除
要从列表中按值删除元素:
# remove() 删除第一个匹配的元素
elements.remove('Earth') # 删除值为'Earth'的元素
5. 从列表中弹出一个元素
要删除并返回给定索引处的元素(默认为最后一项):
# pop() 移除并返回最后一个元素
last_element = elements.pop() # 不带参数时删除最后一个元素
6. 查找元素的索引
要查找元素第一次出现的索引:
# index() 返回元素首次出现的位置
index_of_air = elements.index('Air') # 获取'Air'的索引位置
7. 列表切片
要对列表进行切片,获取子列表:
# 切片语法:[起始:结束:步长],结果包含起始不包含结束
sub_elements = elements[1:4] # 获取索引1到3的元素
8. 列表推导
要通过将表达式应用于现有列表的每个元素来创建新列表:
# 列表推导式提供了创建新列表的简洁方式
lengths = [len(element) for element in elements] # 计算每个元素的长度
9. 对列表进行排序
要按升序对列表进行排序(就地):
# sort() 方法直接修改原列表
elements.sort() # 按字母顺序排序
10. 反转列表
要就地反转列表的元素:
# reverse() 方法将列表元素顺序颠倒
elements.reverse() # 反转列表中元素的顺序
五、使用字典
1. 创建词典
要创建一个新词典:
# 创建包含键值对的字典
elements = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li'} # 元素名称和符号的映射
2. 添加或更新条目
要添加新条目或更新现有条目:
# 使用键值赋值来添加或更新字典条目
elements['Carbon'] = 'C' # 添加新元素或更新已存在的元素
3. 删除条目
要从字典中删除条目:
# del 语句用于删除字典中的条目
del elements['Lithium'] # 删除键为'Lithium'的条目
4. 检查Key是否存在
要检查键是否存在于字典中:
# 使用 in 运算符检查键是否存在
if 'Helium' in elements: # 检查'Helium'是否在字典中
print('Helium is present')
5. 迭代Key
要遍历字典中的键:
# 直接遍历字典会遍历所有的键
for element in elements:
print(element)
6. 迭代值
要遍历字典中的值:
# 使用values()方法遍历字典的所有值
for symbol in elements.values():
print(symbol)
7. 迭代项目
要同时遍历字典的键和值:
# 使用items()方法同时获取键和值
for element, symbol in elements.items():
print(f'{element}: {symbol}')
8. 字典理解
要通过对可迭代对象施咒来创建新字典:
# 使用字典推导式创建平方数字典
squares = {x: x**2 for x in range(5)} # 生成0-4的平方映射
9. 合并词典
要合并两个或多个词典,形成它们条目的新联盟:
# 创建两个独立的字典
alchemists = {'Paracelsus': 'Mercury'}
philosophers = {'Plato': 'Aether'}
# 使用解包运算符(**)合并字典
merged = {**alchemists, **philosophers} # Python 3.5+的字典合并方式
10. 使用default获取值
要安全地检索值,为缺失的键提供默认值:
# get()方法在键不存在时返回默认值
element = elements.get('Neon', 'Unknown') # 如果'Neon'不存在,返回'Unknown'
六、使用操作系统
1. 导航文件路径
要制作和剖析路径,确保跨操作系统的兼容性:
import os
# 使用os.path.join()创建跨平台兼容的路径
path = os.path.join('mystic', 'forest', 'artifact.txt')
# 获取路径中的目录部分
directory = os.path.dirname(path)
# 获取路径中的文件名部分
artifact_name = os.path.basename(path)
2. 列出目录内容
要揭示目录中的所有文件和子目录:
import os
# listdir()返回指定目录中的所有文件和文件夹名称
contents = os.listdir('enchanted_grove')
print(contents) # 打印目录内容列表
3. 创建目录
要在文件系统中创建新目录:
import os
# mkdir()创建单个目录
os.mkdir('alchemy_lab')
# makedirs()创建多级目录结构,包括所有必要的父目录
os.makedirs('alchemy_lab/potions/elixirs')
4. 删除文件和目录
要删除文件或目录:
import os
# remove()删除单个文件
os.remove('unnecessary_scroll.txt')
# rmdir()删除空目录
os.rmdir('abandoned_hut')
import shutil
# rmtree()递归删除目录及其所有内容
shutil.rmtree('cursed_cavern')
5. 执行Shell命令
要直接从Python调用Shell命令:
import subprocess
# run()执行shell命令并捕获输出
result = subprocess.run(['echo', 'Revealing the arcane'],
capture_output=True, # 捕获命令输出
text=True) # 将输出作为文本返回
print(result.stdout)
6. 使用环境变量
要读取和设置环境变量:
import os
# 获取系统环境变量PATH的值
path = os.environ.get('PATH')
# 设置新的环境变量
os.environ['MAGIC'] = 'Arcane'
7. 更改当前工作目录
要将当前工作目录切换到文件系统中的另一个目录:
import os
# 切换到指定目录
os.chdir('arcane_library')
8. 路径存在和类型
要辨别路径的存在及其性质(是文件还是目录):
import os
# 检查路径是否存在
exists = os.path.exists('mysterious_ruins')
# 检查是否是目录
is_directory = os.path.isdir('mysterious_ruins')
# 检查是否是文件
is_file = os.path.isfile('ancient_manuscript.txt')
9. 使用临时文件
要创建临时文件和目录:
import tempfile
# 创建临时文件,不会自动删除
temp_file = tempfile.NamedTemporaryFile(delete=False)
print(temp_file.name) # 打印临时文件的路径
# 创建临时目录
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name) # 打印临时目录的路径
10. 获取系统信息
要获取有关主机系统的信息,包括其名称和支持的特性:
import os
import platform
# 获取操作系统类型(如:'posix', 'nt')
os_name = os.name
# 获取操作系统名称(如:'Linux', 'Windows')
system_info = platform.system()
七、使用CLI(命令行界面)
1. 读取用户输入
从STDIN获取输入:
# 从控制台读取用户输入
user_input = input("Impart your wisdom: ")
# 打印用户输入的内容
print(f"You shared: {user_input}")
2. 打印到STDOUT
要将消息打印到控制台:
# 使用print函数将消息输出到标准输出
print("Behold, the message of the ancients!")
3. 格式打印
要优雅而精确地将变量嵌入到消息中:
# 定义变量
name = "Merlin"
age = 300
# 使用f-string格式化字符串
print(f"{name}, of {age} years, speaks of forgotten lore.")
4. 从STDIN读取行
从STDIN逐行修剪空格:
import sys
# 从标准输入逐行读取
for line in sys.stdin:
# strip()移除行首行尾的空白字符
print(f"Echo from the void: {line.strip()}")
5. 写信给STDERR
要向STDERR发送消息:
import sys
# 将错误消息写入标准错误流
sys.stderr.write("Beware! The path is fraught with peril.\n")
6. 重定向STDOUT
要重定向STDOUT:
import sys
# 保存原始的标准输出
original_stdout = sys.stdout
# 将标准输出重定向到文件
with open('mystic_log.txt', 'w') as f:
sys.stdout = f
print("This message is inscribed within the mystic_log.txt.")
# 恢复原始的标准输出
sys.stdout = original_stdout
7. 重定向STDERR
要重定向STDERR:
import sys
# 将标准错误流重定向到文件
with open('warnings.txt', 'w') as f:
sys.stderr = f
print("This warning is sealed within warnings.txt.", file=sys.stderr)
8. 提示输入密码
要提示输入密码:
import getpass
# 安全地读取密码输入(不显示输入的字符)
secret_spell = getpass.getpass("Whisper the secret spell: ")
9. 命令行参数
使用和解析命令行参数:
import sys
# 解包命令行参数(脚本名称和参数)
script, first_arg, second_arg = sys.argv
# 打印传入的参数
print(f"Invoked with the sacred tokens: {first_arg} and {second_arg}")
10. 使用Argparse进行复杂的CLI交互
添加描述和选项/参数:
import argparse
# 创建参数解析器对象
parser = argparse.ArgumentParser(description="Invoke the ancient scripts.")
# 添加位置参数
parser.add_argument('spell', help="The spell to cast")
# 添加可选参数
parser.add_argument('--power', type=int, help="The power level of the spell")
# 解析命令行参数
args = parser.parse_args()
# 使用解析后的参数
print(f"Casting {args.spell} with power {args.power}")
八、使用数学运算和排列
1. 基本算术运算
要执行基本算术运算:
# 加法运算
sum_result = 7 + 3
# 减法运算
difference = 7 - 3
# 乘法运算
product = 7 * 3
# 除法运算(返回浮点数)
quotient = 7 / 3
# 取余运算(求除法的余数)
remainder = 7 % 3
# 幂运算(7的3次方)
power = 7 ** 3
2. 使用复数
要使用复数:
# 创建一个复数 (2 + 3i)
z = complex(2, 3)
# 获取复数的实部
real_part = z.real
# 获取复数的虚部
imaginary_part = z.imag
# 获取复数的共轭
conjugate = z.conjugate()
3. 数学函数
常见的数学函数:
import math
# 计算平方根
root = math.sqrt(16)
# 计算以10为底的对数
logarithm = math.log(100, 10)
# 计算正弦值(参数为弧度)
sine = math.sin(math.pi / 2)
4. 生成排列
从给定集合生成排列的简单方法:
from itertools import permutations
# 生成[1,2,3]的所有可能排列
paths = permutations([1, 2, 3])
# 遍历并打印每个排列
for path in paths:
print(path) # 输出所有可能的排列组合
5. 生成组合
生成组合的简单方法:
from itertools import combinations
# 从[1,2,3,4]中选择2个元素的所有可能组合
combos = combinations([1, 2, 3, 4], 2)
# 遍历并打印每个组合
for combo in combos:
print(combo) # 输出所有可能的组合
6. 随机数生成
要获取随机数:
import random
# randint(a,b)生成一个位于[a,b]区间的随机整数
num = random.randint(1, 100) # 生成1到100之间的随机数
7. 使用分数
当需要处理分数时:
from fractions import Fraction
# 创建一个分数对象(3/4)
f = Fraction(3, 4)
# 分数可以直接与整数进行运算
print(f + 1) # 输出: 7/4
8. 统计函数
要获取平均值、中位数和标准差:
import statistics
data = [1, 2, 3, 4]
# 计算算术平均值
mean = statistics.mean(data)
# 计算中位数(数据中心位置的值)
median = statistics.median(data)
# 计算样本标准差(数据离散程度)
std_dev = statistics.stdev(data)
9. 矩阵运算
要执行基本的矩阵运算:
import numpy as np
# 创建两个2x2矩阵
matrix_a = np.array([[1, 2], [3, 4]]) # 第一个矩阵
matrix_b = np.array([[5, 6], [7, 8]]) # 第二个矩阵
# 矩阵加法(对应元素相加)
sum_matrix = matrix_a + matrix_b
# 矩阵乘法(线性代数运算)
product_matrix = np.dot(matrix_a, matrix_b)
10. 三角函数
要使用三角函数:
import math
# 计算正弦值(参数必须是弧度)
sin_value = math.sin(math.pi / 2) # sin(90度)
# 计算余弦值
cos_value = math.cos(math.pi) # cos(180度)
# 将角度转换为弧度
radians = math.radians(180) # 180度转换为π弧度
九、使用日期和时间
1. 获取当前日期和时间
from datetime import datetime
# 获取当前系统日期和时间
now = datetime.now()
# 将日期时间格式化为字符串,使用指定格式
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") # 如:2024-01-05 20:21:14
print(formatted_date)
2. 日期计算
from datetime import datetime, timedelta
# 获取当前日期时间
today = datetime.now()
# 使用timedelta进行日期运算,计算一周后
one_week_later = today + timedelta(days=7)
# 计算两个日期之间的时间差
difference = one_week_later - today # 返回timedelta对象
3. 时区处理
from datetime import datetime
import pytz
# 创建特定时区对象(如上海时区)
timezone = pytz.timezone('Asia/Shanghai')
# 获取指定时区的当前时间
local_time = datetime.now(timezone)
# 将时间转换为UTC时间
utc_time = local_time.astimezone(pytz.UTC) # 转换为协调世界时
4. 解析日期字符串
from datetime import datetime
# 将日期字符串转换为datetime对象
date_string = "2024-01-01 12:00:00"
# strptime解析字符串为datetime对象,指定格式
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
# 从datetime对象中提取具体的日期部分
year = parsed_date.year # 获取年份
month = parsed_date.month # 获取月份
day = parsed_date.day # 获取日期
十、使用正则表达式
1. 基本模式匹配
import re
# 准备要搜索的文本
text = "Python programming is fun"
# 使用search()在文本中查找模式
match = re.search(r'Python', text) # r前缀表示原始字符串,避免转义符问题
if match:
print("Found Python!") # 如果找到匹配项则打印
2. 提取信息
import re
# 包含数字的示例文本
text = "The price is $19.99 and quantity is 5"
# 使用findall()提取所有数字(包括小数)
numbers = re.findall(r'\d+\.?\d*', text) # \d+匹配多个数字,\.?匹配可选的小数点,\d*匹配小数点后的数字
print(numbers) # 输出: ['19.99', '5']
3. 替换文本
import re
# 原始文本
text = "I love cats, cats are great"
# 使用sub()替换文本中的所有匹配项
new_text = re.sub(r'cats', 'dogs', text) # 将所有'cats'替换为'dogs'
print(new_text) # 输出替换后的文本
4. 分割文本
import re
# 包含多个分隔符的文本
text = "apple,banana;orange:grape"
# 使用split()基于多个分隔符分割文本
fruits = re.split(r'[,;:]', text) # 使用字符类[,;:]匹配任意一个分隔符
print(fruits) # 输出分割后的列表
5. 验证格式
import re
# 定义电子邮件验证函数
def is_valid_email(email):
# 电子邮件格式的正则表达式模式
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
# 使用match()验证整个字符串是否匹配模式
return bool(re.match(pattern, email))
# 测试不同的电子邮件地址
print(is_valid_email("user@example.com")) # 有效的邮箱地址
print(is_valid_email("invalid.email")) # 无效的邮箱地址
十一、多线程与多进程
1. 多线程基础
多线程允许程序在同一进程内并发执行多个线程,每个线程独立运行且共享进程资源,适用于I/O密集型任务(如网络请求、文件读写等),可提高程序响应速度。
2. 使用threading
模块
import threading
def print_numbers():
for i in range(1, 6):
print(i)
def print_letters():
for letter in 'abcde':
print(letter)
# 创建线程对象,指定目标函数
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
import threading
# 共享资源
counter = 0
# 创建锁对象
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
# 获取锁
lock.acquire()
try:
counter += 1
finally:
# 释放锁
lock.release()
# 创建多个线程并启动
threads = []
for _ in range(5):
thread = threading.Thread(target=increment)
threads.append(thread)
thread.start()
# 等待所有线程结束
for thread in threads:
thread.join()
print(counter)
3. 多进程基础
多进程将任务分配到多个进程中并行执行,每个进程有独立的内存空间,适用于计算密集型任务(如数学计算、图像处理等),可充分利用多核CPU优势提高计算速度。
4. 使用multiprocessing
模块
from multiprocessing import Process
def square(x):
return x ** 2
if __name__ == '__main__':
# 创建进程对象,指定目标函数和参数
processes = []
for i in range(1, 6):
process = Process(target=square, args=(i,))
processes.append(process)
process.start()
# 等待进程结束
for process in processes:
process.join()
Queue
):进程间无法直接共享数据,需使用Queue
等方式进行通信。from multiprocessing import Process, Queue
def producer(queue):
for i in range(1, 6):
queue.put(i)
def consumer(queue):
while True:
if queue.empty():
break
item = queue.get()
print(item ** 2)
if __name__ == '__main__':
# 创建队列对象
queue = Queue()
# 创建生产者进程和消费者进程
p1 = Process(target=producer, args=(queue,))
p2 = Process(target=consumer, args=(queue,))
p1.start()
p1.join()
p2.start()
p2.join()
5. 线程池与进程池
线程池和进程池可管理多个线程或进程,重复利用线程或进程执行任务,减少创建和销毁开销,提高性能。
6. 使用concurrent.futures
模块
from concurrent.futures import ThreadPoolExecutor
def print_number(number):
print(number)
# 创建线程池对象,指定最大线程数
with ThreadPoolExecutor(max_workers=3) as executor:
numbers = [1, 2, 3, 4, 5]
# 提交任务到线程池
futures = [executor.submit(print_number, number) for number in numbers]
# 等待所有任务完成
for future in futures:
future.result()
from concurrent.futures import ProcessPoolExecutor
def square(x):
return x ** 2
if __name__ == '__main__':
# 创建进程池对象,指定最大进程数
with ProcessPoolExecutor(max_workers=2) as executor:
numbers = [1, 2, 3, 4, 5]
# 提交任务到进程池
futures = [executor.submit(square, number) for number in numbers]
# 等待所有任务完成
for future in futures:
print(future.result())
7. 多线程与多进程的选择
十二、数据库操作
1. 数据库操作概述
在Python中,数据库操作是许多应用程序的重要组成部分。无论是Web开发、数据分析还是自动化脚本,与数据库交互都至关重要。Python提供了丰富的库和工具,使得连接和操作各种数据库变得相对容易。以下将介绍常见数据库的操作,包括MySQL、PostgreSQL等,并展示如何将查询结果转换为Pandas数据格式,以便进行进一步的数据分析和处理。
2. MySQL数据库操作
连接到MySQL数据库
使用mysql-connector-python
库来连接MySQL数据库。首先确保已安装该库(pip install mysql-connector-python
)。
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost", # 数据库主机地址
user="your_user", # 用户名
password="your_password", # 密码
database="your_database" # 数据库名称
)
# 创建游标对象,用于执行SQL语句
mycursor = mydb.cursor()
** 插入数据**
向数据库表中插入新数据。
# SQL插入语句
sql = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
val = ("value1", "value2")
# 执行插入操作
mycursor.execute(sql, val)
# 提交事务,使插入生效
mydb.commit()
print(mycursor.rowcount, "记录插入成功。")
查询数据
从数据库表中检索数据。
# SQL查询语句
sql = "SELECT * FROM your_table"
# 执行查询操作
mycursor.execute(sql)
# 获取所有查询结果
results = mycursor.fetchall()
for row in results:
print(row)
更新数据
修改数据库表中已存在的数据。
# SQL更新语句
sql = "UPDATE your_table SET column1 = %s WHERE column2 = %s"
val = ("new_value", "condition_value")
# 执行更新操作
mycursor.execute(sql, val)
# 提交事务,使更新生效
mydb.commit()
print(mycursor.rowcount, "记录被更新。")
删除数据
从数据库表中删除数据。
# SQL删除语句
sql = "DELETE FROM your_table WHERE condition_column = %s"
val = ("condition_value",)
# 执行删除操作
mycursor.execute(sql, val)
# 提交事务,使删除生效
mydb.commit()
print(mycursor.rowcount, "记录被删除。")
3. PostgreSQL数据库操作
连接到PostgreSQL数据库
使用psycopg2
库连接PostgreSQL数据库(pip install psycopg2
)。
import psycopg2
# 建立数据库连接
conn = psycopg2.connect(
dbname="your_database",
user="your_user",
password="your_password",
host="your_host"
)
# 创建游标对象
cur = conn.cursor()
插入数据
向PostgreSQL数据库表插入数据。
# SQL插入语句
sql = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
val = ("value1", "value2")
# 执行插入操作
cur.execute(sql, val)
# 提交事务
conn.commit()
print(cur.rowcount, "记录插入成功。")
查询数据
从PostgreSQL数据库表中检索数据。
# SQL查询语句
sql = "SELECT * FROM your_table"
# 执行查询操作
cur.execute(sql)
# 获取所有查询结果
results = cur.fetchall()
for row in results:
print(row)
更新数据
更新PostgreSQL数据库表中的数据。
# SQL更新语句
sql = "UPDATE your_table SET column1 = %s WHERE column2 = %s"
val = ("new_value", "condition_value")
# 执行更新操作
cur.execute(sql, val)
# 提交事务
conn.commit()
print(cur.rowcount, "记录被更新。")
删除数据
从PostgreSQL数据库表中删除数据。
# SQL删除语句
sql = "DELETE FROM your_table WHERE condition_column = %s"
val = ("condition_value",)
# 执行删除操作
cur.execute(sql, val)
# 提交事务
conn.commit()
print(cur.rowcount, "记录被删除。")
4. 将数据库查询结果转换为Pandas格式
pandas
是Python中强大的数据处理库,将数据库查询结果转换为pandas
的DataFrame
格式,能方便地进行数据分析和处理。
对于MySQL查询结果
假设已完成上述MySQL查询操作并获取了results
。
import pandas as pd
# 使用查询结果创建DataFrame
df = pd.DataFrame(results, columns=[desc[0] for desc in mycursor.description])
print(df)
对于PostgreSQL查询结果
假设已完成上述PostgreSQL查询操作并获取了results
。
import pandas as pd
# 使用查询结果创建DataFrame
df = pd.DataFrame(results, columns=[desc[0] for desc in cur.description])
print(df)
通过以上步骤,可在Python中实现对MySQL和PostgreSQL数据库的基本操作,并将查询结果转换为pandas
格式,便于后续的数据处理工作。在实际应用中,根据具体需求构建更复杂的数据库操作逻辑。
十三、自动化脚本与任务调度
1. 自动化脚本基础
自动化脚本能够自动执行重复性任务,减少人工干预,提高工作效率。在Python中,可通过系统命令执行、文件操作、数据处理等功能实现各种自动化任务场景,如定期备份文件、批量处理数据、自动化测试等。
2. 使用subprocess
模块执行外部命令
subprocess
模块允许在Python脚本中创建新进程并与之通信,从而执行系统命令或其他外部程序。
执行简单命令
执行一个简单的系统命令,如列出当前目录下的文件列表。
import subprocess
# 执行系统命令 'ls'(在Windows上可改为 'dir')
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
执行带参数命令
执行一个带参数的命令,如使用grep
在文件中查找特定字符串。
import subprocess
# 执行 'grep' 命令查找特定字符串
command = ['grep', 'python', 'example.txt']
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode == 0:
print(result.stdout)
else:
print(f"未找到匹配项: {result.stderr}")
3. 任务调度基础
任务调度用于在特定时间或按照一定时间间隔自动执行任务。Python中有多种任务调度库可供选择,可根据任务需求和系统环境进行选择。
4. 使用APScheduler
库进行任务调度
APScheduler
是一个强大的Python任务调度库,支持多种调度方式,如定时调度、间隔调度和一次性调度。
安装APScheduler
使用pip install apscheduler
安装该库。
定时执行任务
创建一个任务,每天凌晨2点执行备份数据的函数。
from apscheduler.schedulers.background import BackgroundScheduler
import time
def backup_data():
print("正在执行数据备份...")
# 这里添加实际的数据备份代码,如复制文件到备份目录等
# 创建后台调度器对象
scheduler = BackgroundScheduler()
# 添加定时任务,每天凌晨2点执行备份函数
scheduler.add_job(backup_data, 'cron', hour=2)
# 启动调度器
scheduler.start()
try:
# 保持主线程运行,防止程序退出
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
# 关闭调度器
scheduler.shutdown()
间隔执行任务
创建一个任务,每隔5分钟检查一次系统状态。
from apscheduler.schedulers.background import BackgroundScheduler
import psutil
def check_system_status():
cpu_usage = psutil.cpu_percent()
memory_usage = psutil.virtual_memory().percent
print(f"CPU使用率: {cpu_usage}%,内存使用率: {memory_usage}%")
# 创建后台调度器对象
scheduler = BackgroundScheduler()
# 添加间隔任务,每隔5分钟执行系统状态检查函数
scheduler.add_job(check_system_status, 'interval', minutes=5)
# 启动调度器
scheduler.start()
try:
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()
十四、图像处理
1. 图像处理概述
Python提供了多个强大的库用于图像处理,其中Pillow
(Python Imaging Library的分支)是常用的库之一。
2. 图像基本操作
安装Pillow
库
使用pip install pillow
命令安装Pillow
库。
打开和显示图像
使用Image.open()
函数打开图像文件,并可使用show()
方法显示图像(此方法会调用系统默认的图像查看器)。
from PIL import Image
# 打开图像文件
image = Image.open('image.jpg')
# 显示图像
image.show()
获取图像信息
获取图像的基本信息,如尺寸、格式、模式等。
from PIL import Image
image = Image.open('image.jpg')
# 获取图像尺寸(宽度和高度)
width, height = image.size
print(f"图像尺寸: {width} x {height}")
# 获取图像格式(如JPEG、PNG等)
print(f"图像格式: {image.format}")
# 获取图像模式(如RGB、灰度等)
print(f"图像模式: {image.mode}")
保存图像
将处理后的图像保存为不同格式或使用不同文件名保存。
from PIL import Image
image = Image.open('image.jpg')
# 保存图像为PNG格式
image.save('image.png')
# 以新文件名保存图像
image.save('new_image.jpg')
3. 图像裁剪与缩放
** 图像裁剪**
指定裁剪区域的坐标(左上角和右下角坐标),使用crop()
方法裁剪图像。
from PIL import Image
image = Image.open('image.jpg')
# 定义裁剪区域(左上角坐标(x1, y1)和右下角坐标(x2, y2))
left = 100
top = 100
right = 400
bottom = 400
cropped_image = image.crop((left, top, right, bottom))
# 显示裁剪后的图像
cropped_image.show()
** 图像缩放**
使用resize()
方法调整图像大小,指定新的尺寸(宽度和高度)。
from PIL import Image
image = Image.open('image.jpg')
# 定义新的尺寸
new_width = 200
new_height = 200
resized_image = image.resize((new_width, new_height))
# 显示缩放后的图像
resized_image.show()
4. 图像滤镜与特效
Pillow
库还提供了一些内置的滤镜和特效,可通过ImageFilter
模块应用到图像上。
模糊滤镜
应用模糊滤镜到图像上,使图像变得模糊。
from PIL import Image, ImageFilter
image = Image.open('image.jpg')
# 应用模糊滤镜
blurred_image = image.filter(ImageFilter.BLUR)
# 显示模糊后的图像
blurred_image.show()
边缘增强滤镜
增强图像边缘,突出图像的轮廓。
from PIL import Image, ImageFilter
image = Image.open('image.jpg')
# 应用边缘增强滤镜
edge_enhanced_image = image.filter(ImageFilter.EDGE_ENHANCE)
# 显示边缘增强后的图像
edge_enhanced_image.show()
5. 图像合成与混合
可将多个图像进行合成或混合,创造出更复杂的图像效果。
图像合成
将一个图像粘贴到另一个图像上,指定粘贴位置。
from PIL import Image
# 打开背景图像和要粘贴的图像
background = Image.open('background.jpg')
foreground = Image.open('foreground.jpg')
# 调整前景图像大小以适应背景图像(可选)
foreground = foreground.resize((background.width, background.height))
# 将前景图像粘贴到背景图像上,指定位置为(0, 0)
background.paste(foreground, (0, 0))
# 显示合成后的图像
background.show()
图像混合
使用blend()
方法将两个图像按照一定比例混合。
from PIL import Image
image1 = Image.open('image1.jpg')
image2 = Image.open('image2.jpg')
# 混合图像,alpha参数控制混合比例(0.0 - 1.0)
mixed_image = Image.blend(image1, image2, alpha=0.5)
# 显示混合后的图像
mixed_image.show()
十五、文本处理
1. 大批量文件打开与处理
处理大批量文件时,高效的文件读取和管理策略能够避免内存瓶颈,确保程序稳定运行。
逐行读取文件
使用with
语句打开文件,逐行读取内容,这种方式能有效控制内存使用,适用于大型文件的处理。
def process_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
# 对每行数据进行处理,例如数据清洗、分析等
processed_line = line.strip().lower()
print(processed_line)
# 处理单个大文件
process_large_file('large_file.txt')
批量处理多个文件
通过遍历文件列表,依次打开并处理每个文件,实现对大批量文件的批量操作。
def process_files(file_paths):
for file_path in file_paths:
with open(file_path, 'r') as file:
for line in file:
print(line.strip())
# 文件路径列表
file_paths = ['file1.txt', 'file2.txt', 'file3.txt']
process_files(file_paths)
2. 字符编码处理
字符编码是文本处理中的关键环节,正确处理编码问题能确保文本数据的准确解读和转换。
常见字符编码
编码和解码操作
使用encode()
方法将字符串编码为字节串,decode()
方法将字节串解码为字符串,需指定正确的编码格式。
# 原始字符串
text = "你好,世界!"
# 编码为UTF-8字节串
encoded_text_utf8 = text.encode('utf-8')
print(encoded_text_utf8)
# 解码为字符串(使用正确的编码格式)
decoded_text_utf8 = encoded_text_utf8.decode('utf-8')
print(decoded_text_utf8)
# 编码为GBK字节串
encoded_text_gbk = text.encode('gbk')
print(encoded_text_gbk)
# 解码为字符串(使用GBK编码格式)
decoded_text_gbk = encoded_text_gbk.decode('gbk')
print(decoded_text_gbk)
编码转换
在不同编码之间进行转换,先将字节串解码为字符串,再编码为目标编码格式。
# 将UTF-8编码的字节串转换为GBK编码
text_utf8 = "你好,世界!".encode('utf-8')
text_gbk = text_utf8.decode('utf-8').encode('gbk')
print(text_gbk)
处理编码错误
在解码过程中遇到编码错误时,可通过errors
参数指定处理方式,如ignore
忽略错误字节或replace
用特定字符替换。
# 处理可能存在编码错误的字节串
encoded_text = b'\xe4\xbd\xa0\xe5\xa5\xbd\xff\xfe\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
decoded_text = encoded_text.decode('utf-8', errors='replace')
print(decoded_text)
3. 常用正则表达式应用
正则表达式是文本处理的强大工具,能够灵活地匹配、查找、替换和验证文本中的模式。
匹配数字
使用\d
匹配数字字符,+
表示匹配一个或多个数字,可用于提取文本中的数字信息。
import re
text = "订单号为12345,数量是5个"
matches = re.findall(r'\d+', text)
print(matches)
匹配电子邮件地址
运用复杂的正则表达式模式匹配电子邮件地址,尽管无法涵盖所有可能的合法格式,但能处理常见情况。
import re
text = "我的邮箱是user@example.com,请联系我。"
pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
match = re.search(pattern, text)
if match:
print(match.group())
匹配URL
使用正则表达式匹配URL,提取网页链接等信息。
import re
text = "这是一个链接:https://www.example.com/page"
pattern = r'https?://[^\s]+'
match = re.search(pattern, text)
if match:
print(match.group())
替换字符串
利用sub()
函数根据正则表达式模式替换文本中的部分内容。
import re
text = "今天天气真好,天气真好啊!"
new_text = re.sub(r'天气真好', '阳光明媚', text)
print(new_text)
分割字符串
使用split()
函数结合正则表达式模式按指定分隔符分割字符串。
import re
text = "苹果,香蕉;橙子:葡萄"
fruits = re.split(r'[,;:]', text)
print(fruits)
十六、日志记录与调试
1. 日志记录与调试的重要性
常用的日志库有logging、loguru和structlog
2. 使用logging
模块记录日志
基本配置与使用
logging
模块是Python标准库中用于记录日志的强大工具。其基本配置包括设置日志级别、指定日志格式以及确定输出目的地。
import logging
# 配置日志记录器,设置日志级别为DEBUG,日志格式包含时间、名称、级别和消息,同时输出到文件和控制台
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)s %(levelname)s %(message)s',
handlers=[
logging.FileHandler('app.log'),
logging.StreamHandler()
])
# 记录不同级别的日志
logging.debug('这是一条DEBUG级别的日志,用于调试程序细节。')
logging.info('程序正常运行,执行到此处。')
logging.warning('出现了一个可能影响程序运行的情况。')
logging.error('发生错误,需要关注并解决。')
logging.critical('严重错误,程序可能无法继续正常运行。')
日志级别与应用场景
3. 使用loguru
进行高级日志记录
安装与基本用法
loguru
是一个简洁且功能强大的日志记录库,可通过pip install loguru
进行安装。
from loguru import logger
# 记录信息日志
logger.info("这是一条使用loguru记录的信息日志。")
# 记录错误日志并捕获异常
try:
1 / 0
except ZeroDivisionError as e:
logger.error(f"发生错误: {e}")
特色功能
loguru
会自动记录函数名、行号、模块名等,方便快速定位问题所在的代码位置。# 配置日志输出到文件,每天生成一个新的日志文件,保留最近7天的日志文件,并进行压缩
logger.add("app_{time:YYYY-MM-DD}.log", rotation="1 day", retention="7 days", compression="zip")
4. 使用structlog
进行结构化日志记录
安装与基本配置
structlog
专注于创建结构化的日志记录,通过pip install structlog
安装。其基本配置涉及设置处理器链来定义日志的处理流程。
import structlog
# 配置structlog,添加日志级别、时间戳并以JSON格式输出日志
structlog.configure(
processors=[
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer()
]
)
logger = structlog.get_logger()
# 记录结构化日志
logger.info("这是一条结构化日志", key="value", another_key=123)
结构化日志的优势
5. 调试技巧
使用print
语句进行简单调试
在代码中插入print
语句是最直接的调试方法,可输出变量的值、程序执行的中间结果等,帮助开发者了解程序的执行流程和状态。
def add_numbers(a, b):
print(f"进入add_numbers函数,参数a={a},b={b}")
result = a + b
print(f"计算结果为{result}")
return result
add_numbers(3, 5)
使用pdb
进行交互式调试
pdb
(Python Debugger)是Python内置的调试器,提供了强大的交互式调试功能。
pdb.set_trace()
语句,程序运行到此处将暂停,进入调试模式。import pdb
def divide_numbers(a, b):
pdb.set_trace()
result = a / b
return result
divide_numbers(10, 2)
pdb
调试模式下,常用命令如下。
n
(next):执行下一行代码。s
(step):进入函数内部单步执行。c
(continue):继续执行程序直到下一个断点或程序结束。p <variable>
:打印变量的值。q
(quit):退出调试模式。十七、性能优化
1. 性能优化概述
在Python编程中,性能优化至关重要,它直接影响程序的运行速度、资源利用率和用户体验。随着数据量的增长和应用程序复杂性的增加,优化代码性能能够提高程序的响应能力、降低资源消耗,使程序在各种环境下更加高效地运行。
2. 性能分析工具
cProfile
模块
cProfile
是Python标准库中的性能分析工具,可用于分析代码中各个函数的执行时间和调用次数,帮助定位性能瓶颈。
import cProfile
def slow_function():
total = 0
for i in range(1000000):
total += i
return total
# 使用cProfile分析函数性能
cProfile.run('slow_function()')
line_profiler
库(需额外安装)
line_profiler
提供了逐行分析代码性能的功能,能更精确地找出耗时的代码行。
pip install line_profiler
@profile
装饰器,然后在命令行中使用kernprof -l -v your_script.py
运行脚本进行分析。@profile
def another_slow_function():
result = 0
for i in range(1000):
for j in range(1000):
result += i * j
return result
3. 代码优化策略
算法优化
选择更高效的算法和数据结构是性能优化的关键。例如,使用字典(dict
)查找元素的时间复杂度为O(1),而在列表(list
)中查找元素的时间复杂度为O(n)。
# 低效的列表查找
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
if my_list[i] == 3:
print("找到元素")
# 高效的字典查找(假设已将列表元素转换为字典)
my_dict = {i: i for i in my_list}
if 3 in my_dict:
print("找到元素")
减少不必要的计算
避免重复计算,将计算结果缓存起来,在后续需要时直接使用。
import math
def calculate_area(radius):
# 避免重复计算圆周率
return math.pi * radius ** 2
# 调用函数计算圆的面积
area = calculate_area(5)
优化循环
# 低效的循环
my_list = [1, 2, 3, 4, 5]
new_list = []
for i in my_list:
new_list.append(math.sqrt(i))
# 优化后的循环
new_list = [math.sqrt(i) for i in my_list]
enumerate()
函数替代手动获取索引和元素,提高代码可读性和性能。my_list = ['a', 'b', 'c', 'd']
# 低效的循环
for i in range(len(my_list)):
print(i, my_list[i])
# 优化后的循环
for i, item in enumerate(my_list):
print(i, item)
4. 使用numba
加速计算密集型任务(需额外安装)
numba
是一个即时(JIT)编译器,能够将Python函数编译为机器码,显著提高计算密集型任务的执行速度。
pip install numba
import numba
@numba.jit(nopython=True)
def add_numbers(a, b):
return a + b
# 调用加速后的函数
result = add_numbers(3, 5)
5. 内存管理优化
及时释放不再使用的内存
手动删除不再需要的对象,释放内存空间,避免内存泄漏。
# 创建一个大列表
my_list = [i for i in range(1000000)]
# 使用完列表后,删除它
del my_list
使用生成器代替列表
当处理大量数据时,如果不需要一次性将所有数据存储在内存中,可以使用生成器表达式,逐个生成数据项,减少内存占用。
# 使用列表推导式,一次性生成所有数据并存储在内存中
my_list = [i ** 2 for i in range(1000000)]
# 使用生成器表达式,逐个生成数据,不占用大量内存
my_generator = (i ** 2 for i in range(1000000))
for item in my_generator:
print(item)
十八、安全与加密
1. 密码哈希
密码哈希是将密码转换为不可逆的哈希值存储在数据库中的过程,以保护用户密码的安全性。
使用bcrypt
库进行密码哈希(需额外安装:pip install bcrypt
)
bcrypt
是一种广泛使用的密码哈希算法,具有良好的安全性。
import bcrypt
# 生成盐值
salt = bcrypt.gensalt()
# 对密码进行哈希
password = "mysecretpassword".encode('utf-8')
hashed_password = bcrypt.hashpw(password, salt)
print(hashed_password)
验证密码
在用户登录时,验证输入的密码与存储的哈希值是否匹配。
entered_password = "mysecretpassword".encode('utf-8')
if bcrypt.checkpw(entered_password, hashed_password):
print("密码正确")
else:
print("密码错误")
2. 数据加密与解密
对敏感数据进行加密,确保数据在传输和存储过程中的保密性。
使用cryptography
库进行对称加密(需额外安装:pip install cryptography
)
对称加密使用相同的密钥进行加密和解密。
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# 加密数据
data = "敏感信息".encode('utf-8')
encrypted_data = cipher_suite.encrypt(data)
print(encrypted_data)
# 解密数据
decrypted_data = cipher_suite.decrypt(encrypted_data)
print(decrypted_data.decode('utf-8'))
3. 安全随机数生成
在密码重置令牌、加密密钥生成等场景中,需要使用安全的随机数。
使用secrets
模块生成安全随机数
secrets
模块提供了生成密码学安全随机数的功能。
import secrets
# 生成一个随机整数(例如用于密码重置令牌)
token = secrets.randbelow(1000000)
print(token)
# 生成一个安全的随机十六进制字符串(例如用于加密密钥)
key = secrets.token_hex(16)
print(key)
4. 防止SQL注入
在与数据库交互时,防止SQL注入攻击至关重要。
使用参数化查询
在Python中,使用数据库驱动提供的参数化查询功能,避免将用户输入直接嵌入SQL语句中。例如,使用psycopg2
库连接PostgreSQL数据库时:
import psycopg2
# 连接数据库(假设已正确配置连接参数)
conn = psycopg2.connect(
dbname="your_database",
user="your_user",
password="your_password",
host="your_host"
)
# 创建游标
cur = conn.cursor()
# 使用参数化查询插入数据
username = "user1"
password = "password1"
cur.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))
# 提交事务
conn.commit()
# 关闭游标和连接
cur.close()
conn.close()
5. 防止跨站脚本攻击(XSS)
在Web应用程序中,防止XSS攻击以保护用户免受恶意脚本的侵害。
对用户输入进行过滤和转义
在将用户输入输出到HTML页面时,使用合适的模板引擎或手动进行HTML转义,确保用户输入不会被解释为脚本。例如,在使用Flask框架时:
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/')
def index():
user_input = request.args.get('input')
# 对用户输入进行转义
escaped_input = escape(user_input)
return render_template_string("<p>{{ escaped_input }}</p>", escaped_input=escaped_input)
if __name__ == '__main__':
app.run()
6. 安全通信(HTTPS)
确保Web应用程序与客户端之间的通信安全,防止数据在传输过程中被窃取或篡改。
使用ssl
模块创建HTTPS服务器(简单示例)
在创建网络服务器时,使用ssl
模块配置SSL/TLS证书,实现HTTPS通信。
import socket
import ssl
# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8000))
server_socket.listen(5)
# 使用SSL上下文包装套接字
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile='server.crt', keyfile='server.key')
ssl_socket = context.wrap_socket(server_socket, server_side=True)
while True:
# 接受客户端连接
client_socket, client_address = ssl_socket.accept()
# 处理客户端请求
request = client_socket.recv(1024).decode('utf-8')
print(request)
# 发送响应
response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello, World!"
client_socket.send(response.encode('utf-8'))
client_socket.close()
作者:什么都想学的阿超