Python 开发配置速查表
本速查表覆盖 Python 开发中的常用命令与代码片段,包括虚拟环境管理、pip 包管理、核心数据类型操作、字符串处理、文件读写、模块管理、输入输出以及调试技巧。
虚拟环境管理 (py-env)
``bash
# 创建虚拟环境
python -m venv venv
# 激活虚拟环境 (Linux/macOS) source venv/bin/activate
# 激活虚拟环境 (Windows PowerShell) venv\Scripts\Activate.ps1
# 退出虚拟环境 deactivate
# 导出已安装包列表 pip freeze > requirements.txt
# 从 requirements 文件安装
pip install -r requirements.txt
`
包管理 (py-env)
`bash
# 安装包
pip install requests
# 安装指定版本 pip install requests==2.31.0
# 升级包 pip install --upgrade requests
# 卸载包 pip uninstall requests -y
# 列出已安装包 pip list
# 查看包详细信息 pip show requests
# 安装到用户目录(无 sudo) pip install --user package
# 检查可升级的包
pip list --outdated
`
核心数据类型 (py-data)
`python
# 列表操作
lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4]
lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
lst.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
lst.remove(3) # [0, 1, 2, 4, 5, 6]
popped = lst.pop() # popped=6, lst=[0, 1, 2, 4, 5]
# 字典操作 d = {'a': 1, 'b': 2} d['c'] = 3 # {'a': 1, 'b': 2, 'c': 3} d.get('x', 0) # 0 (带默认值) d.setdefault('y', 4) # 键不存在时设置默认值 d.keys() # dict_keys(['a', 'b', 'c']) d.values() # dict_values([1, 2, 3]) d.items() # dict_items([('a',1), ('b',2), ('c',3)])
# 集合操作
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.discard(2) # {1, 3, 4}
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1 & s2 # {3} 交集
s1 | s2 # {1,2,3,4,5} 并集
s1 - s2 # {1, 2} 差集
`
字符串处理 (py-string)
`python
s = " hello world "
s.strip() # "hello world"
s.upper() # " HELLO WORLD "
s.lower() # " hello world "
s.split() # ['hello', 'world']
'-'.join(['a','b']) # "a-b"
s.replace("world", "python") # " hello python "
s.startswith("hel") # True
s.find("world") # 8
s.count("l") # 3
# f-string 格式化 name = "Alice" age = 30 f"Name: {name}, Age: {age}" # "Name: Alice, Age: 30" f"{3.14159:.2f}" # "3.14" f"{1000:>10}" # " 1000" (右对齐)
# 字符串切片
text = "python"
text[0:3] # "pyt"
text[::-1] # "nohtyp"
text[::2] # "pto"
`
文件 IO (py-file)
`python
# 读取文件
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read() # 全部读取
lines = f.readlines() # 逐行读取到列表
for line in f: # 逐行迭代(内存友好)
print(line.strip())
# 写入文件 with open('file.txt', 'w', encoding='utf-8') as f: f.write('hello\n') f.writelines(['line1\n', 'line2\n'])
# 追加写入 with open('file.txt', 'a', encoding='utf-8') as f: f.write('append this\n')
# JSON 文件操作 import json data = {'name': 'Alice', 'scores': [90, 85]} with open('data.json', 'w') as f: json.dump(data, f, indent=2) with open('data.json') as f: loaded = json.load(f)
# 路径操作
from pathlib import Path
p = Path('/home/user/file.txt')
p.name # "file.txt"
p.stem # "file"
p.suffix # ".txt"
p.parent # "/home/user"
p.exists() # True/False
p.mkdir(parents=True, exist_ok=True)
`
模块与参数解析 (py-module)
`python
# argparse 命令行参数
import argparse
parser = argparse.ArgumentParser(description='My script')
parser.add_argument('input', help='输入文件路径')
parser.add_argument('-o', '--output', default='out.txt', help='输出文件')
parser.add_argument('-v', '--verbose', action='store_true', help='详细输出')
parser.add_argument('--count', type=int, default=1, help='次数')
args = parser.parse_args()
# sys 模块 import sys sys.argv # 命令行参数列表 sys.exit(0) # 正常退出 sys.exit(1) # 错误退出 sys.path # Python 模块搜索路径
# os 模块
import os
os.getcwd() # 当前工作目录
os.listdir('.') # 列出目录内容
os.environ.get('HOME') # 环境变量
os.path.join('dir', 'file.txt') # 路径拼接
`
日期与随机 (py-module)
`python
# datetime
from datetime import datetime, timedelta
now = datetime.now()
now.strftime('%Y-%m-%d %H:%M:%S') # "2026-07-16 15:30:00"
datetime.strptime('2026-07-16', '%Y-%m-%d')
now + timedelta(days=7) # 一周后
now - timedelta(hours=3) # 三小时前
# random
import random
random.random() # [0.0, 1.0) 随机浮点数
random.randint(1, 10) # [1, 10] 随机整数
random.choice(['a','b','c']) # 随机选择一个
random.sample(range(100), 5) # 不重复随机抽样
random.shuffle(list) # 原地打乱列表
`
输入输出与格式化 (py-io)
`python
# 输入
user_input = input("Enter name: ")
# print 高级用法 print("hello", "world", sep=", ") # hello, world print("loading", end="...\n") # 自定义结尾 print(f"值: {value:>10.2f}") # 右对齐保留两位小数
# 异常处理 try: result = 10 / 0 except ZeroDivisionError as e: print(f"错误: {e}") except (ValueError, TypeError): print("类型或值错误") else: print("无异常") finally: print("始终执行")
# 主动抛出异常
raise ValueError("invalid value")
`
列表推导与调试 (py-debug)
``python # 列表推导式 squares = [x2 for x in range(10)] # [0, 1, 4, ..., 81] evens = [x for x in range(20) if x % 2 == 0] pairs = [(x, y) for x in [1,2] for y in [3,4]] # [(1,3),(1,4),(2,3),(2,4)]
# 字典推导式 square_dict = {x: x2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
# 集合推导式 unique_lens = {len(w) for w in ["hi", "hello", "hey"]} # {2, 3, 5}
# 生成器表达式 gen = (x2 for x in range(1000000)) # 惰性求值,内存友好 sum(x2 for x in range(10)) # 285
# 调试打印 from pprint import pprint data = {'users': [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]} pprint(data, indent=2, depth=2)
# 断点调试 (Python 3.7+) # breakpoint() # 启动 pdb 调试器
# 计时装饰器 import time def timer(func): def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start print(f"{func.__name__} 耗时: {elapsed:.4f}s") return result return wrapper
@timer def slow_function(): time.sleep(0.1) return "done"
环境管理(8)
| 命令 | 难度 | ||
|---|---|---|---|
python -m venv venv创建 Python 虚拟环境 | 基础 | python -m venv venv | |
source venv/bin/activate激活虚拟环境(Linux/macOS) | 基础 | source venv/bin/activate | |
deactivate退出虚拟环境 | 基础 | deactivate | |
pip freeze > requirements.txt导出已安装包列表到文件 | 基础 | pip freeze > requirements.txt | |
pip install -r requirements.txt从 requirements 文件安装依赖 | 基础 | pip install -r requirements.txt | |
pip install requests==2.31.0安装指定版本的包 | 基础 | pip install requests==2.31.0 | |
pip install --upgrade requests升级已安装的包 | 基础 | pip install --upgrade requests | |
pip list --outdated检查可升级的包 | 中级 | pip list --outdated |
数据类型(5)
| 命令 | 难度 | ||
|---|---|---|---|
lst = [1, 2, 3]; lst.append(4)列表追加元素 | 基础 | lst.append(4) | |
d.get('x', 0)字典安全取值,带默认值 | 基础 | d.get('x', 0) | |
d.setdefault('y', 4)字典键不存在时设置默认值 | 中级 | d.setdefault('y', 4) | |
s1 & s2集合交集运算 | 基础 | s1 = {1,2,3}; s2 = {3,4,5}; s1 & s2 | |
s1 - s2集合差集运算 | 基础 | s1 = {1,2,3}; s2 = {3,4,5}; s1 - s2 |
字符串(5)
| 命令 | 难度 | ||
|---|---|---|---|
s.strip()去除字符串首尾空白 | 基础 | s = " hello "; s.strip() | |
s.replace('world', 'python')字符串替换 | 基础 | s.replace('world', 'python') | |
'-'.join(['a', 'b'])使用分隔符合并字符串列表 | 基础 | '-'.join(['a', 'b']) | |
f'Name: {name}, Age: {age}'f-string 格式化输出 | 基础 | f'Name: {name}, Age: {age}' | |
text[::-1]字符串反转(步进切片) | 中级 | text[::-1] |
文件IO(5)
| 命令 | 难度 | ||
|---|---|---|---|
open('file.txt', 'r', encoding='utf-8')以只读模式打开文件(UTF-8) | 基础 | with open('file.txt', 'r', encoding='utf-8') as f: | |
json.dump(data, f, indent=2)将 Python 对象序列化为 JSON 文件 | 中级 | json.dump(data, f, indent=2) | |
json.load(f)从 JSON 文件读取为 Python 对象 | 中级 | with open('data.json') as f: data = json.load(f) | |
Path('/tmp/file.txt').suffix获取文件扩展名 | 基础 | Path('/tmp/file.txt').suffix | |
p.mkdir(parents=True, exist_ok=True)递归创建目录,存在不报错 | 中级 | p.mkdir(parents=True, exist_ok=True) |
模块管理(8)
| 命令 | 难度 | ||
|---|---|---|---|
argparse.ArgumentParser(description='My script')创建命令行参数解析器 | 中级 | parser = argparse.ArgumentParser(description='My script') | |
sys.argv获取命令行参数列表 | 基础 | sys.argv | |
os.environ.get('HOME')获取环境变量值 | 基础 | os.environ.get('HOME') | |
datetime.now().strftime('%Y-%m-%d %H:%M:%S')获取当前时间并格式化 | 基础 | datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
random.randint(1, 10)生成指定范围内的随机整数 | 基础 | random.randint(1, 10) | |
random.sample(range(100), 5)不重复随机抽样 | 中级 | random.sample(range(100), 5) | |
@contextmanager使用 contextmanager 装饰器自定义上下文管理器 | 高级 | from contextlib import contextmanager
@contextmanager
def managed_resource():
print("enter")
yield
print("exit")
with managed_resource():
print("inside") | |
lru_cache函数结果缓存(LRU 策略) | 高级 | from functools import lru_cache
@lru_cache(maxsize=128)
def expensive_func(n):
return n * n |
输入输出(5)
| 命令 | 难度 | ||
|---|---|---|---|
input('Enter name: ')从标准输入读取一行 | 基础 | input('Enter name: ') | |
print('hello', 'world', sep=', ')使用自定义分隔符打印 | 基础 | print('hello', 'world', sep=', ') | |
try ... except ... else ... finally完整的异常处理结构 | 中级 | try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
else:
print('No exception')
finally:
print('Always executed') | |
raise ValueError("invalid value")主动抛出异常 | 中级 | raise ValueError('invalid value') | |
async with aiohttp.ClientSession() as session:异步 HTTP 请求(asyncio + aiohttp) | 高级 | async with aiohttp.ClientSession() as session:
async with session.get("https://api.example.com") as resp:
data = await resp.json() |
调试(5)
| 命令 | 难度 | ||
|---|---|---|---|
[x**2 for x in range(10)]列表推导式 | 中级 | [x**2 for x in range(10)] | |
{x: x**2 for x in range(5)}字典推导式 | 中级 | {x: x**2 for x in range(5)} | |
(x**2 for x in range(1000000))生成器表达式(惰性求值) | 中级 | (x**2 for x in range(1000000)) | |
breakpoint()启动 pdb 交互式调试器(Python 3.7+) | 中级 | breakpoint() | |
from pprint import pprint; pprint(data, indent=2)美观打印嵌套数据结构 | 基础 | from pprint import pprint; pprint(data, indent=2) |