本文目录导读:

- 方案一:定时抓拍屏幕截图(最常用)
- 方案二:定时抓拍摄像头画面
- 方案三:更精确的定时任务(使用 schedule 库)
- 方案四:Windows 专用 - 使用 PowerShell + 任务计划程序
- 使用建议
要实现定时抓拍画面(例如屏幕截图或摄像头画面),你可以使用以下几种方法,这里我会提供最常用的Python脚本方案,适用于 Windows、macOS 和 Linux。
定时抓拍屏幕截图(最常用)
使用 pyautogui 或 PIL (Pillow) 库。
安装依赖
pip install pyautogui pillow schedule
脚本示例:每10秒抓拍一次屏幕
import pyautogui
import time
from datetime import datetime
import os
def capture_screen():
# 创建保存目录
save_dir = "screenshots"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 生成带时间戳的文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{save_dir}/screenshot_{timestamp}.png"
# 截取屏幕
screenshot = pyautogui.screenshot()
screenshot.save(filename)
print(f"已保存: {filename}")
def main():
interval = 10 # 抓拍间隔(秒)
print(f"开始定时抓拍,每 {interval} 秒一次...")
try:
while True:
capture_screen()
time.sleep(interval)
except KeyboardInterrupt:
print("\n抓拍已停止。")
if __name__ == "__main__":
main()
定时抓拍摄像头画面
如果需要从摄像头抓拍,使用 opencv-python。
安装依赖
pip install opencv-python schedule
脚本示例:每5秒抓拍一次摄像头
import cv2
import time
from datetime import datetime
import os
def capture_camera():
# 打开摄像头(0 = 默认摄像头)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("错误:无法打开摄像头")
return
# 读取一帧
ret, frame = cap.read()
if ret:
# 创建保存目录
save_dir = "camera_captures"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 生成带时间戳的文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{save_dir}/camera_{timestamp}.jpg"
# 保存图片
cv2.imwrite(filename, frame)
print(f"已保存: {filename}")
# 释放摄像头
cap.release()
def main():
interval = 5 # 抓拍间隔(秒)
print(f"开始定时抓拍摄像头,每 {interval} 秒一次...")
try:
while True:
capture_camera()
time.sleep(interval)
except KeyboardInterrupt:
print("\n抓拍已停止。")
if __name__ == "__main__":
main()
更精确的定时任务(使用 schedule 库)
如果你想在特定时间执行,或者需要更复杂的定时逻辑:
import pyautogui
from datetime import datetime
import os
import schedule
import time
def capture():
save_dir = "scheduled_screenshots"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{save_dir}/screenshot_{timestamp}.png"
screenshot = pyautogui.screenshot()
screenshot.save(filename)
print(f"已保存: {filename}")
# 设置定时任务
schedule.every(10).seconds.do(capture) # 每10秒
# schedule.every().minute.do(capture) # 每分钟
# schedule.every().hour.do(capture) # 每小时
# schedule.every().day.at("10:30").do(capture) # 每天10:30
print("定时任务已启动(按 Ctrl+C 停止)...")
while True:
schedule.run_pending()
time.sleep(1)
Windows 专用 - 使用 PowerShell + 任务计划程序
如果你不想写 Python,可以用系统自带功能:
PowerShell 脚本(screen_capture.ps1)
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$savePath = "C:\Screenshots"
if (!(Test-Path $savePath)) {
New-Item -ItemType Directory -Path $savePath
}
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$filename = "$savePath\screenshot_$timestamp.png"
$screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$bitmap = New-Object System.Drawing.Bitmap $screen.Width, $screen.Height
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($screen.X, $screen.Y, 0, 0, $screen.Size)
$bitmap.Save($filename)
$graphics.Dispose()
$bitmap.Dispose()
Write-Host "已保存: $filename"
然后用 Windows 任务计划程序设置定时执行此脚本。
使用建议
-
避免磁盘空间溢出:添加清理旧文件逻辑
# 保留最近100张图片 import glob files = sorted(glob.glob(f"{save_dir}/*.png")) if len(files) > 100: os.remove(files[0]) -
守护进程方式运行(Linux/macOS):
nohup python screenshot_timer.py &
-
Windows 后台运行:将脚本打包为
.exe(使用pyinstaller),或使用 Windows 服务。
需要哪种具体的功能调整(如只抓拍特定区域、抓拍后发送到邮箱等),可以告诉我,我可以帮你优化脚本。