pythonsubprocessusb-drivedisk-partitioning

How could I self-eject my USB-Drive using the python module 'sub-process'


I have a script for my USB that i need to use on multiple devices, and i want it to auto-eject, and using this method, as long as it has elevated privileges it runs, no issues, no errors, but i check the file explorer and the USB is still in there:

            p = Popen(["diskpart"], stdin=PIPE)
            p.stdin.write(b"select disk " + drive_letter.encode() + b"\n")
            p.stdin.write(b"remove all dismount\n")
            p.stdin.write(b"exit\n")
            print(f"Successfully ejected drive {successful_drive_path}.")

this is all using sub-process module for python, I know I don't need to do this, but I still want to. I suspect it's due to the code being ran in the usb, so maybe i could, with the bat file i use to run and handle everything, run the ejection code using a self-deleting script in the main disk. Idk just ideas.


Solution

  • I believe the issue is that you are call it as a disk, not a volume. This code will fix your issue, but only works with elevated privileges:

    
    def eject_drive(drive_letter=input():
        try:
            p = subprocess.Popen(["diskpart"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    
            # Prepare the diskpart script
            commands = f"""
            select volume {drive_letter}
            remove all dismount
            exit
            """
    
            # Send the commands
            stdout, stderr = p.communicate(commands)
    
            if p.returncode == 0:
                print(f"Successfully ejected drive {drive_letter}.")
            else:
                print(f"Failed to eject drive {drive_letter}. Error: {stderr}")
        except Exception as e:
            print(f"Exception occurred: {e}")