-
Python实用技巧-SQLite 数据库
基本操作 import sqlite3conn = sqlite3.connect('example.db')cursor = conn.cursor()cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))conn.commit() 查询数据 cursor.exec...…
-
Python实用技巧-网络请求基础
基本请求 import requestsresponse = requests.get('https://httpbin.org/json')print(response.status_code)print(response.json()) POST 请求 data = {'key': 'value'}response = requests.post('https://httpbin.org/post', json=data) 会话管理 session = requests.Se...…
-
Python实用技巧-异步编程入门
基本异步函数 import asyncioasync def fetch_data(): await asyncio.sleep(1) return "数据"async def main(): result = await fetch_data() print(result)asyncio.run(main()) 并发执行 async def main(): tasks = [fetch_data() for _ in range(3)] results = ...…
-
Python实用技巧-多线程基础
基本线程 import threadingimport timedef worker(name): for i in range(3): print(f"{name}: {i}") time.sleep(0.1)t1 = threading.Thread(target=worker, args=("线程1",))t1.start()t1.join() 锁的使用 lock = threading.Lock()with lock: # 临界区代码 pa...…
-
Python实用技巧-日志进阶
高级配置 import loggingfrom logging.handlers import RotatingFileHandlerlogger = logging.getLogger('app')handler = RotatingFileHandler('app.log', maxBytes=1024*1024, backupCount=5)formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -...…
-
Python实用技巧-CSV 与 Excel 处理
CSV 读写 import csvwith open('data.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['姓名', '年龄']) writer.writerow(['张三', 25]) pandas 基础 import pandas as pddf = pd.read_csv('data.csv')print(df.head()) 转载...…
-
Python实用技巧-subprocess 入门
运行并捕获输出 import subprocess as spout = sp.check_output(["python", "-V"], text=True)print(out.strip()) 返回码与错误 proc = sp.run(["python", "-c", "exit(1)"])print(proc.returncode) 转载请注明:周志洋的博客 » Python实用技巧-subprocess 入门…
-
Python基础知识-模块与包
模块搜索路径与 sys.path import sysprint(sys.path) # 当前解释器的模块查找路径 包与相对导入 # pkg/__init__.py pkg/utils.py pkg/sub/mod.py# 在 pkg/sub/mod.py 中:from ..utils import helper # 相对导入 控制导出符号 __all__ # 在模块中声明:__all__ = ["foo", "Bar"] 脚本与库双用套路 def main():...…
-
Python实用技巧-路径处理小技巧
os.path 与 pathlib import osfrom pathlib import Pathp = Path('data') / 'notes.txt'print(os.path.join('data', 'notes.txt'))print(p.resolve()) 转载请注明:周志洋的博客 » Python实用技巧-路径处理小技巧…
-
Python实用技巧-JSON 与 YAML
JSON 读写 import jsondata = {"name": "Tom", "age": 20}text = json.dumps(data, ensure_ascii=False)obj = json.loads(text) YAML 读写 # pip install pyyamlimport yamltext = yaml.dump({"name": "Tom", "age": 20}, allow_unicode=True)obj = yaml.safe_load(te...…
-
Python实用技巧-日期与时间基础
获取当前时间与格式化 from datetime import datetime, timezonenow = datetime.now(timezone.utc)print(now.isoformat())print(now.strftime('%Y-%m-%d %H:%M:%S %z')) 解析字符串 from datetime import datetimedt = datetime.strptime('2018-10-02 12:30:00', '%Y-%m-%d %H:%M...…
-
Python实用技巧-类型注解基础
基本注解 from typing import List, Dict, Optional, Tupledef top_k(nums: List[int], k: int) -> List[int]: return sorted(nums, reverse=True)[:k]def find_user(users: Dict[int, str], uid: int) -> Optional[str]: return users.get(uid) mypy 简介 pi...…
-
Python实用技巧-单元测试基础
最小示例 import unittestdef add(a, b): return a + bclass TestAdd(unittest.TestCase): def test_add(self): self.assertEqual(add(1, 2), 3)if __name__ == '__main__': unittest.main() 转载请注明:周志洋的博客 » Python实用技巧-单元测试基础…
-
Python实用技巧-命令行参数 argparse
快速上手 import argparseparser = argparse.ArgumentParser()parser.add_argument("path")parser.add_argument("--verbose", action="store_true")args = parser.parse_args(["notes.txt", "--verbose"]) # 示例 子命令 sub = parser.add_subparsers(dest="sub")p_run = ...…
-
Python基础知识-错误与异常
捕获与抛出 try: int("abc")except ValueError as e: print("转换失败", e)def must_positive(n: int): if n <= 0: raise ValueError("n must be positive") 断言 def divide(a, b): assert b != 0, "b cannot be zero" return a / b 转载请注明:周志洋的博客 » Pyt...…
-
Python基础知识-函数进阶
参数种类回顾 def demo(pos, default=1, *args, scale=1.0, **kwargs): return pos, default, args, scale, kwargsprint(demo(10, 2, 3, 4, scale=0.5, mode="fast")) 可变对象做默认值的陷阱 def bad_append(item, cache=[]): cache.append(item) return cacheprint(bad_app...…
-
Python基础知识-布尔与逻辑运算
真值与空值 # 以下在条件判断中均为 False:0, 0.0, '', [], {}, set(), None 短路逻辑 a = Noneb = a or "default" # 左侧为假,返回右值c = a and 100 # 左侧为假,直接返回左值(None) any/all nums = [0, 1, 2]print(any(nums), all(nums)) # True, False 转载请注明:周志洋的博客 » Python基础知识-布尔与逻辑运算…
-
Python实用技巧-性能基础
内置优先与向量化倾向 # 慢:Python 级循环total = 0for x in range(1_000_000): total += x# 快:内置 sum 用 C 实现total = sum(range(1_000_000)) 避免不必要的列表化 # 慎用 list(...) 立刻展开even_sum = sum(x for x in range(10_000_000) if x % 2 == 0) 转载请注明:周志洋的博客 » Python实用技巧-性能基础…
-
Python实用技巧-调试与断点
最简调试:print def calc(a, b): print("a=", a, "b=", b) # 临时调试 return a + b pdb 基础 import pdbdef main(): x = 10 pdb.set_trace() # 断点 y = x * 2 return y 转载请注明:周志洋的博客 » Python实用技巧-调试与断点…
-
Python基础知识-继承与多态
继承与重写 class Animal: def speak(self) -> str: return "..."class Dog(Animal): def speak(self) -> str: return "woof"def make_speak(a: Animal): print(a.speak())make_speak(Dog()) super 的使用 class Base: def __init__(self, name...…