Search code examples
pythonusb

Eject device/USB using Python 3 (Windows 10)


I have a program that does backup to my USB, but to make it easier, I wanted to make it automatically eject when it's done.

(I replaced the actual paths with 'path' so I don't expose personal information.)

Code:

from shutil import copytree as ct
from shutil import copyfile as cf
from shutil import make_archive as arc
from shutil import rmtree as rm
from time import sleep as wait

f_drive = r'F:\BACKUP\stuff'
path_to_user = r'path'
another_path = r"path"
a_path = r'path'

def backup():
    ct(r'path', r'path')
    ct(r'path', r"F:\BACKUP\stuff\path")
    ct(r'path', r"path")
    ct(r'D:\path', r'path')

print("Starting backup...")
print("This process is automatic. This should not take any longer than 2 minutes...")
backup()
print()
print("Backup complete!")
print("Archiving folder...")
arc(r"F:\BACKUP", "zip", r'F:\BACKUP')
rm(r'F:\BACKUP')
print("Program will close in 10 seconds.")
wait(10)

Solution

  • yeah i figured it out myself. code:

    import os
    
    os.system('powershell $driveEject = New-Object -comObject Shell.Application; $driveEject.Namespace(17).ParseName("""F:""").InvokeVerb("""Eject""")')
    

    this took me alot of time

    finally...

    Btw it might only work on my pc lol