Table of Contents
背景
具体实现
️ 摄像头拍照
屏幕截图
写邮件
MIMEMultipart 类型
️ 发邮件
台式机唤醒后触发 python 脚本
Windows 脚本
任务计划程序
Home Backend Development Python Tutorial How to use a Python script to automatically take photos, take screenshots and send email notifications after the computer wakes up

How to use a Python script to automatically take photos, take screenshots and send email notifications after the computer wakes up

Apr 19, 2023 pm 11:07 PM
python computer

    背景

    背景是这样的, 我的家里台式机常年 休眠, 并配置了 Wake On Lan (WOL) 方便远程唤醒并使用.

    但是我发现, 偶尔台式机会被其他情况唤醒, 这时候我并不知道, 结果白白运行了好几天, 浪费了很多电.

    所以我的需求是这样的:

    电脑唤醒后(可能是开机, 有可能是从休眠状态唤醒), 自动做如下几件事:

    • 摄像头拍照(判断是不是有人在使用)

    • 屏幕截图(判断是不是有人在使用)

    • 生成一封邮件, 告诉我「电脑已启动」并附上拍照和截图;

    • 发送到我的邮箱.

    具体实现

    ️ 摄像头拍照

    概述:

    通过 opencv-python 包实现.

    具体的包名为: opencv-python

    依赖 numpy

    所以安装命令为:

    python -m pip install numpy
    python -m pip install opencv-python
    Copy after login

    然后导入语句为: import cv2

    源码如下:

    # 打开摄像头并拍照
    cap = cv2.VideoCapture(0)  # 0 表示打开 PC 的内置摄像头(若参数是视频文件路径则打开视频)
    #  按帧读取图片或视频
    # ret,frame 是 cap.read() 方法的两个返回值。
    # 其中 ret 是布尔值,如果读取帧是正确的则返回 True,如果文件读取到结尾,它的返回值就为 False。
    # frame 就是每一帧的图像,是个三维矩阵。
    ret, frame = cap.read()  # 按帧读取图片
    cv2.imwrite('p1.jpg', frame)  # 保存图像
    cap.release()  # 释放(关闭)摄像头
    Copy after login

    屏幕截图

    概述:

    通过 pyautogui 包实现.

    pyautogui 是比较简单的,但是不能指定获取程序的窗口,因此窗口也不能遮挡,不过可以指定截屏的位置,0.04s 一张截图,比 PyQt 稍慢一点,但也很快了。

    import pyautogui
    import cv2
    
    
    # 截图
    screen_shot = pyautogui.screenshot()
    screen_shot.save('screenshot.png')
    Copy after login

    写邮件

    概述:

    通过 email 包实现.

    MIMEMultipart 类型

    MIME 邮件中各种不同类型的内容是分段存储的,各个段的排列方式、位置信息都通过 Content-Type 域的 multipart 类型来定义。 multipart 类型主要有三种子类型:

    • mixed : 附件

    • alternative : 纯文本和超文本内容

    • related :内嵌资源. 比如:在发送 html 格式的邮件内容时,可能使用图像作为 html 的背景,html 文本会被存储在 alternative 段中,而作为背景的图像则会存储在 related 类型定义的段中

    具体源码如下:

    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    
    
    sender = 'admin@example.com'  # 发件人
    receivers = 'admin@example.com'  # 收件人
    pw = 'p@ssw0rd'  # 三方客户端登录邮箱授权码
    subject = '电脑已启动拍照并发送'  # 邮件主题
    text = '您好,您的电脑已开机,并拍摄了如下照片:'  # 邮件正文
    
    msg = MIMEMultipart('mixed')  # 定义含有附件类型的邮件
    msg['Subject'] = subject  # 邮件主题
    msg['From'] = sender  # 发件人
    msg['To'] = receivers  # 收件人
    # MIMEText三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
    # 构造一个文本邮件对象, plain 原格式输出; html html格式输出
    text = MIMEText(text, 'plain', 'utf-8')
    msg.attach(text)  # 将文本内容添加到邮件中
    
    for i in ('p1.jpg', 'screenshot.png'):
        sendImg = open(i, 'rb').read()  # 读取刚才的图片
        img = MIMEImage(sendImg)  # 构造一个图片附件对象
        # 指定下载的文件类型为:附件, 并加上文件名
        img['Content-Disposition'] = 'attachment; filename={}'.format(i)
        msg.attach(img)  # 将附件添加到邮件中
    
    msg_tsr = msg.as_string()  # 将msg对象变为str
    Copy after login

    ️ 发邮件

    概述:

    通过 smtplib 包实现.

    源码如下:

    import smtplib
    
    
    # 发送邮件
    try:
        smtp = smtplib.SMTP()  # 定义一个SMTP(传输协议)对象
        smtp.connect('smtp.example.com', 25)  # 连接到邮件发送服务器,默认25端口
        smtp.login(sender, pw)  # 使用发件人邮件及授权码登陆
        smtp.sendmail(sender, receivers, msg_tsr)  # 发送邮件
        smtp.quit()  # 关闭邮箱,退出登陆
    except Exception as e:
        print('\033[31;1m出错了:%s\033[0m' % (e))
    else:
        print('邮件发送成功!')
    Copy after login

    台式机唤醒后触发 python 脚本

    Windows 脚本

    Windows bat 脚本如下:

    @echo off
    timeout /T 15 /NOBREAK # sleep 15s
    cd /d D:\scripts\auto_send_email
    python auto_email.py  # 执行py文件
    Copy after login

    任务计划程序

    进入 计算机管理 -> 系统工具 -> 任务计划程序. 添加如下任务计划:

    • 安全选项:

      • 勾选: 不管用户是否登录都要运行

      • 勾选: 使用最高权限运行

    • 触发器:

      • 发生事件时

      • 日志: 系统

      • 源: Power-Troubleshooter

      • 事件 ID: 1

    • 操作: 启动程序: D:\scripts\auto_email.bat

    The above is the detailed content of How to use a Python script to automatically take photos, take screenshots and send email notifications after the computer wakes up. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    What is the reason why PS keeps showing loading? What is the reason why PS keeps showing loading? Apr 06, 2025 pm 06:39 PM

    PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

    How to solve the problem of loading when PS is started? How to solve the problem of loading when PS is started? Apr 06, 2025 pm 06:36 PM

    A PS stuck on "Loading" when booting can be caused by various reasons: Disable corrupt or conflicting plugins. Delete or rename a corrupted configuration file. Close unnecessary programs or upgrade memory to avoid insufficient memory. Upgrade to a solid-state drive to speed up hard drive reading. Reinstalling PS to repair corrupt system files or installation package issues. View error information during the startup process of error log analysis.

    How to speed up the loading speed of PS? How to speed up the loading speed of PS? Apr 06, 2025 pm 06:27 PM

    Solving the problem of slow Photoshop startup requires a multi-pronged approach, including: upgrading hardware (memory, solid-state drive, CPU); uninstalling outdated or incompatible plug-ins; cleaning up system garbage and excessive background programs regularly; closing irrelevant programs with caution; avoiding opening a large number of files during startup.

    Is slow PS loading related to computer configuration? Is slow PS loading related to computer configuration? Apr 06, 2025 pm 06:24 PM

    The reason for slow PS loading is the combined impact of hardware (CPU, memory, hard disk, graphics card) and software (system, background program). Solutions include: upgrading hardware (especially replacing solid-state drives), optimizing software (cleaning up system garbage, updating drivers, checking PS settings), and processing PS files. Regular computer maintenance can also help improve PS running speed.

    How to solve the problem of loading when PS is always showing that it is loading? How to solve the problem of loading when PS is always showing that it is loading? Apr 06, 2025 pm 06:30 PM

    PS card is "Loading"? Solutions include: checking the computer configuration (memory, hard disk, processor), cleaning hard disk fragmentation, updating the graphics card driver, adjusting PS settings, reinstalling PS, and developing good programming habits.

    How to solve the problem of loading when the PS opens the file? How to solve the problem of loading when the PS opens the file? Apr 06, 2025 pm 06:33 PM

    "Loading" stuttering occurs when opening a file on PS. The reasons may include: too large or corrupted file, insufficient memory, slow hard disk speed, graphics card driver problems, PS version or plug-in conflicts. The solutions are: check file size and integrity, increase memory, upgrade hard disk, update graphics card driver, uninstall or disable suspicious plug-ins, and reinstall PS. This problem can be effectively solved by gradually checking and making good use of PS performance settings and developing good file management habits.

    How to set color mode for export PDF on PS How to set color mode for export PDF on PS Apr 06, 2025 pm 05:09 PM

    The secret to export PDFs with accurate colors: choose color mode according to the purpose: RGB for network display, CMYK for professional printing. Check Embed Profiles when exporting to maintain color consistency. Adjust compression settings to balance image quality and file size. For PDFs for networks, use RGB mode; for PDFs for printing, use CMYK mode.

    Can PDF export be exported in batches by PS? Can PDF export be exported in batches by PS? Apr 06, 2025 pm 04:54 PM

    There are three ways to export PDFs in batches on PS: use PS action functions: record and open files and export PDF actions, and execute actions in a loop. With the help of third-party software: use file management software or automation tools to specify the input and output folders and set the file name format. Use scripts: Write scripts to customize batch export logic, but programming knowledge is required.

    See all articles