Python27教程——从零构建Python 2.7核心能力体系
本教程面向希望系统掌握Python 2.7开发能力的技术人员,尤其适合需维护 legacy 系统、参与遗留项目升级或专注特定生态(如旧版 Django、Twisted、Scientific Python)的开发者。内容覆盖环境搭建、语法核心、标准库深度应用、网络编程、自动化脚本开发、与Python 3差异对比及迁移策略,辅以真实代码示例与工程实践建议,助您构建扎实、可复用的Python 2.7技能栈。
为何选择聚焦 Python 2.7? 尽管官方已于2020年1月1日终止支持(EOL),全球仍有大量生产环境(尤其政府、金融、科研领域)运行于Python 2.7。理解其设计哲学、行为模式与局限性,是技术演进中的必要知识沉淀;同时,掌握其向Python 3的平滑迁移路径,是现代工程师应对技术债务的关键能力。
本教程特色
- • 以Python 2.7官方文档为基准,结合十年工程经验提炼最佳实践
- • 每个模块均含可运行代码片段,适配 Linux/macOS/Windows 多平台
- • 显式标注与Python 3语法/语义差异,避免常见陷阱
- • 提供自动化迁移检查清单与代码转换工具链实战指南
第一章:环境配置与基础语法核心
1.1 安装与环境管理
在主流系统中部署Python 2.7需注意版本选择。官方最后版本为2.7.18(2020年4月发布),修复了关键安全漏洞。建议使用版本管理工具隔离环境:
# Linux/macOS 使用 pyenv 安装指定版本
curl https://pyenv.run | bash
pyenv install 2.7.18
pyenv global 2.7.18
# Windows 推荐使用 python.org 安装包 + virtualenvwrapper
# 创建独立虚拟环境(关键!避免污染系统环境)
pip install virtualenv
virtualenv -p python2.7 myenv27
source myenv27/bin/activate # Linux/macOS
myenv27\Scripts\activate # Windows
验证安装:终端输入 `python --version` 应返回 `Python 2.7.18`。使用 `pip list` 确认环境纯净性。
1.2 关键语法差异:与 Python 3 的分水岭
Python 2.7与Python 3在字符串、除法、输入输出等核心行为存在根本性差异,直接影响代码可移植性:
| 特性 | Python 2.7 | Python 3.x | 迁移要点 |
|---|---|---|---|
| 字符串类型 | str(字节串), unicode | str(Unicode), bytes | 显式使用 u"中文" 标识 Unicode;文件读写需指定编码 |
| 除法运算 | / 整数除法(截断) | / 真除法(浮点) | 2.7 中用 from __future__ import division 预支 Python3 行为 |
| 输入函数 | raw_input()(安全), input()(执行表达式) | input()(仅读字符串) | 2.7 中始终用 raw_input();迁移时替换为 input() 并加类型转换 |
| print 语句 | print "Hello" | print("Hello") | 2.7 中可用 from __future__ import print_function 预支语法 |
| range/xrange | range 返回列表, xrange 返回迭代器 | range 返回迭代器(类似原 xrange) | 2.7 大循环用 xrange 节省内存;迁移后统一用 range |
重要提示:在Python 2.7中处理非 ASCII 字符(如中文)时,必须确保源文件头声明编码:
# -*- coding: utf-8 -*-,否则会触发 SyntaxError: Non-ASCII character。
1.3 数据类型深度解析
列表(List)与元组(Tuple)
列表可变,元组不可变。在Python 2.7中,元组常用于函数多返回值(通过解包实现):
def get_coords():
return (10, 20) # 返回元组
x, y = get_coords() # 解包赋值
print "坐标: (%d, %d)" % (x, y) # Python2 格式化
字典(Dict)操作
Python 2.7字典方法分两类:返回列表的(如 keys())与返回迭代器的(如 iterkeys())。后者更高效:
data = {"name": "Alice", "age": 30}
# 高效遍历(避免生成中间列表)
for key in data.iterkeys():
print "键: %s" % key
# 字典推导式(Python 2.7 支持)
squares = {x: x**2 for x in range(5)}
print squares # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
集合(Set)的实用技巧
集合支持高效去重与数学集合运算。在Python 2.7中,使用 set() 构造空集(而非 {},后者为空字典):
items = [1, 2, 2, 3, 1]
unique_items = set(items) # 去重: {1, 2, 3}
# 集合运算
a = set([1, 2, 3])
b = set([2, 3, 4])
print a & b # 交集: {2, 3}
print a | b # 并集: {1, 2, 3, 4}
print a - b # 差集: {1}
第二章:数据处理与文件操作
2.1 编码问题终极指南
Python 2.7的编码问题常导致 UnicodeDecodeError 或 UnicodeEncodeError。核心原则:所有输入解码为 Unicode,所有输出编码为 UTF-8:
# -*- coding: utf-8 -*-
import sys
# 读取文件(假设为 UTF-8 编码)
with open("data.txt", "r") as f:
content = f.read().decode("utf-8") # 显式解码
# 处理后写回
with open("output.txt", "w") as f:
f.write(content.encode("utf-8")) # 显式编码
在终端交互中,使用 sys.stdout.encoding 动态获取编码:
import sys
print u"当前终端编码: %s" % sys.stdout.encoding
text = raw_input(u"请输入中文: ")
print u"您输入了: %s" % text.encode(sys.stdout.encoding or "utf-8")
2.2 JSON 与 CSV 处理
JSON 操作
Python 2.7内置 json 模块(Python 2.6+),但默认不支持非 ASCII 字符的直接输出:
import json
data = {"name": u"张三", "hobby": [u"编程", u"阅读"]}
# ensure_ascii=False 确保中文不被转义
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print json_str
# 写入文件(需手动指定编码)
with open("output.json", "w") as f:
f.write(json_str.encode("utf-8"))
CSV 处理
标准库 csv 模块在Python 2.7中仅支持字节串,处理 Unicode 需额外包装:
import csv
import codecs
# 写入 CSV(UTF-8 编码)
with codecs.open("data.csv", "w", "utf-8") as f:
writer = csv.writer(f)
writer.writerow([u"姓名", u"年龄"])
writer.writerow([u"李四", 28])
2.3 正则表达式实战
re 模块在Python 2.7中对 Unicode 支持有限,建议统一使用字节串或显式处理编码:
import re
# 提取邮箱(字节串模式)
text = "联系: admin@python27.com, support@python27.com"
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
emails = re.findall(pattern, text)
for email in emails:
print "邮箱: %s" % email
# Unicode 文本匹配(需解码后处理)
text_unicode = u"测试文本:中文@email.com"
if re.search(ur"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text_unicode, re.U):
print "找到邮箱地址"
第三章:网络编程与 Web 开发
3.1 urllib2 与 requests 的对比
Python 2.7内置 urllib2,但 requests(第三方库)更简洁易用:
# 方式一:urllib2(标准库)
import urllib2
req = urllib2.Request("https://www.xservx.com")
try:
response = urllib2.urlopen(req, timeout=5)
html = response.read()
print "状态码:", response.getcode()
except urllib2.HTTPError as e:
print "HTTP 错误:", e.code
except urllib2.URLError as e:
print "URL 错误:", e.reason
# 方式二:requests(推荐)
# pip install requests
import requests
response = requests.get("https://www.xservx.com", timeout=5)
print "状态码:", response.status_code
print "响应头:", response.headers["Content-Type"]
3.2 构建简单 HTTP 服务器
Python 2.7可通过一行命令启动静态文件服务器:
# 启动 8000 端口服务器(当前目录)
python -m SimpleHTTPServer 8000
# Python 3 对应命令
python -m http.server 8000
自定义服务器(基于 BaseHTTPServer):
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(u"欢迎访问 Python27 教程
".encode("utf-8"))
server = HTTPServer(("", 8000), Handler)
print "服务器启动于 8000 端口..."
server.serve_forever()
3.3 Twisted 异步编程入门
Twisted 是Python 2.7生态中的核心异步框架。以下实现简单回显服务器:
from twisted.internet import reactor, protocol
class Echo(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data) # 直接回显
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
print "Twisted 回显服务器启动..."
reactor.run()
Twisted 的事件驱动模型适用于高并发场景,但学习曲线较陡。迁移至Python 3需使用 twisted.internet.asyncioreactor 或转向 asyncio。
第四章:自动化运维与脚本开发
4.1 subprocess 模块的正确用法
Python 2.7中 subprocess 是执行外部命令的标准方式。注意:避免使用 shell=True 防止注入攻击:
import subprocess
# 安全方式:列表传参(不经过 shell)
result = subprocess.run(["ls", "-l", "/tmp"], capture_output=True, text=True)
print "输出:", result.stdout
print "错误:", result.stderr
print "返回码:", result.returncode
# Python 2.7 兼容写法(无 subprocess.run)
proc = subprocess.Popen(["ls", "-l", "/tmp"], stdout=subprocess.PIPE)
stdout, stderr = proc.communicate()
print stdout
4.2 日志记录系统
构建可配置的日志系统,区分调试/错误级别:
import logging
# 配置日志
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("app.log", encoding="utf-8"),
logging.StreamHandler()
]
)
logging.debug("调试信息")
logging.info("操作成功")
logging.error("文件不存在: config.yaml")
日志文件 app.log 将记录完整时间戳与级别,便于后期排查。
4.3 定时任务:schedule 库实战
轻量级任务调度库 schedule(需安装):
# pip install schedule
import schedule
import time
def job():
print "执行定时任务..."
# 每小时执行一次
schedule.every().hour.do(job)
# 每天 14:30 执行
schedule.every().day.at("14:30").do(job)
while True:
schedule.run_pending()
time.sleep(1)
生产环境建议用 cron 或 systemd 管理,避免单进程崩溃导致任务中断。
第五章:从 Python 2.7 到 Python 3 的平滑迁移
5.1 迁移前评估清单
- • 依赖库是否提供 Python 3 支持?(检查 PyPI 或项目文档)
- • 代码库规模与测试覆盖率?(覆盖率 < 80% 建议先补充测试)
- • 是否有 C 扩展?需确认兼容性
- • 是否有硬编码路径(如
C:\Python27\...)?
5.2 自动化转换工具链
2to3 工具(Python 官方提供):
# 生成差异文件
2to3 -w myscript.py
# 批量转换整个目录
2to3 -w -r src/
# 仅查看差异(不修改文件)
2to3 src/
自定义转换规则:通过 fixers 扩展支持特定模式转换。
5.3 兼容性双写策略
过渡期可使用 six 库实现Python 2/3双兼容:
# pip install six
import six
@six.add_metaclass(MetaClass)
class MyClass:
pass
# 字典遍历兼容
for key in my_dict.iterkeys() if six.PY2 else my_dict.keys():
...
# 字符串处理
text = "中文"
if six.PY2:
text = text.decode("utf-8")
推荐路径:优先用 __future__ 导入兼容语法,逐步替换非兼容模块,最后移除 six。
第六章:高频问题解答
json.dumps(obj, ensure_ascii=False) + encode("utf-8") 写入文件。切勿直接打印 Unicode 字符串到终端(需处理终端编码)。# -*- coding: utf-8 -*-);② 未使用虚拟环境导致依赖冲突;③ 路径包含中文(改用英文路径)。python -m py_compile myscript.py 验证语法;配合 flake8(安装 pip install 'flake8<4')检查风格问题;用 python -3 -W error myscript.py 将警告转为错误。python -m pip install --upgrade "pip<21"(pip 21+ 不支持 Python 2)。注意:高版本 pip 可能无法安装新包。