一文分享4個Python實用腳本讓你效率爆表
更新時間:2026年01月30日 09:19:00 作者:咖啡Beans
這篇文章主要為大家分享看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():
"""調(diào)用 Windows 系統(tǒng)彈窗 + 提示音"""
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):
"""復制單元格內(nèi)容與樣式"""
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)
# 復制合并區(qū)域
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
# 創(chuàng)建新工作簿
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))
總結(jié)
以上我們了解了4個腳本工具,可用于日常辦公使用。
到此這篇關于一文分享4個Python實用腳本讓你效率爆表的文章就介紹到這了,更多相關Python腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決selenium模塊利用performance獲取network日志請求報錯的問題(親測有效)
這篇文章主要介紹了解決selenium模塊利用performance獲取network日志請求報錯的問題(親測有效),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03
在pycharm中為項目導入anacodna環(huán)境的操作方法
這篇文章主要介紹了在pycharm中為項目導入anacodna環(huán)境的操作方法,本文圖文并茂通過實例詳解的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02

