'Python Script To Continually Run (Better)

The below script is a working prototype of a script that runs on a rasberry pi and its job is to grab files from a specified folder on a flashdrive when plugged in. After that point it emails the files as attachments. Now, everything works perfect, but not logically in the way I want. I have a really janky while True: loop with janky sleep timers to kind delay some things. Ideally I need help developing a way for all of this to happen only ONCE per usb drive plug in. Then it would go into "Idle mode" waiting for the next stick. As of now, without my added sleep timers, It would just continually run over and over. I've been stuck trying to logically figure out a way to make it work how I would like.

Thanks in advance!

import smtplib, ssl
import shutil
import os
from time import sleep
from distutils import dir_util
from psutil import disk_partitions
from datetime import datetime
from datetime import date
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

now = datetime.now()
current_time = now.strftime("%H:%M:%S")

today = date.today()
day = today.strftime("%B %d, %Y")

def CopyFilesFromSD():
    try:
        dir_util.copy_tree(driver+'/REDACTED', '/home/pi/Desktop/Transferred Files')
        print("Files Succesfully Copied")
        if 'rw' in opts:
            with open(driver+'/Transfer_Log_REDACTED.txt', 'a', encoding = 'utf-8') as fp:
                fp.write("\nFiles Succesfully Transferred to REDACTED on " + day + " at " + current_time)
    except:
        print("Device unmounted during transfer process!")
    sleep(10)
    
def SendFiles():
    dir_path = "/home/pi/Desktop/Transferred Files/"
    files = os.listdir(dir_path)

    msg = MIMEMultipart()
    msg['To'] = "REDACTED"
    msg['From'] = "REDACTED"
    msg['Subject'] = "REDACTED"
    password = "REDACTED"

    body = MIMEText('Test.', 'html', 'utf-8')
    msg.attach(body)

    for f in files:
        file_path = os.path.join(dir_path, f)
        attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
        attachment.add_header('Content-Disposition','attachment', filename=f)
        msg.attach(attachment)

    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("REDACTED", 465, context=context) as server:
        server.login(msg['From'], password)
        server.sendmail(
            msg['From'], msg['To'], msg.as_string()
        )
    shutil.rmtree(dir_path, ignore_errors = False)
    sleep(5)

while True:
    sleep(1)
    for item in disk_partitions():
        if 'nodev' in item.opts:
            driver, opts = item.mountpoint, item.opts
            CopyFilesFromSD()
            SendFiles()
            break
        else:
            continue
        break


Solution 1:[1]

Answered by iScripters in the comment section:

https://betterprogramming.pub/how-to-run-a-python-script-on-insertion-of-a-usb-device-2e86d38dcdb

This will allow for the python script to only be ran when USB insertion is detected. No need to have a constant running program looking for drives.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DanDaMan