Python知识点及代码示例
所属分类 python
浏览量 23
一、基础语法与数据类型
1.1 变量与基本类型
# 变量赋值(动态类型)
x = 10 # int
y = 3.14 # float
name = "Alice" # str
is_active = True # bool
nothing = None # NoneType
print(type(x)) #
print(type(y)) #
print(type(name)) #
# 类型转换
str_num = "123"
int_num = int(str_num) # 123
float_num = float(str_num) # 123.0
bool_val = bool(0) # False
1.2 容器类型
# 列表 - 可变序列
fruits = ["apple", "banana", "orange"]
fruits.append("grape") # 添加元素
fruits[1] = "berry" # 修改元素
print(fruits[0:2]) # 切片: ['apple', 'berry']
# 元组 - 不可变序列
coordinates = (10, 20, 30)
x, y, z = coordinates # 元组解包
print(f"x={x}, y={y}, z={z}")
# 字典 - 键值对
person = {
"name": "Bob",
"age": 25,
"city": "Shanghai"
}
person["email"] = "bob@example.com" # 添加键值对
print(person.get("name", "Unknown")) # Bob
# 集合 - 无序不重复
set1 = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 | set2) # 并集: {1, 2, 3, 4, 5, 6}
print(set1 & set2) # 交集: {3, 4}
1.3 控制流示例
# if-elif-else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"成绩等级: {grade}")
# 三元表达式
age = 18
status = "成年" if age >= 18 else "未成年"
print(status)
# for循环
for i in range(5): # 0 1 2 3 4
print(i, end=" ")
print()
for fruit in ["apple", "banana", "orange"]:
print(f"I like {fruit}")
# while循环
count = 0
while count < 3:
print(f"计数: {count}")
count += 1
# break和continue
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num == 3:
continue # 跳过3
if num == 5:
break # 跳出循环
print(num) # 输出: 1 2 4
二、函数详解
2.1 函数定义与参数
# 基础函数
def greet(name):
"""向某人打招呼"""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# 默认参数
def power(base, exponent=2):
"""计算幂,默认平方"""
return base ** exponent
print(power(3)) # 9 (3²)
print(power(3, 3)) # 27 (3³)
# 可变参数
def sum_all(*numbers):
"""计算任意数量数字的和"""
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3, 4, 5)) # 15
print(sum_all(10, 20)) # 30
# 关键字参数
def create_profile(**info):
"""创建用户资料"""
profile = {
"name": info.get("name", "Unknown"),
"age": info.get("age", 0),
"email": info.get("email", "")
}
return profile
print(create_profile(name="Alice", age=25))
# {'name': 'Alice', 'age': 25, 'email': ''}
2.2 作用域与闭包
# 全局与局部作用域
global_var = "global"
def test_scope():
local_var = "local"
print(f"局部变量: {local_var}")
print(f"全局变量: {global_var}")
test_scope()
# print(local_var) # 错误!局部变量不能在外部访问
# 修改全局变量
counter = 0
def increment():
global counter
counter += 1
print(f"当前计数: {counter}")
increment() # 当前计数: 1
increment() # 当前计数: 2
# 闭包示例
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
add_five = outer_function(5)
print(add_five(3)) # 8
print(add_five(10)) # 15
2.3 lambda函数
# 简单lambda
add = lambda x, y: x + y
print(add(5, 3)) # 8
# 与map、filter、sort配合使用
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# map: 对每个元素应用函数
squared = list(map(lambda x: x**2, numbers))
print(f"平方: {squared}") # [1, 4, 9, 16, 25, 36, 49, 64, 81]
# filter: 过滤元素
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"偶数: {even_numbers}") # [2, 4, 6, 8]
# sort: 自定义排序
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 78}
]
# 按成绩降序排序
students.sort(key=lambda s: s["grade"], reverse=True)
print("按成绩排序:", students)
三、面向对象编程(OOP)
3.1 类与对象基础
class Dog:
"""狗类示例"""
# 类属性(所有实例共享)
species = "Canis familiaris"
def __init__(self, name, age):
"""初始化方法"""
self.name = name # 实例属性
self.age = age
def bark(self):
"""实例方法"""
return f"{self.name} says: Woof!"
def get_human_age(self):
"""计算相当于人类的年龄"""
return self.age * 7
@classmethod
def get_species(cls):
"""类方法"""
return f"Species: {cls.species}"
@staticmethod
def is_pet():
"""静态方法"""
return True
# 创建实例
my_dog = Dog("Buddy", 3)
print(my_dog.name) # Buddy
print(my_dog.bark()) # Buddy says: Woof!
print(my_dog.get_human_age()) # 21
print(Dog.get_species()) # Species: Canis familiaris
print(Dog.is_pet()) # True
3.2 继承与多态
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现此方法")
class Cat(Animal):
def speak(self):
return f"{self.name} says: Meow!"
class Dog(Animal):
def speak(self):
return f"{self.name} says: Woof!"
# 多态演示
animals = [Cat("Kitty"), Dog("Buddy")]
for animal in animals:
print(animal.speak())
# Kitty says: Meow!
# Buddy says: Woof!
# 多重继承
class Flyable:
def fly(self):
return "I can fly!"
class Swimmable:
def swim(self):
return "I can swim!"
class Duck(Flyable, Swimmable):
def __init__(self, name):
self.name = name
def quack(self):
return f"{self.name} says: Quack!"
duck = Duck("Donald")
print(duck.fly()) # I can fly!
print(duck.swim()) # I can swim!
print(duck.quack()) # Donald says: Quack!
3.3 属性装饰器与特殊方法
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # 私有属性(约定)
@property
def balance(self):
"""余额属性获取器"""
return self._balance
@balance.setter
def balance(self, amount):
"""余额属性设置器"""
if amount < 0:
raise ValueError("余额不能为负数")
self._balance = amount
def deposit(self, amount):
"""存款"""
if amount <= 0:
raise ValueError("存款金额必须为正数")
self._balance += amount
return self._balance
def withdraw(self, amount):
"""取款"""
if amount > self._balance:
raise ValueError("余额不足")
self._balance -= amount
return self._balance
def __str__(self):
"""字符串表示"""
return f"BankAccount(owner={self.owner}, balance={self._balance})"
def __repr__(self):
"""调试表示"""
return f"BankAccount('{self.owner}', {self._balance})"
# 使用示例
account = BankAccount("Alice", 1000)
print(account) # BankAccount(owner=Alice, balance=1000)
print(account.balance) # 1000
account.deposit(500)
print(account.balance) # 1500
account.withdraw(200)
print(account.balance) # 1300
# account.balance = -100 # 会报错:ValueError: 余额不能为负数
四、高级数据结构操作
4.1 推导式
# 列表推导式
# 生成0-9的平方列表
squares = [x**2 for x in range(10)]
print(f"平方列表: {squares}") # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(f"偶数的平方: {even_squares}") # [0, 4, 16, 36, 64]
# 字典推导式
fruit_prices = {"apple": 5, "banana": 3, "orange": 4}
# 价格增加20%
new_prices = {fruit: price * 1.2 for fruit, price in fruit_prices.items()}
print(f"新价格: {new_prices}")
# 集合推导式
words = ["hello", "world", "python", "hello", "code"]
unique_lengths = {len(word) for word in words}
print(f"单词长度集合: {unique_lengths}") # {5, 6, 4}
# [5, 5, 6, 5, 4]
lengths = [len(word) for word in words]
# 嵌套推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 转置矩阵
transposed = [[row[i] for row in matrix] for i in range(3)]
print(f"转置矩阵: {transposed}") # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
4.2 内置函数与高阶函数
# zip - 合并多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["Beijing", "Shanghai", "Guangzhou"]
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old, from {city}")
# enumerate - 带索引的迭代
for index, name in enumerate(names, start=1):
print(f"{index}. {name}")
# map - 应用函数到序列
def to_upper(name):
return name.upper()
uppercase_names = list(map(to_upper, names))
print(f"大写名字: {uppercase_names}")
# filter - 过滤序列
def is_adult(age):
return age >= 18
ages = [15, 25, 17, 30, 12, 22]
adults = list(filter(is_adult, ages))
print(f"成年人年龄: {adults}")
# reduce - 累积计算
from functools import reduce
def multiply(x, y):
return x * y
numbers = [1, 2, 3, 4, 5]
product = reduce(multiply, numbers)
print(f"乘积: {product}") # 120
五、异常处理
# 基础异常处理
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "错误:除数不能为零"
except TypeError:
return "错误:操作数类型不正确"
else:
return f"结果: {result}"
finally:
print("计算完成")
print(divide(10, 2)) # 结果: 5.0\n计算完成
print(divide(10, 0)) # 错误:除数不能为零\n计算完成
print(divide(10, "2")) # 错误:操作数类型不正确\n计算完成
# 自定义异常
class InsufficientFundsError(Exception):
"""自定义异常:余额不足"""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"余额不足:当前余额{balance},尝试提取{amount}")
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
return self.balance
# 使用自定义异常
account = BankAccount(100)
try:
account.withdraw(200)
except InsufficientFundsError as e:
print(f"取款失败: {e}")
print(f"详细信息: 余额={e.balance}, 提取金额={e.amount}")
六、文件操作
# 文本文件读写
# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("这是第二行\n")
lines = ["第三行\n", "第四行\n", "第五行\n"]
f.writelines(lines)
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
# 读取全部内容
content = f.read()
print("全部内容:")
print(content)
print("-" * 30)
# 逐行读取
with open("example.txt", "r", encoding="utf-8") as f:
print("逐行读取:")
for line_num, line in enumerate(f, 1):
print(f"行 {line_num}: {line.strip()}")
# CSV文件处理
import csv
# 写入CSV
data = [
["Name", "Age", "City"],
["Alice", "25", "Beijing"],
["Bob", "30", "Shanghai"],
["Charlie", "35", "Guangzhou"]
]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(data)
# 读取CSV
print("\nCSV文件内容:")
with open("people.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# JSON文件处理
import json
# Python对象转换为JSON
person = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "swimming", "coding"],
"is_student": True
}
with open("person.json", "w", encoding="utf-8") as f:
json.dump(person, f, indent=2, ensure_ascii=False)
# 读取JSON
with open("person.json", "r", encoding="utf-8") as f:
loaded_person = json.load(f)
print("\nJSON数据:")
print(json.dumps(loaded_person, indent=2, ensure_ascii=False))
七、装饰器详解
# 基础装饰器
def simple_decorator(func):
def wrapper():
print("函数执行前...")
result = func()
print("函数执行后...")
return result
return wrapper
@simple_decorator
def say_hello():
print("Hello, World!")
say_hello()
# 输出:
# 函数执行前...
# Hello, World!
# 函数执行后...
# 带参数的装饰器
def repeat(times):
"""重复执行函数指定次数"""
def decorator(func):
def wrapper(*args, **kwargs):
results = []
for i in range(times):
print(f"执行第 {i+1} 次")
result = func(*args, **kwargs)
results.append(result)
return results
return wrapper
return decorator
@repeat(times=3)
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# 输出:
# 执行第 1 次
# 执行第 2 次
# 执行第 3 次
# ['Hello, Alice!', 'Hello, Alice!', 'Hello, Alice!']
# 类装饰器
class Timer:
"""计时装饰器"""
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
import time
start_time = time.time()
result = self.func(*args, **kwargs)
end_time = time.time()
print(f"函数 {self.func.__name__} 执行时间: {end_time - start_time:.6f}秒")
return result
@Timer
def slow_function():
import time
time.sleep(1)
return "完成"
print(slow_function())
# 输出:
# 函数 slow_function 执行时间: 1.001234秒
# 完成
# 装饰器链(多个装饰器)
def bold(func):
def wrapper():
return f"{func()}"
return wrapper
def italic(func):
def wrapper():
return f"{func()}"
return wrapper
@bold
@italic
def get_text():
return "装饰器链示例"
print(get_text()) # 装饰器链示例
八、生成器与迭代器
# 生成器函数
def fibonacci_generator(limit):
"""生成斐波那契数列"""
a, b = 0, 1
count = 0
while count < limit:
yield a
a, b = b, a + b
count += 1
# 使用生成器
fib_gen = fibonacci_generator(10)
print("斐波那契数列前10项:")
for num in fib_gen:
print(num, end=" ")
# 输出: 0 1 1 2 3 5 8 13 21 34
print("\n" + "="*30)
# 生成器表达式
# 类似列表推导式,但返回生成器
numbers = [1, 2, 3, 4, 5]
squared_gen = (x**2 for x in numbers)
print("生成器表达式:")
for square in squared_gen:
print(square, end=" ") # 1 4 9 16 25
print("\n" + "="*30)
# 自定义迭代器类
class CountDown:
"""倒计时迭代器"""
def __init__(self, start):
self.current = start
self.start = start
def __iter__(self):
return self
def __next__(self):
if self.current < 0:
raise StopIteration
value = self.current
self.current -= 1
return value
# 使用自定义迭代器
print("倒计时:")
for num in CountDown(5):
print(num, end=" ") # 5 4 3 2 1 0
print("\n" + "="*30)
# 生成器发送数据
def accumulator():
"""累积器生成器"""
total = 0
while True:
value = yield total
if value is None:
break
total += value
acc = accumulator()
next(acc) # 启动生成器
print("累积器示例:")
print(acc.send(10)) # 10
print(acc.send(20)) # 30
print(acc.send(5)) # 35
acc.close()
九、并发编程
import threading
import time
import asyncio
import concurrent.futures
# 多线程示例
def print_numbers(name, count):
for i in range(count):
print(f"{name}: {i}")
time.sleep(0.1)
def multi_thread_demo():
"""多线程演示"""
print("多线程示例:")
# 创建线程
thread1 = threading.Thread(target=print_numbers, args=("线程A", 5))
thread2 = threading.Thread(target=print_numbers, args=("线程B", 5))
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
print("所有线程执行完成")
# multi_thread_demo()
# 线程锁示例
counter = 0
lock = threading.Lock()
def increment_counter():
global counter
for _ in range(100000):
with lock: # 使用锁确保线程安全
counter += 1
def lock_demo():
"""线程锁演示"""
global counter
counter = 0
threads = []
for i in range(10):
thread = threading.Thread(target=increment_counter)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(f"最终计数器值: {counter} (应该是 1000000)")
# lock_demo()
# 异步编程示例
async def async_task(name, seconds):
"""异步任务"""
print(f"任务 {name} 开始")
await asyncio.sleep(seconds)
print(f"任务 {name} 完成,耗时 {seconds}秒")
return f"任务 {name} 结果"
async def async_demo():
"""异步演示"""
print("异步编程示例:")
# 创建多个异步任务
tasks = [
async_task("A", 2),
async_task("B", 1),
async_task("C", 3)
]
# 并发执行所有任务
results = await asyncio.gather(*tasks)
print(f"所有任务完成,结果: {results}")
# 运行异步示例
# asyncio.run(async_demo())
# 线程池示例
def cpu_intensive_task(n):
"""CPU密集型任务"""
return sum(i * i for i in range(n))
def thread_pool_demo():
"""线程池演示"""
print("线程池示例:")
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
# 提交多个任务
futures = [
executor.submit(cpu_intensive_task, i * 1000000)
for i in range(1, 6)
]
# 获取结果
for future in concurrent.futures.as_completed(futures):
result = future.result()
print(f"任务完成,结果: {result}")
# thread_pool_demo()
十、常用标准库
# os模块 - 操作系统接口
import os
print(f"当前工作目录: {os.getcwd()}")
print(f"环境变量PATH: {os.environ.get('PATH')}")
# 创建目录
if not os.path.exists("test_dir"):
os.makedirs("test_dir")
print("目录创建成功")
# 列出文件
print("当前目录文件:")
for file in os.listdir("."):
print(f" {file}")
# sys模块 - 系统参数
import sys
print(f"Python版本: {sys.version}")
print(f"命令行参数: {sys.argv}")
print(f"默认编码: {sys.getdefaultencoding()}")
# datetime模块 - 日期时间
from datetime import datetime, date, timedelta
# 当前时间
now = datetime.now()
print(f"当前时间: {now}")
print(f"格式化时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# 日期运算
today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
print(f"今天: {today}")
print(f"昨天: {yesterday}")
print(f"明天: {tomorrow}")
# collections模块 - 扩展容器
from collections import namedtuple, deque, Counter, defaultdict
# 命名元组
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(f"命名元组: {p}, x={p.x}, y={p.y}")
# 双端队列
dq = deque([1, 2, 3])
dq.append(4) # 右端添加
dq.appendleft(0) # 左端添加
print(f"双端队列: {dq}")
# 计数器
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_count = Counter(words)
print(f"单词计数: {word_count}")
print(f"最常见的2个: {word_count.most_common(2)}")
# 默认字典
def_dict = defaultdict(list)
def_dict['fruits'].append('apple')
def_dict['fruits'].append('banana')
def_dict['colors'].append('red')
print(f"默认字典: {dict(def_dict)}")
十一、上下文管理器
# 类实现的上下文管理器
class DatabaseConnection:
"""数据库连接上下文管理器"""
def __init__(self, db_name):
self.db_name = db_name
self.connection = None
def __enter__(self):
print(f"连接到数据库: {self.db_name}")
# 模拟连接数据库
self.connection = f"Connection to {self.db_name}"
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"关闭数据库连接: {self.db_name}")
self.connection = None
# 如果有异常,可以在这里处理
if exc_type:
print(f"发生异常: {exc_type.__name__}: {exc_val}")
return True # 返回True表示异常已处理
# 使用上下文管理器
with DatabaseConnection("mydb") as conn:
print(f"使用连接: {conn}")
print("执行数据库操作...")
# raise ValueError("模拟数据库错误")
print("连接已关闭")
# contextmanager装饰器实现
from contextlib import contextmanager
@contextmanager
def file_handler(filename, mode):
"""文件处理上下文管理器"""
file = None
try:
file = open(filename, mode, encoding='utf-8')
print(f"文件 {filename} 已打开")
yield file
except Exception as e:
print(f"处理文件时出错: {e}")
finally:
if file:
file.close()
print(f"文件 {filename} 已关闭")
# 使用
with file_handler("test.txt", "w") as f:
f.write("Hello, Context Manager!")
# 多重上下文管理器
with DatabaseConnection("db1") as conn1, \
DatabaseConnection("db2") as conn2:
print(f"同时使用两个连接: {conn1}, {conn2}")
print("执行跨数据库操作...")
十二、元编程与反射
# 动态创建类
def create_class(class_name, base_classes, attributes):
"""动态创建类"""
return type(class_name, base_classes, attributes)
# 使用type动态创建类
DynamicClass = create_class(
"DynamicClass",
(object,),
{
"x": 10,
"say_hello": lambda self: f"Hello from {self.__class__.__name__}"
}
)
obj = DynamicClass()
print(obj.x) # 10
print(obj.say_hello()) # Hello from DynamicClass
# 反射 - 检查对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
person = Person("Alice", 25)
# 检查属性和方法
print(f"对象类型: {type(person)}")
print(f"是否有name属性: {hasattr(person, 'name')}")
print(f"name属性值: {getattr(person, 'name', 'Unknown')}")
print(f"所有属性: {dir(person)}")
# 动态调用方法
method_name = "greet"
if hasattr(person, method_name):
method = getattr(person, method_name)
print(f"动态调用: {method()}")
# 动态设置属性
setattr(person, "city", "Beijing")
print(f"新属性city: {person.city}")
# 元类示例
class SingletonMeta(type):
"""单例模式元类"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class SingletonClass(metaclass=SingletonMeta):
def __init__(self, value):
self.value = value
def show_value(self):
return self.value
# 测试单例
obj1 = SingletonClass("First")
obj2 = SingletonClass("Second")
print(f"obj1 is obj2: {obj1 is obj2}") # True
print(f"obj1.value: {obj1.value}") # First
print(f"obj2.value: {obj2.value}") # First
十三、单元测试
import unittest
# 待测试的函数
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
# 测试类
class TestMathFunctions(unittest.TestCase):
"""测试数学函数"""
def setUp(self):
"""每个测试前执行"""
self.test_data = [(1, 2, 3), (0, 0, 0), (-1, 1, 0)]
def test_add_positive_numbers(self):
"""测试正数相加"""
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
"""测试负数相加"""
self.assertEqual(add(-2, -3), -5)
def test_add_multiple_cases(self):
"""测试多个用例"""
for a, b, expected in self.test_data:
with self.subTest(a=a, b=b):
self.assertEqual(add(a, b), expected)
def test_divide_normal(self):
"""测试正常除法"""
self.assertAlmostEqual(divide(10, 3), 3.333333, places=6)
def test_divide_by_zero(self):
"""测试除零异常"""
with self.assertRaises(ValueError) as context:
divide(10, 0)
self.assertEqual(str(context.exception), "除数不能为零")
def test_add_type_error(self):
"""测试类型错误"""
with self.assertRaises(TypeError):
add("2", 3)
def tearDown(self):
"""每个测试后执行"""
self.test_data = None
# 运行测试
if __name__ == '__main__':
# 方法1: 使用unittest.main()
unittest.main(verbosity=2)
# 方法2: 使用测试套件
# suite = unittest.TestLoader().loadTestsFromTestCase(TestMathFunctions)
# runner = unittest.TextTestRunner(verbosity=2)
# runner.run(suite)
十四、虚拟环境与包管理
"""
这部分主要涉及命令行操作,这里展示如何用Python脚本管理环境
"""
import subprocess
import sys
import os
def check_python_version():
"""检查Python版本"""
print(f"Python版本: {sys.version}")
print(f"Python路径: {sys.executable}")
def list_installed_packages():
"""列出已安装的包"""
try:
import pkg_resources
packages = [dist.key for dist in pkg_resources.working_set]
print(f"已安装 {len(packages)} 个包:")
for package in sorted(packages)[:10]: # 显示前10个
print(f" {package}")
if len(packages) > 10:
print(f" ... 还有 {len(packages) - 10} 个包")
except ImportError:
print("无法获取包列表")
def create_requirements_file():
"""创建requirements.txt文件"""
try:
import pkg_resources
packages = pkg_resources.working_set
with open("requirements.txt", "w", encoding="utf-8") as f:
for dist in packages:
f.write(f"{dist.key}=={dist.version}\n")
print("已生成 requirements.txt 文件")
# 显示文件内容
with open("requirements.txt", "r", encoding="utf-8") as f:
content = f.read()
print("文件内容预览:")
print(content[:500] + "..." if len(content) > 500 else content)
except ImportError:
print("无法生成requirements.txt")
def run_pip_command(command):
"""运行pip命令"""
try:
result = subprocess.run(
[sys.executable, "-m", "pip"] + command.split(),
capture_output=True,
text=True,
check=True
)
print("命令执行成功:")
print(result.stdout)
except subprocess.CalledProcessError as e:
print("命令执行失败:")
print(e.stderr)
if __name__ == "__main__":
print("=" * 50)
print("Python环境信息检查")
print("=" * 50)
check_python_version()
print("-" * 30)
list_installed_packages()
print("-" * 30)
create_requirements_file()
print("-" * 30)
print("常用pip命令示例:")
print("1. 安装包: python -m pip install package_name")
print("2. 升级包: python -m pip install --upgrade package_name")
print("3. 卸载包: python -m pip uninstall package_name")
print("4. 从requirements安装: python -m pip install -r requirements.txt")
# 示例:检查requests包
try:
import requests
print(f"\nrequests包已安装,版本: {requests.__version__}")
except ImportError:
print("\nrequests包未安装")
print("可以运行: python -m pip install requests")
上一篇
python 发送http请求获取行情数据实例
Python 类型提示(Type Hints)
python 属性访问器