search
HomeBackend DevelopmentPython TutorialHow to use a Python script to automatically take photos, take screenshots and send email notifications after the computer wakes up

    背景

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

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

    所以我的需求是这样的:

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

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

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

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

    • 发送到我的邮箱.

    具体实现

    ️ 摄像头拍照

    概述:

    通过 opencv-python 包实现.

    具体的包名为: opencv-python

    依赖 numpy

    所以安装命令为:

    python -m pip install numpy
    python -m pip install opencv-python

    然后导入语句为: 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()  # 释放(关闭)摄像头

    屏幕截图

    概述:

    通过 pyautogui 包实现.

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

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

    写邮件

    概述:

    通过 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

    ️ 发邮件

    概述:

    通过 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('邮件发送成功!')

    台式机唤醒后触发 python 脚本

    Windows 脚本

    Windows bat 脚本如下:

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

    任务计划程序

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

    • 安全选项:

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

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

    • 触发器:

      • 发生事件时

      • 日志: 系统

      • 源: 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
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

    Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

    Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

    BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

    Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

    ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

    Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

    Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

    How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

    ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

    Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

    Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

    What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

    The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

    What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

    Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

    See all articles

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool