如何编写Python文件复制脚本及获取目录最新图片并复制到剪贴板
2. 如何编写脚本获取指定目录最新图片并复制到剪贴板?
这个需求分两步走:找出目录里最新的图片 + 把图片复制到剪贴板,我给你拆解成可复用的代码块:
第一步:筛选最新图片
用os模块遍历目录,通过扩展名判断图片,再按修改时间排序取最新的:
import os def get_latest_image(dir_path): # 定义常见的图片扩展名,你可以根据需要添加 image_exts = ('.jpg', '.jpeg', '.png', '.gif', '.bmp') # 获取目录下所有文件的完整路径 all_files = [os.path.join(dir_path, f) for f in os.listdir(dir_path)] # 筛选出真正的图片文件(排除子目录) image_files = [f for f in all_files if os.path.isfile(f) and f.lower().endswith(image_exts)] if not image_files: print("目录里没找到任何图片文件!") return None # 按修改时间倒序,取第一个就是最新的 latest_img = max(image_files, key=os.path.getmtime) print(f"找到最新图片:{latest_img}") return latest_img
第二步:复制图片到剪贴板
不同系统的剪贴板机制不一样,这里做了跨平台兼容:
import sys import subprocess import io from PIL import Image # Windows需要,先跑pip install pillow import win32clipboard # Windows需要,先跑pip install pywin32 def copy_image_to_clipboard(image_path): if not image_path: return False try: if sys.platform == 'win32': # Windows剪贴板需要特定的位图格式,用PIL转换 img = Image.open(image_path) output = io.BytesIO() img.convert("RGB").save(output, "BMP") # 去掉BMP文件头的前14字节,只保留像素数据 img_data = output.getvalue()[14:] output.close() win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, img_data) win32clipboard.CloseClipboard() print("图片已复制到剪贴板(Windows)") elif sys.platform == 'darwin': # macOS用系统自带的pbcopy命令 subprocess.run( ['pbcopy', '-Prefer', 'TIFF', '<', image_path], shell=True, check=True ) print("图片已复制到剪贴板(macOS)") elif sys.platform.startswith('linux'): # Linux需要先装xclip:sudo apt install xclip subprocess.run( ['xclip', '-selection', 'clipboard', '-t', 'image/png', image_path], check=True ) print("图片已复制到剪贴板(Linux)") else: print(f"抱歉,暂不支持你的系统:{sys.platform}") return False return True except ImportError as e: print(f"请先安装依赖:{str(e)}") except subprocess.CalledProcessError: print("执行系统命令失败,Linux用户请检查是否装了xclip") except Exception as e: print(f"复制出错:{str(e)}") return False # 测试调用,替换成你的目标目录 if __name__ == "__main__": target_dir = "/home/user/Pictures" latest_img = get_latest_image(target_dir) copy_image_to_clipboard(latest_img)
内容的提问来源于stack exchange,提问作者inthanwill12
相关产品推荐
相关产品推荐

