摘要
本文分享4个Python3.8实用脚本,可用于久坐提醒、点餐提醒、excel合并、密码生成。
脚本
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个脚本工具,可用于日常办公使用。
关注公众号:咖啡Beans
在这里,我们专注于软件技术的交流与成长,分享开发心得与笔记,涵盖编程、AI、资讯、面试等多个领域。无论是前沿科技的探索,还是实用技巧的总结,我们都致力于为大家呈现有价值的内容。期待与你共同进步,开启技术之旅。
479

被折叠的 条评论
为什么被折叠?



