基于Python打造一個高效開發(fā)輔助全能工具箱
1.概述
在日常開發(fā)過程中,我們經(jīng)常需要進行各種瑣碎但又必不可少的操作,比如文件處理、編碼轉(zhuǎn)換、哈希計算、二維碼生成、單位換算等。如果每次都需要單獨尋找工具或者編寫零散的代碼,效率難免會受到影響。因此,本文介紹一款基于 Python 編寫的 全能工具箱,它涵蓋了開發(fā)過程中常用的功能,極大地提高了工作效率。
該工具箱主要涵蓋以下功能:
- 文件操作(合并、拆分、編碼轉(zhuǎn)換)
- 二維碼生成與解析
- 哈希計算(MD5、SHA256等)
- 時間轉(zhuǎn)換(時間戳與日期格式互轉(zhuǎn))
- IP 歸屬地查詢
- 單位換算(文件大小、人類可讀格式)
接下來,我們將詳細介紹如何使用這些功能,并展示相關(guān)代碼示例。
2.功能使用指南
1.文件操作
在開發(fā)過程中,我們經(jīng)常需要合并多個文件或者拆分大文件。以下是文件合并的示例代碼:
import os def merge_files(input_files, output_file): with open(output_file, 'wb') as outfile: for file in input_files: with open(file, 'rb') as infile: outfile.write(infile.read()) print(f'文件合并完成: {output_file}')
使用方式:
merge_files(['file1.txt', 'file2.txt'], 'merged.txt')
類似地,我們可以拆分大文件:
def split_file(input_file, chunk_size): with open(input_file, 'rb') as infile: chunk_number = 1 while chunk := infile.read(chunk_size): with open(f'{input_file}.part{chunk_number}', 'wb') as chunk_file: chunk_file.write(chunk) chunk_number += 1 print(f'文件拆分完成,共 {chunk_number - 1} 份')
2.二維碼生成與解析
Python 的 qrcode 和 pyzbar 庫可以輕松處理二維碼。
生成二維碼
import qrcode def generate_qr_code(data, output_file='qrcode.png'): qr = qrcode.make(data) qr.save(output_file) print(f'二維碼已生成: {output_file}')
解析二維碼
from pyzbar.pyzbar import decode from PIL import Image ???????def decode_qr_code(image_path): data = decode(Image.open(image_path)) return data[0].data.decode(‘utf-8') if data else ‘未識別到二維碼'
3.哈希計算
計算 MD5 和 SHA256
import hashlib def calculate_hash(file_path, hash_type='md5'): hash_func = hashlib.md5() if hash_type == 'md5' else hashlib.sha256() with open(file_path, 'rb') as f: while chunk := f.read(4096): hash_func.update(chunk) return hash_func.hexdigest()
示例:
print(calculate_hash('example.txt', 'sha256'))
4.時間戳轉(zhuǎn)換
時間戳轉(zhuǎn)日期
from datetime import datetime ???????def timestamp_to_date(timestamp): return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
日期轉(zhuǎn)時間戳
def date_to_timestamp(date_str): return int(datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').timestamp())
5.IP 歸屬地查詢
查詢 IP 歸屬地(基于 API)
import requests def get_ip_location(ip): url = f'https://ipinfo.io/{ip}/json' response = requests.get(url) return response.json() if response.status_code == 200 else '查詢失敗'
示例:
print(get_ip_location('8.8.8.8'))
6.單位換算
文件大小轉(zhuǎn)換
def human_readable_size(size_bytes): units = ['B', 'KB', 'MB', 'GB', 'TB'] i = 0 while size_bytes >= 1024 and i < len(units) - 1: size_bytes /= 1024.0 i += 1 return f'{size_bytes:.2f} {units[i]}'
示例:
print(human_readable_size(1048576)) # 1.00 MB
3.運行效果
4.相關(guān)源碼
import tkinter as tk from tkinter import ttk, filedialog, messagebox import base64 import hashlib import os import qrcode import webbrowser import time import random import json import requests from PIL import Image, ImageTk from datetime import datetime from tkinter import scrolledtext import pyperclip import zhconv class ToolBox: def __init__(self, root): self.root = root self.root.title("超級工具箱 v2.0") self.root.geometry("1000x800") # 創(chuàng)建標簽容器 self.notebook = ttk.Notebook(root) self.notebook.pack(fill='both', expand=True) # 創(chuàng)建各個功能標簽頁 self.create_file_tools_tab() self.create_encoder_tab() self.create_qrcode_tab() self.create_hash_tools_tab() self.create_time_tools_tab() self.create_network_tools_tab() self.create_conversion_tools_tab() self.create_other_tools_tab() # 添加右鍵菜單 self.create_context_menu() # 右鍵菜單功能 def create_context_menu(self): self.context_menu = tk.Menu(self.root, tearoff=0) self.context_menu.add_command(label="復制", command=self.copy_text) self.context_menu.add_command(label="粘貼", command=self.paste_text) # 綁定右鍵事件 self.root.bind("<Button-3>", self.show_context_menu) def show_context_menu(self, event): self.context_menu.post(event.x_root, event.y_root) def copy_text(self): widget = self.root.focus_get() if isinstance(widget, tk.Entry): widget.event_generate("<<Copy>>") elif isinstance(widget, tk.Text): widget.event_generate("<<Copy>>") def paste_text(self): widget = self.root.focus_get() if isinstance(widget, tk.Entry): widget.event_generate("<<Paste>>") elif isinstance(widget, tk.Text): widget.event_generate("<<Paste>>") # 以下是各功能標簽頁的創(chuàng)建和功能實現(xiàn) def create_file_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="文件工具") # 文件搜索功能 search_frame = ttk.LabelFrame(tab, text="文件搜索") search_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(search_frame, text="搜索目錄:").grid(row=0, column=0, sticky='w') self.path_entry = ttk.Entry(search_frame, width=50) self.path_entry.grid(row=0, column=1, padx=5) ttk.Button(search_frame, text="選擇目錄", command=self.browse_directory).grid(row=0, column=2) ttk.Label(search_frame, text="關(guān)鍵詞:").grid(row=1, column=0, sticky='w') self.keyword_entry = ttk.Entry(search_frame, width=50) self.keyword_entry.grid(row=1, column=1, pady=5) ttk.Button(search_frame, text="開始搜索", command=self.search_files).grid(row=2, column=1, pady=10) self.result_text = scrolledtext.ScrolledText(search_frame, height=10, width=80) self.result_text.grid(row=3, column=0, columnspan=3) # 文件批量重命名 rename_frame = ttk.LabelFrame(tab, text="批量重命名") rename_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(rename_frame, text="原文件名:").grid(row=0, column=0) self.original_name = ttk.Entry(rename_frame, width=25) self.original_name.grid(row=0, column=1) ttk.Label(rename_frame, text="新文件名:").grid(row=0, column=2) self.new_name = ttk.Entry(rename_frame, width=25) self.new_name.grid(row=0, column=3) ttk.Button(rename_frame, text="執(zhí)行重命名", command=self.batch_rename).grid(row=0, column=4, padx=10) def create_encoder_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="編解碼工具") # Base64 編解碼 base64_frame = ttk.LabelFrame(tab, text="Base64 編解碼") base64_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(base64_frame, text="輸入內(nèi)容:").grid(row=0, column=0) self.base64_input = scrolledtext.ScrolledText(base64_frame, height=5, width=40) self.base64_input.grid(row=0, column=1, padx=5) btn_frame = ttk.Frame(base64_frame) btn_frame.grid(row=1, column=1, pady=5) ttk.Button(btn_frame, text="編碼", command=self.base64_encode).pack(side='left', padx=5) ttk.Button(btn_frame, text="解碼", command=self.base64_decode).pack(side='left', padx=5) ttk.Button(btn_frame, text="清空", command=self.clear_base64).pack(side='right', padx=5) ttk.Label(base64_frame, text="結(jié)果:").grid(row=2, column=0) self.base64_output = scrolledtext.ScrolledText(base64_frame, height=5, width=40) self.base64_output.grid(row=2, column=1, padx=5) # URL 編解碼 url_frame = ttk.LabelFrame(tab, text="URL 編解碼") url_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(url_frame, text="URL:").grid(row=0, column=0) self.url_entry = ttk.Entry(url_frame, width=50) self.url_entry.grid(row=0, column=1, padx=5) btn_frame = ttk.Frame(url_frame) btn_frame.grid(row=1, column=1, pady=5) ttk.Button(btn_frame, text="編碼", command=self.url_encode).pack(side='left', padx=5) ttk.Button(btn_frame, text="解碼", command=self.url_decode).pack(side='left', padx=5) def create_qrcode_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="二維碼工具") frame = ttk.LabelFrame(tab, text="二維碼生成器") frame.pack(padx=10, pady=10, fill='both', expand=True) ttk.Label(frame, text="輸入內(nèi)容:").grid(row=0, column=0) self.qr_content = ttk.Entry(frame, width=60) self.qr_content.grid(row=0, column=1, padx=5) ttk.Button(frame, text="生成二維碼", command=self.generate_qrcode).grid(row=1, column=1, pady=5) ttk.Button(frame, text="保存二維碼", command=self.save_qrcode).grid(row=1, column=0, pady=5) self.qr_image_label = ttk.Label(frame) self.qr_image_label.grid(row=2, column=0, columnspan=2) def create_hash_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="哈希工具") # 字符串哈希 str_frame = ttk.LabelFrame(tab, text="字符串哈希") str_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(str_frame, text="輸入字符串:").grid(row=0, column=0) self.hash_input = ttk.Entry(str_frame, width=50) self.hash_input.grid(row=0, column=1) ttk.Button(str_frame, text="計算哈希", command=self.calculate_str_hash).grid(row=0, column=2) self.hash_result = ttk.Entry(str_frame, width=70) self.hash_result.grid(row=1, column=0, columnspan=3, pady=5) # 文件哈希 file_frame = ttk.LabelFrame(tab, text="文件哈希") file_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(file_frame, text="選擇文件:").grid(row=0, column=0) self.file_hash_entry = ttk.Entry(file_frame, width=50) self.file_hash_entry.grid(row=0, column=1) ttk.Button(file_frame, text="瀏覽", command=self.browse_hash_file).grid(row=0, column=2) ttk.Button(file_frame, text="計算文件哈希", command=self.calculate_file_hash).grid(row=1, column=1) def create_time_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="時間工具") # 時間戳轉(zhuǎn)換 ts_frame = ttk.LabelFrame(tab, text="時間戳轉(zhuǎn)換") ts_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(ts_frame, text="時間戳:").grid(row=0, column=0) self.timestamp_entry = ttk.Entry(ts_frame) self.timestamp_entry.grid(row=0, column=1) ttk.Button(ts_frame, text="轉(zhuǎn)換", command=self.timestamp_to_datetime).grid(row=0, column=2) ttk.Label(ts_frame, text="日期時間:").grid(row=1, column=0) self.datetime_entry = ttk.Entry(ts_frame) self.datetime_entry.grid(row=1, column=1) ttk.Button(ts_frame, text="轉(zhuǎn)換", command=self.datetime_to_timestamp).grid(row=1, column=2) ttk.Button(ts_frame, text="當前時間", command=self.get_current_time).grid(row=2, column=1) def create_network_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="網(wǎng)絡(luò)工具") # IP查詢 ip_frame = ttk.LabelFrame(tab, text="IP地址查詢") ip_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(ip_frame, text="輸入IP:").grid(row=0, column=0) self.ip_entry = ttk.Entry(ip_frame, width=25) self.ip_entry.grid(row=0, column=1) ttk.Button(ip_frame, text="查詢", command=self.ip_lookup).grid(row=0, column=2) self.ip_result = scrolledtext.ScrolledText(ip_frame, height=5, width=60) self.ip_result.grid(row=1, column=0, columnspan=3) def create_conversion_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="轉(zhuǎn)換工具") # 單位轉(zhuǎn)換 unit_frame = ttk.LabelFrame(tab, text="單位轉(zhuǎn)換") unit_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(unit_frame, text="數(shù)值:").grid(row=0, column=0) self.num_entry = ttk.Entry(unit_frame, width=15) self.num_entry.grid(row=0, column=1) self.unit_from = ttk.Combobox(unit_frame, values=["米", "千米", "英尺"]) self.unit_from.grid(row=0, column=2) ttk.Label(unit_frame, text="轉(zhuǎn)換為").grid(row=0, column=3) self.unit_to = ttk.Combobox(unit_frame, values=["米", "千米", "英尺"]) self.unit_to.grid(row=0, column=4) ttk.Button(unit_frame, text="轉(zhuǎn)換", command=self.unit_convert).grid(row=0, column=5) self.unit_result = ttk.Label(unit_frame, text="結(jié)果:") self.unit_result.grid(row=1, column=0, columnspan=6) # 簡繁轉(zhuǎn)換 zh_frame = ttk.LabelFrame(tab, text="簡繁轉(zhuǎn)換") zh_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(zh_frame, text="輸入文本:").grid(row=0, column=0) self.zh_input = scrolledtext.ScrolledText(zh_frame, height=3, width=30) self.zh_input.grid(row=0, column=1) btn_frame = ttk.Frame(zh_frame) btn_frame.grid(row=1, column=1) ttk.Button(btn_frame, text="轉(zhuǎn)簡體", command=lambda: self.convert_zh('zh-cn')).pack(side='left') ttk.Button(btn_frame, text="轉(zhuǎn)繁體", command=lambda: self.convert_zh('zh-tw')).pack(side='left') self.zh_output = scrolledtext.ScrolledText(zh_frame, height=3, width=30) self.zh_output.grid(row=2, column=1) def create_other_tools_tab(self): tab = ttk.Frame(self.notebook) self.notebook.add(tab, text="其他工具") # 密碼生成器 pwd_frame = ttk.LabelFrame(tab, text="隨機密碼生成") pwd_frame.pack(padx=10, pady=5, fill='both', expand=True) ttk.Label(pwd_frame, text="長度:").grid(row=0, column=0) self.pwd_length = ttk.Spinbox(pwd_frame, from_=6, to=32, width=5) self.pwd_length.grid(row=0, column=1) self.use_digits = tk.BooleanVar(value=True) ttk.Checkbutton(pwd_frame, text="包含數(shù)字", variable=self.use_digits).grid(row=0, column=2) self.use_symbols = tk.BooleanVar(value=True) ttk.Checkbutton(pwd_frame, text="包含符號", variable=self.use_symbols).grid(row=0, column=3) ttk.Button(pwd_frame, text="生成密碼", command=self.generate_password).grid(row=0, column=4) self.password_entry = ttk.Entry(pwd_frame, width=30) self.password_entry.grid(row=1, column=0, columnspan=5, pady=5) # 以下是各功能的實現(xiàn)方法 def browse_directory(self): path = filedialog.askdirectory() self.path_entry.delete(0, tk.END) self.path_entry.insert(0, path) def search_files(self): directory = self.path_entry.get() keyword = self.keyword_entry.get() if not directory or not keyword: messagebox.showwarning("提示", "請先選擇目錄并輸入關(guān)鍵詞") return self.result_text.delete(1.0, tk.END) count = 0 for root, dirs, files in os.walk(directory): for file in files: if keyword.lower() in file.lower(): filepath = os.path.join(root, file) self.result_text.insert(tk.END, filepath + "\n") count += 1 self.result_text.insert(tk.END, f"\n找到 {count} 個匹配文件") def batch_rename(self): original = self.original_name.get() new = self.new_name.get() directory = self.path_entry.get() if not directory: messagebox.showwarning("提示", "請先選擇目錄") return count = 0 for filename in os.listdir(directory): if original in filename: new_filename = filename.replace(original, new) os.rename( os.path.join(directory, filename), os.path.join(directory, new_filename) ) count += 1 messagebox.showinfo("完成", f"成功重命名 {count} 個文件") def base64_encode(self): text = self.base64_input.get("1.0", tk.END).strip() encoded = base64.b64encode(text.encode()).decode() self.base64_output.delete("1.0", tk.END) self.base64_output.insert(tk.END, encoded) def base64_decode(self): text = self.base64_input.get("1.0", tk.END).strip() try: decoded = base64.b64decode(text).decode() self.base64_output.delete("1.0", tk.END) self.base64_output.insert(tk.END, decoded) except: messagebox.showerror("錯誤", "解碼失敗,請檢查輸入內(nèi)容") def clear_base64(self): self.base64_input.delete("1.0", tk.END) self.base64_output.delete("1.0", tk.END) def url_encode(self): text = self.url_entry.get() encoded = requests.utils.quote(text) self.url_entry.delete(0, tk.END) self.url_entry.insert(0, encoded) def url_decode(self): text = self.url_entry.get() decoded = requests.utils.unquote(text) self.url_entry.delete(0, tk.END) self.url_entry.insert(0, decoded) def generate_qrcode(self): data = self.qr_content.get() if not data: return qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(data) qr.make(fit=True) self.qr_img = qr.make_image(fill_color="black", back_color="white") self.display_qrcode() def display_qrcode(self): self.qr_img.save("temp_qr.png") image = Image.open("temp_qr.png") image.thumbnail((300, 300)) photo = ImageTk.PhotoImage(image) self.qr_image_label.config(image=photo) self.qr_image_label.image = photo def save_qrcode(self): if hasattr(self, 'qr_img'): filename = filedialog.asksaveasfilename( defaultextension=".png", filetypes=[("PNG文件", "*.png"), ("所有文件", "*.*")] ) if filename: self.qr_img.save(filename) messagebox.showinfo("保存成功", "二維碼已保存") def calculate_str_hash(self): text = self.hash_input.get() algorithms = ['md5', 'sha1', 'sha256'] results = [] for algo in algorithms: hash_obj = hashlib.new(algo) hash_obj.update(text.encode()) results.append(f"{algo.upper()}: {hash_obj.hexdigest()}") self.hash_result.delete(0, tk.END) self.hash_result.insert(0, " | ".join(results)) def browse_hash_file(self): filename = filedialog.askopenfilename() self.file_hash_entry.delete(0, tk.END) self.file_hash_entry.insert(0, filename) def calculate_file_hash(self): filename = self.file_hash_entry.get() if not os.path.isfile(filename): return hash_md5 = hashlib.md5() with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) self.hash_result.delete(0, tk.END) self.hash_result.insert(0, f"MD5: {hash_md5.hexdigest()}") def timestamp_to_datetime(self): try: ts = int(self.timestamp_entry.get()) dt = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') self.datetime_entry.delete(0, tk.END) self.datetime_entry.insert(0, dt) except: messagebox.showerror("錯誤", "無效的時間戳") def datetime_to_timestamp(self): try: dt_str = self.datetime_entry.get() dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') ts = int(dt.timestamp()) self.timestamp_entry.delete(0, tk.END) self.timestamp_entry.insert(0, ts) except: messagebox.showerror("錯誤", "無效的日期格式") def get_current_time(self): current_ts = int(time.time()) current_dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.timestamp_entry.delete(0, tk.END) self.timestamp_entry.insert(0, current_ts) self.datetime_entry.delete(0, tk.END) self.datetime_entry.insert(0, current_dt) def ip_lookup(self): ip = self.ip_entry.get() try: response = requests.get(f"http://ip-api.com/json/{ip}") data = response.json() result = f""" 國家: {data.get('country', '未知')} 地區(qū): {data.get('regionName', '未知')} 城市: {data.get('city', '未知')} ISP: {data.get('isp', '未知')} AS: {data.get('as', '未知')} """ self.ip_result.delete(1.0, tk.END) self.ip_result.insert(tk.END, result) except: messagebox.showerror("錯誤", "查詢失敗") def unit_convert(self): try: value = float(self.num_entry.get()) unit_from = self.unit_from.get() unit_to = self.unit_to.get() # 轉(zhuǎn)換系數(shù)(米為基準單位) units = { "米": 1, "千米": 1000, "英尺": 0.3048 } result = value * units[unit_from] / units[unit_to] self.unit_result.config(text=f"結(jié)果: {result:.4f} {unit_to}") except: messagebox.showerror("錯誤", "無效的輸入") def convert_zh(self, target): text = self.zh_input.get("1.0", tk.END) converted = zhconv.convert(text, target) self.zh_output.delete("1.0", tk.END) self.zh_output.insert(tk.END, converted) def generate_password(self): length = int(self.pwd_length.get()) chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' if self.use_digits.get(): chars += '0123456789' if self.use_symbols.get(): chars += '!@#$%^&*()_+-=' password = ''.join(random.choice(chars) for _ in range(length)) self.password_entry.delete(0, tk.END) self.password_entry.insert(0, password) pyperclip.copy(password) messagebox.showinfo("提示", "密碼已復制到剪貼板") if __name__ == "__main__": root = tk.Tk() app = ToolBox(root) root.mainloop()
5.總結(jié)
本文介紹了如何使用 Python 實現(xiàn)一款 高效的全能工具箱,涵蓋了文件操作、二維碼處理、哈希計算、時間轉(zhuǎn)換、IP 查詢和單位換算等功能。此工具能夠幫助開發(fā)者提高工作效率,減少重復勞動,適用于各種開發(fā)場景。
你可以擴展以下功能:
GUI 界面(PyQt5/Tkinter):打造更加直觀的操作界面
多線程優(yōu)化:提升處理效率
日志系統(tǒng):記錄操作歷史
以上就是基于Python打造一個高效開發(fā)輔助全能工具箱的詳細內(nèi)容,更多關(guān)于Python開發(fā)輔助工具箱的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python爬蟲實現(xiàn)教程轉(zhuǎn)換成 PDF 電子書
本文給大家分享的是使用python爬蟲實現(xiàn)把《廖雪峰的 Python 教程》轉(zhuǎn)換成PDF的方法和代碼,有需要的小伙伴可以參考下2017-02-02基于Python實現(xiàn)合并多張圖片轉(zhuǎn)成mp4視頻
隨著現(xiàn)代科技飛速發(fā)展和人們提升視覺上體驗,利用圖片生成視頻的方法,確實為工作或者提升生活體驗感做了很多成功案例,本文就來介紹一下具體實現(xiàn)方法吧2023-04-04python基礎(chǔ)之變量和數(shù)據(jù)類型
這篇文章主要介紹了python的變量和數(shù)據(jù)類型,實例分析了Python中返回一個返回值與多個返回值的方法,需要的朋友可以參考下2021-10-10python通過socket搭建極簡web服務(wù)器的實現(xiàn)代碼
python的web框架眾多,常見的如django、flask、tornado等,其底層是什么還是有些許的疑問,所以查找相關(guān)資料,實現(xiàn)瀏覽器訪問,并返回相關(guān)信息,本文將給大家介紹python通過socket搭建極簡web服務(wù)器,需要的朋友可以參考下2023-10-10