首页 健康生活文章正文

7 段不到 50 行的 Python 脚本,解决 7 个真实麻烦:代码、场景与可复制

健康生活 2025年09月05日 10:23 2 admin
7 段不到 50 行的 Python 脚本,解决 7 个真实麻烦:代码、场景与可复制

Python 脚本

本文整理自开发者 Abdur Rahman 在 Stackademic 的真实记录,所有代码均经过最小化删减,确保在 50 行内即可运行。每段脚本都对应一个日常场景,拿来即用,无需额外依赖。


一、在朋友家连不上 Wi-Fi?一行命令找回已保存密码

问题还原

去朋友家做客,电脑曾经连过 Wi-Fi,但密码早已忘记;朋友也记不清。手动翻系统设置太麻烦,还容易出错。

解决思路

Windows 系统把连接过的 Wi-Fi 配置保存在本地,只是默认不显示明文密码。用netsh命令可以调出配置,再用正则提取即可。

50 行以内代码

import subprocess, redef get_saved_wifi_passwords():    output = subprocess.check_output('netsh wlan show profiles', shell=True).decode()    profiles = re.findall(r"All User Profile\s*:\s(.*)", output)    for profile in profiles:        profile = profile.strip()        result = subprocess.check_output(            f'netsh wlan show profile name="{profile}" key=clear', shell=True        ).decode()        password = re.search(r"Key Content\s*:\s(.*)", result)        if password:            print(f"{profile}: {password.group(1)}")get_saved_wifi_passwords()

使用提示

  1. 直接在 CMD 或 PowerShell 运行脚本。
  2. 输出格式为“网络名: 密码”,复制即可。
  3. 仅在本地已连接过的网络有效,无法破解陌生 Wi-Fi。

二、多设备开发,仓库总不同步?自动克隆与拉取一次搞定

问题还原

白天在公司电脑 clone 了新仓库,晚上回家想用笔记本继续写代码,却忘记同步;第二天又出现冲突,浪费时间。

解决思路

GitHub 提供 REST API,可一次性获取个人所有仓库地址。脚本先检查本地是否存在同名目录:不存在就 clone,存在就 pull。

50 行以内代码

import requests, os, subprocessUSERNAME = 'your_github_username'TOKEN = 'your_github_token'def sync_github_repos():    headers = {'Authorization': f'token {TOKEN}'}    repos = requests.get(f'https://api.github.com/users/{USERNAME}/repos', headers=headers).json()    for repo in repos:        name, clone_url = repo['name'], repo['clone_url']        if not os.path.exists(name):            subprocess.run(['git', 'clone', clone_url])            print(f'Cloned: {name}')        else:            subprocess.run(['git', '-C', name, 'pull'])            print(f'Updated: {name}')sync_github_repos()

使用提示

  1. 将脚本设为定时任务(Windows 任务计划或 Linux cron),每 30 分钟跑一次。
  2. TOKEN 需在 GitHub「Settings > Developer settings > Personal access tokens」生成,只勾选repo权限即可。
  3. 若仓库较多,首次 clone 耗时较长,后续仅增量更新。

三、凌晨三点服务挂了?30 秒自检重启脚本

问题还原

小型项目上线后无人值守,进程偶尔崩溃。虽可接入专业监控,但配置复杂,对轻量级应用来说太重。

解决思路

pgrep检测进程是否存在,不存在就通过subprocess.Popen重新启动。死循环+30 秒睡眠即可实现“自愈”。

50 行以内代码

import subprocess, timedef is_running(process_name):    result = subprocess.run(['pgrep', '-f', process_name], stdout=subprocess.PIPE)    return result.returncode == 0def monitor_and_restart(command):    while True:        if not is_running(command.split()[0]):            print(f"Restarting process: {command}")            subprocess.Popen(command.split())        time.sleep(30)monitor_and_restart("python3 my_server_script.py")

使用提示

  1. my_server_script.py换成真实入口文件。
  2. 可放到nohupscreen中后台运行,日志重定向到文件,方便排查。
  3. Linux/macOS 通用;Windows 需改用taskliststart命令。

四、会议太多容易错过?Google Calendar 自动输出今日议程

问题还原

日历里排满会议,但高强度编码时无暇查看网页;错过会议后还得尴尬解释。

解决思路

Google Calendar API 提供只读权限,拉取当日事件后,按时间排序输出标题与开始时间,一目了然。

50 行以内代码

from googleapiclient.discovery import buildfrom oauth2client.service_account import ServiceAccountCredentialsfrom datetime import datetimedef get_upcoming_events():    scopes = ['https://www.googleapis.com/auth/calendar.readonly']    creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scopes)    service = build('calendar', 'v3', credentials=creds)    now = datetime.utcnow().isoformat() + 'Z'    events = service.events().list(        calendarId='primary', timeMin=now,        maxResults=5, singleEvents=True,        orderBy='startTime').execute().get('items', [])    for event in events:        start = event['start'].get('dateTime', event['start'].get('date'))        print(f"{event['summary']} at {start}")get_upcoming_events()

使用提示

  1. 在 Google Cloud Console 创建服务账号,下载credentials.json并放在脚本同目录。
  2. 把脚本放到开机启动或早晨定时任务,每天首次开机即可看到当日安排。
  3. 如需多日历,把calendarId改为对应 ID 即可。

五、银行 PDF 都叫 transaction.pdf?根据内容自动改名

问题还原

每月从网银批量下载账单,文件名全是transaction(1).pdftransaction(2).pdf;报销时需要翻半天。

解决思路

用 PyPDF2 提取第一页文本,匹配关键字(如“Starbucks”)再重命名。规则可自定义,准确率 90%以上。

50 行以内代码

import osfrom PyPDF2 import PdfReaderdef rename_pdfs(folder):    for filename in os.listdir(folder):        if filename.endswith(".pdf"):            path = os.path.join(folder, filename)            text = PdfReader(path).pages[0].extract_text()            if "Starbucks" in text:                os.rename(path, os.path.join(folder, "starbucks_receipt.pdf"))            elif "Amazon" in text:                os.rename(path, os.path.join(folder, "amazon_invoice.pdf"))rename_pdfs('/path/to/receipts')

使用提示

  1. /path/to/receipts换成实际目录。
  2. 关键字可扩展成列表+循环,适配更多商户。
  3. 若出现同名文件,脚本会覆盖,请提前备份或加时间戳。

六、离开咖啡店担心电脑被偷?拔掉 USB 立即锁屏

问题还原

公共场所短暂离开,手动锁屏容易忘;一旦设备丢失,数据风险巨大。

解决思路

利用psutil枚举磁盘,发现可移动磁盘消失即调用系统锁屏命令。USB 作为“钥匙”,拔掉即触发。

50 行以内代码

import subprocess, time, psutildef is_usb_connected():    for part in psutil.disk_partitions():        if 'removable' in part.opts:            return True    return Falsedef monitor_usb():    while True:        if not is_usb_connected():            subprocess.run('gnome-screensaver-command -l', shell=True)            print("USB removed. System locked.")            break        time.sleep(2)monitor_usb()

使用提示

  1. 仅 GNOME 桌面测试通过;KDE 改为qdbus org.freedesktop.ScreenSaver /ScreenSaver Lock
  2. Windows 用户可把锁屏命令换成rundll32.exe user32.dll,LockWorkStation
  3. 建议把脚本设为开机自启,常驻后台。

七、Slack 线程消息爆炸?安静生成摘要悄悄看

问题还原

离线几小时,Slack 某线程刷屏上百条;不想打扰同事,又必须快速掌握要点。

解决思路

调用 Slack API 获取线程回复,取前 5 条消息拼接成列表,本地打印即可。无@,无广播,零打扰。

50 行以内代码

import requestsdef summarize_thread(channel_id, thread_ts, token):    headers = {'Authorization': f'Bearer {token}'}    url = f"https://slack.com/api/conversations.replies?channel={channel_id}&ts={thread_ts}"    messages = [msg['text'] for msg in requests.get(url, headers=headers).json()['messages']]    print("Thread Summary:\n", '\n'.join(f"- {m}" for m in messages[:5]))summarize_thread('C12345678', '1620750234.000200', 'xoxb-your-slack-token')

使用提示

  1. channel_idthread_ts可在 Slack 桌面版右键消息「Copy link」中截取。
  2. token 需在「Your Apps > OAuth & Permissions」申请conversations:history权限。
  3. 可把脚本封装成命令行工具,离线后一键查看所有活跃线程。

结语:把代码放进生活,而非放进收藏夹

七段脚本加起来不足 350 行,却覆盖了密码找回、代码同步、服务守护、日程提醒、文件整理、物理安全、消息降噪七种真实场景。它们没有高深的算法,也不需要昂贵的服务,只把系统已提供的接口重新组合,就让日常效率向前一步。

你可以直接复制运行,也可以按需调整。真正重要的,是把“代码能解决问题”这一信念,从教程里带到真实生活。祝使用愉快。

发表评论

泰日号Copyright Your WebSite.Some Rights Reserved. 网站地图 备案号:川ICP备66666666号 Z-BlogPHP强力驱动