阅读视图

发现新文章,点击刷新页面。

Python 速记手册

Python 速记手册(含可运行 Demo 01~11)

6b41cd17ac5d47b5959ab5f226a4ec29(1).jpeg

适合人群:

  • 前端/全栈转 Python,需要“先跑起来”的最小路径
  • 只想快速掌握:语法、JSON、文件、请求、写接口、脚本自动化、Excel

git地址在这里:https://gitee.com/mslimyjj/old-ling-python/tree/master/python-cheatsheet-demos



0. 快速开始(先跑起来)

建议在 python-cheatsheet-demos/ 目录中运行命令(相对路径/生成文件最直观)。

python 01_basics.py

Windows:没有 python 命令怎么办

如果你的环境里 python 命令不可用,可以使用 Python 官方“嵌入式版本”(无需安装、不污染系统环境)。

python-cheatsheet-demos/ 目录执行:

$ver='3.11.8'
$zip="python-$ver-embed-amd64.zip"
$url="https://www.python.org/ftp/python/$ver/$zip"
$dest="..\.python-embed"
New-Item -ItemType Directory -Force -Path $dest | Out-Null
Invoke-WebRequest -Uri $url -OutFile "$dest\$zip"
Expand-Archive -Force -Path "$dest\$zip" -DestinationPath $dest
& "$dest\python.exe" 01_basics.py

后续统一用它运行 demo:

& "..\.python-embed\python.exe" 05_requests_demo.py

一键安装依赖

如果你用系统 Python:

pip install -r requirements.txt

如果你用嵌入式 Python:

& "..\.python-embed\python.exe" -m pip install -r requirements.txt

1. Demo 01:基础语法(变量 / 条件 / 循环 / 函数)

文件:01_basics.py

name = "张三"      # str
age = 20           # int
is_ok = True       # bool
arr = [1, 2, 3]    # list  = JS Array
obj = {"a": 1}     # dict  = JS Object

print(name, age, is_ok, arr, obj)

if age > 18:
    print("成年")
elif age == 18:
    print("刚成年")
else:
    print("未成年")

for item in [1, 2, 3]:
    print("item:", item)

for i in range(10):
    print("i:", i)


def add(a, b):
    return a + b


res = add(1, 2)
print("add:", res)

运行:

& "..\.python-embed\python.exe" 01_basics.py

2. Demo 02:list / dict(前端最熟)

文件:02_list_dict.py

arr = [1, 2, 3]
arr.append(4)
last = arr.pop()
print(arr, "popped:", last)
print("len:", len(arr))
print("first:", arr[0])

user = {
    "name": "tom",
    "age": 20,
}

print("name1:", user["name"])
print("name2:", user.get("name"))
print("missing:", user.get("addr"))

user["addr"] = "北京"
print(user)

你可以把 list 当成 JS 的数组,把 dict 当成 JS 的对象。

运行:

& "..\.python-embed\python.exe" 02_list_dict.py

3. Demo 03:JSON(前后端交互必备)

文件:03_json_demo.py

import json

data = json.loads('{"name":"tom","age":20}')
print(data, type(data))

str_data = json.dumps(data, ensure_ascii=False)
print(str_data, type(str_data))
  • json.loads:字符串 -> 对象
  • json.dumps:对象 -> 字符串

运行:

& "..\.python-embed\python.exe" 03_json_demo.py

4. Demo 04:文件读写(批量处理神器)

文件:04_file_io.py

import json

with open("test.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")

with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()
print("content:", content)

payload = {"name": "tom", "age": 20}
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(payload, f, ensure_ascii=False, indent=2)

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)
print("json:", data)

运行:

& "..\.python-embed\python.exe" 04_file_io.py

输出会读写当前目录的:

  • test.txt
  • data.json

5. Demo 05:requests(抓接口 / mock)

文件:05_requests_demo.py

import requests

res = requests.get("https://httpbin.org/get", params={"q": "test"}, timeout=10)
print("get status:", res.status_code)
print(res.json()["args"])

res = requests.post("https://httpbin.org/post", json={"username": "admin"}, timeout=10)
print("post status:", res.status_code)
print(res.json()["json"])

这个 demo 用 https://httpbin.org 作为测试服务,演示 GET/POST JSON。

运行:

& "..\.python-embed\python.exe" 05_requests_demo.py

6. Demo 06:FastAPI(快速写接口)

文件:06_fastapi_main.py

from fastapi import FastAPI

app = FastAPI()


@app.get("/api/user")
def get_user():
    return {"name": "tom", "age": 20}

安装依赖(如果还没装):

pip install fastapi uvicorn

运行:

uvicorn 06_fastapi_main:app --reload

访问:

  • http://localhost:8000/api/user
  • http://localhost:8000/docs

7. Demo 07:小脚本(遍历目录 / 批量重命名)

文件:07_scripts_os.py

import os

for file in os.listdir("./"):
    print(file)

imgs_dir = "./imgs"
if os.path.isdir(imgs_dir):
    for i, file in enumerate(os.listdir(imgs_dir)):
        src = os.path.join(imgs_dir, file)
        dst = os.path.join(imgs_dir, f"img{i}.png")
        if os.path.isfile(src):
            os.rename(src, dst)
            print("renamed:", src, "->", dst)

运行:

& "..\.python-embed\python.exe" 07_scripts_os.py

注意:批量重命名会操作 ./imgs 目录下文件名,运行前确认目录存在并且文件可改名。


8. Demo 08:对接 AI(HTTP 调用套路)

文件:08_ai_call.py

import requests


def call_ai(prompt: str):
    res = requests.post(
        "http://localhost:8000/ai",
        json={"prompt": prompt},
        timeout=30,
    )
    res.raise_for_status()
    return res.json()


code = call_ai("生成一个Vue3按钮组件")
print(code)

这个 demo 会调用:POST http://localhost:8000/ai

如果你本地没有启动这个服务,会出现连接被拒绝(这属于正常现象)。

运行:

& "..\.python-embed\python.exe" 08_ai_call.py

9. Demo 09:抓取网页请求并保存到 send.txt

文件:09_capture_requests.py

import argparse
import re
import sys
from urllib.parse import urlparse


def _normalize_url(u: str) -> str:
    try:
        p = urlparse(u)
        if not p.scheme or not p.netloc:
            return u
        return p._replace(fragment="").geturl()
    except Exception:
        return u


def _looks_like_api(u: str) -> bool:
    low = u.lower()
    if any(x in low for x in ("/api", "/graphql", "/v1/", "/v2/", "/rpc")):
        return True
    if any(low.endswith(x) for x in (".json", ".xml")):
        return True
    return False


def _capture_with_playwright(url: str, timeout_ms: int, only_api: bool) -> list[str]:
    try:
        from playwright.sync_api import sync_playwright  # type: ignore
    except Exception as e:
        raise RuntimeError("missing_playwright") from e

    seen: set[str] = set()
    out: list[str] = []

    def on_request(req):
        u = _normalize_url(req.url)
        if only_api and (not _looks_like_api(u)):
            return
        if u not in seen:
            seen.add(u)
            out.append(u)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = context.new_page()
        page.on("request", on_request)
        page.goto(url, wait_until="networkidle", timeout=timeout_ms)
        try:
            page.wait_for_timeout(1500)
        except Exception:
            pass
        context.close()
        browser.close()

    return out


def _extract_from_html(url: str, timeout_sec: int, only_api: bool) -> list[str]:
    import requests

    html = requests.get(url, timeout=timeout_sec).text
    candidates = set(re.findall(r"https?://[^\s\"'>]+", html))
    cleaned = [_normalize_url(u) for u in candidates]
    if only_api:
        cleaned = [u for u in cleaned if _looks_like_api(u)]
    cleaned.sort()
    return cleaned


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("url")
    parser.add_argument("--out", default="send.txt")
    parser.add_argument("--timeout", type=int, default=30)
    parser.add_argument("--only-api", action="store_true")
    parser.add_argument("--mode", choices=["auto", "playwright", "html"], default="auto")
    args = parser.parse_args(argv)

    url = args.url
    out_path = args.out
    timeout_sec = args.timeout
    only_api = bool(args.only_api)
    mode = args.mode

    urls: list[str] = []
    if mode in ("auto", "playwright"):
        try:
            urls = _capture_with_playwright(url, timeout_sec * 1000, only_api)
        except RuntimeError as e:
            if str(e) != "missing_playwright" or mode == "playwright":
                raise
            urls = []

    if (not urls) and mode in ("auto", "html"):
        urls = _extract_from_html(url, timeout_sec, only_api)

    with open(out_path, "w", encoding="utf-8") as f:
        for u in urls:
            f.write(u + "\n")

    print(f"saved {len(urls)} urls -> {out_path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))

目标:给一个网页 URL,把它“页面里出现的 URL / 或页面运行时发出的请求”抓出来,写到 send.txt

9.1 推荐模式:Playwright(最接近浏览器真实请求)

安装:

pip install playwright
python -m playwright install chromium

运行(只保留更像接口的 URL):

python 09_capture_requests.py https://example.com --only-api --out send.txt

9.2 兜底模式:HTML 提取(抓不到 XHR/fetch)

如果你不安装 Playwright,脚本会自动降级为“从 HTML 源码中提取 URL”。

你也可以强制:

python 09_capture_requests.py https://example.com --mode html --out send.txt

参数速记:

  • --mode playwright:强制用浏览器抓
  • --mode html:只解析 HTML
  • --only-api:只保留更像接口的 URL(包含 /api/graphql/v1//v2/.json 等)

10. Demo 10:3 秒后“键盘输入” Helloween(不是 print)

文件:10_sleep_print.py

import time

from pynput.keyboard import Controller


time.sleep(3)
Controller().type("Helloween")

这个 demo 用 pynput 控制键盘:

  • 等待 3 秒
  • 向“当前获得焦点的窗口”键入 Helloween

使用方法:先把光标点到你想输入的位置(例如记事本/浏览器输入框),再运行脚本。

运行:

& "..\.python-embed\python.exe" 10_sleep_print.py

11. Demo 11:生成 user.xlsx(随机 10 个姓名)

文件:11_generate_user_excel.py

import os
import random

from openpyxl import Workbook


def random_cn_name() -> str:
    surnames = list("赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦章云苏潘葛范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍虞万支柯昝管卢莫经房裘缪干解应宗丁宣贲邓郁单杭洪包诸左石崔吉钮龚程嵇邢滑裴陆荣翁荀羊於惠甄曲家封芮羿储靳汲邴糜松井段富巫乌焦巴弓牧隗山谷车侯宓蓬全郗班仰秋仲伊宫宁仇栾暴甘钭厉戎祖武符刘景詹束龙叶幸司韶郜黎蓟薄印宿白怀蒲邰从鄂索咸籍赖卓蔺屠蒙池乔阴郁胥能苍双闻莘党翟谭贡劳逄姬申扶堵冉宰郦雍却璩桑桂濮牛寿通边扈燕冀郏浦尚农温别庄晏柴瞿阎充慕连茹习宦艾鱼容向古易慎戈廖庾终暨居衡步都耿满弘匡国文寇广禄阙东欧殳沃利蔚越夔隆师巩厍聂晁勾敖融冷訾辛阚那简饶空曾毋沙乜养鞠须丰巢关蒯相查后荆红游竺权逯盖益桓公万俟司马上官欧阳夏侯诸葛闻人东方赫连皇甫尉迟公羊澹台公冶宗政濮阳淳于单于太叔申屠公孙仲孙轩辕令狐钟离宇文长孙慕容司徒司空")
    given_chars = list("一乙二十丁厂七卜人入八九几儿了力乃刀又三于干亏士工土才下寸大丈与万上小口山巾千乞川亿个夕久么勺丸凡及广亡门义之尸弓己已子卫也女飞刃习叉马乡丰王井开夫天元无云专扎艺木五支厅不太犬区历尤友匹车巨牙屯比互切瓦止少日中贝内水冈见手午牛毛气升长仁什片仆化仇币仍仅斤爪反介父从今凶分乏公仓月氏勿欠风丹匀乌凤勾文六方火为斗忆计订户认心尺引丑巴孔队办以允予劝双书幻玉刊末未示击打巧正扑扒功扔去甘世古节本术可丙左厉右石布龙平灭轧东卡北占业旧帅归且旦目叶甲申叮电号田由史只央兄叼叫另叨叹四生失禾丘付仗代仙们仪白仔他斥瓜乎丛令用甩印乐句匆册犯外处冬鸟务包饥主市立闪兰半汁汇头汉宁它讨写让礼训必议讯记永司尼民出辽奶奴召加皮边发孕圣对台矛纠母幼丝式刑动扛寺吉扣考托老执巩圾扩扫地扬场耳共芒亚芝朽朴机权过臣再协西压厌在有百存而页匠夸夺灰达列死成夹轨邪划迈毕至此贞师尘尖劣光当早吐吓虫曲团同吊吃因吸吗屿帆岁回岂则刚网肉年朱先丢舌竹迁乔伟传乒乓休伍伏优伐延件任伤价伦份华仰仿伙伪自伊血向似后行舟全会杀合兆企众爷伞创肌朵杂危旬旨负各名多争色壮冲妆冰庄庆亦刘齐交次衣产决充妄闭问闯羊并关米灯州汗污江池汤忙兴宇守宅字安讲军许论农讽设访那迅尽导异孙阵阳收阶阴防如妇好她妈戏羽观欢买红驮纤级约纪驰巡")
    surname = random.choice(surnames)
    given_len = random.choice([1, 2])
    given = "".join(random.choice(given_chars) for _ in range(given_len))
    return surname + given


def main():
    wb = Workbook()
    ws = wb.active
    ws.title = "user"

    ws.append(["id", "name"])
    for i in range(1, 11):
        ws.append([i, random_cn_name()])

    out_path = os.path.join(os.path.dirname(__file__), "user.xlsx")
    wb.save(out_path)
    print("saved ->", out_path)


if __name__ == "__main__":
    main()

这个 demo 用 openpyxl 生成 Excel:

  • 输出文件:user.xlsx
  • Sheet:user
  • 表头:idname
  • 数据:随机 10 个姓名

运行:

& "..\.python-embed\python.exe" 11_generate_user_excel.py

12. 你可以怎么用这套 demo

  • 当成“Python 最小工具箱”:复制某个脚本改两行就能完成临时需求
  • 当成“速记手册”:忘了 with open(...) / requests.get(...) 直接回来抄
  • 当成“前端同学上手模板”:从 05/06/09 开始就能快速进入“接口 + 自动化”节奏
❌