it编程 > 前端脚本 > Python

一文分享4个Python实用脚本让你效率爆表

6人参与 2026-01-31 Python

1小时久坐弹窗提醒

# -*- coding: utf-8 -*-
# 久坐弹窗提醒
# 打包后自动开机后台运行 把生成的exe放到 win+r → shell:startup 文件夹里即可
# 打包成exe:pyinstaller --onefile --noconsole stand_up.py

import ctypes
import time
import os
import sys
import pathlib

title = "休息提醒"
msg   = "你已久坐1小时,站起来活动一下吧!"

def popup():
    ctypes.windll.user32.messageboxw(0, msg, title, 0x00000040 | 0x00000030)

def main():
    # 单例:防止重复运行
    lock = pathlib.path(__file__).with_suffix('.lock')
    if lock.exists():
        sys.exit(0)
    lock.write_text(str(os.getpid()))
    try:
        while true:
            time.sleep(60 * 60)   #间隔1小时
            popup()
    finally:
        lock.unlink(missing_ok=true)

if __name__ == '__main__':
    main()

每天10点点外卖弹窗提醒

# -*- coding: utf-8 -*-
# 点外卖弹窗提醒
# 打包后自动开机后台运行 把生成的exe放到 win+r → shell:startup 文件夹里即可
# 打包成exe:pyinstaller --onefile --noconsole food_order.py

import time
import datetime
import ctypes
import os
import sys
import pathlib

title = "点外卖啦~"
msg   = "10点了,记得点外卖!"

def popup():
    """调用 windows 系统弹窗 + 提示音"""
    ctypes.windll.user32.messageboxw(0, msg, title, 0x00000040 | 0x00000030)

def next_10am():
    now = datetime.datetime.now()
    today10 = now.replace(hour=10, minute=0, second=0, microsecond=0)
    return today10 if now < today10 else today10 + datetime.timedelta(days=1)

def main():
    # 单例:若已运行则退出
    lock = pathlib.path(__file__).with_suffix('.lock')
    if lock.exists():
        sys.exit(0)
    lock.write_text(str(os.getpid()))
    try:
        while true:
            sec = (next_10am() - datetime.datetime.now()).total_seconds()
            if sec > 0:
                time.sleep(sec)
            popup()
            time.sleep(60*60*24)          # 一天只弹一次
    finally:
        lock.unlink(missing_ok=true)

if __name__ == '__main__':
    main()

多个excel合并成1个excel多个sheet

# -*- coding: utf-8 -*-
# 多个excel合并成1个excel多个sheet
# 打包成exe:pyinstaller --onefile --noconsole excel_merge.py

import os
import tkinter as tk
from tkinter import filedialog, messagebox
from openpyxl import workbook, load_workbook
from copy import copy

def sanitize_sheet_name(name):
    """清理 excel sheet 名称中的非法字符"""
    invalid_chars = ['/', '\', '*', '?', ':', '[', ']', '"']
    for ch in invalid_chars:
        name = name.replace(ch, '_')
    return name[:31]  # excel sheet 名称最多 31 个字符

def copy_cell(source_cell, target_cell):
    """复制单元格内容与样式"""
    target_cell.value = source_cell.value
    if source_cell.has_style:
        target_cell.font = copy(source_cell.font)
        target_cell.border = copy(source_cell.border)
        target_cell.fill = copy(source_cell.fill)
        target_cell.number_format = copy(source_cell.number_format)
        target_cell.protection = copy(source_cell.protection)
        target_cell.alignment = copy(source_cell.alignment)

def copy_worksheet(src_ws, dst_wb, new_sheet_name):
    """复制一个工作表到目标工作簿"""
    new_sheet = dst_wb.create_sheet(title=new_sheet_name)
    for row in src_ws.iter_rows():
        for cell in row:
            if cell.column_letter in src_ws.column_dimensions:
                new_sheet.column_dimensions[cell.column_letter].width = src_ws.column_dimensions[cell.column_letter].width
            if cell.row in src_ws.row_dimensions:
                new_sheet.row_dimensions[cell.row].height = src_ws.row_dimensions[cell.row].height
            new_cell = new_sheet.cell(row=cell.row, column=cell.column)
            copy_cell(cell, new_cell)

    # 复制合并区域
    for merge_range in src_ws.merged_cells.ranges:
        new_sheet.merge_cells(str(merge_range))

    # 复制注释
    for comment in src_ws._comments:
        new_sheet.add_comment(comment.text, comment.author, comment.shape_id)

    # 复制图像(如果需要)
    for img in src_ws._images:
        new_sheet.add_image(img)

def merge_excel_files_to_sheets(file_paths, output_path):
    """将多个 excel 文件合并到一个文件的不同 sheet 中(保留样式)"""
    if not file_paths:
        return

    # 创建新工作簿
    new_wb = workbook()
    new_wb.remove(new_wb.active)  # 删除默认的 sheet

    for file_path in file_paths:
        try:
            wb = load_workbook(file_path)
            base_name = os.path.splitext(os.path.basename(file_path))[0]
            sheet_name = sanitize_sheet_name(base_name)
            for ws in wb.worksheets:
                ws_name = f"{sheet_name}_{ws.title}" if len(wb.worksheets) > 1 else sheet_name
                copy_worksheet(ws, new_wb, ws_name)
        except exception as e:
            print(f"读取文件失败: {file_path} - {e}")
            continue

    # 保存合并后的文件
    new_wb.save(output_path)
    messagebox.showinfo("完成", "文件合并完成!样式已保留。")

def select_files():
    """gui 界面:选择多个 excel 文件并指定输出路径"""
    root = tk.tk()
    root.withdraw()  # 隐藏主窗口

    # 选择多个 excel 文件
    file_paths = filedialog.askopenfilenames(
        title="选择 excel 文件",
        filetypes=[("excel 文件", "*.xlsx")]
    )
    if not file_paths:
        messagebox.showwarning("警告", "未选择任何文件。")
        return

    # 选择输出路径
    output_path = filedialog.asksaveasfilename(
        title="保存合并后的 excel 文件",
        defaultextension=".xlsx",
        filetypes=[("excel 文件", "*.xlsx")]
    )
    if not output_path:
        return

    # 合并文件
    merge_excel_files_to_sheets(file_paths, output_path)

if __name__ == "__main__":
    select_files()

强密码生成

# -*- coding: utf-8 -*-
# 强密码生成器
# 打包成exe:pyinstaller --onefile --noconsole strong_passwd.py

import secrets, string, argparse, sys

def pwd(length=16, symbols=true):
    pool = string.ascii_letters + string.digits
    if symbols:
        pool += string.punctuation
    return ''.join(secrets.choice(pool) for _ in range(length))

if __name__ == '__main__':
    ap = argparse.argumentparser()
    ap.add_argument('-l', '--length', type=int, default=16)
    ap.add_argument('-n', '--no-symbols', action='store_true')
    args = ap.parse_args()
    print(pwd(args.length, not args.no_symbols))

总结

以上我们了解了4个脚本工具,可用于日常办公使用。

到此这篇关于一文分享4个python实用脚本让你效率爆表的文章就介绍到这了,更多相关python脚本内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

Python使用PyQt5打造桌面应用的入门指南

01-31

从原理到实战详解Python中文件并发读写的避坑指南

01-31

10 个Python统计分析常用的经典脚本分享

01-31

Python实现在Excel中动态插入与删除图片的完整指南

01-31

Python Flask实现多文件项目打包部署(Linux+Docker+Windows全环境)指南

01-31

Python 的 print使用解析

01-31

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论