Last active
May 25, 2016 02:39
-
-
Save xiongyihui/986b8f71a55e4979a9724c4635bedaf6 to your computer and use it in GitHub Desktop.
drive detection on linux and windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python2 | |
# Using dbus to detect new drive on linux | |
# Install dependences: sudo apt-get install python-dbus python-gobject | |
import dbus | |
import glib | |
from dbus.mainloop.glib import DBusGMainLoop | |
def handle_new_drive(sender, mount_id, data): | |
mounted_path = data[5][7:] | |
print('New drive is mounted at %s' % mounted_path) | |
DBusGMainLoop(set_as_default=True) | |
bus = dbus.SessionBus() | |
bus.add_signal_receiver(signal_name="MountAdded", | |
dbus_interface="org.gtk.Private.RemoteVolumeMonitor", | |
path="/org/gtk/Private/RemoteVolumeMonitor", | |
bus_name=None, | |
handler_function=handle_new_drive) | |
try: | |
glib.threads_init() | |
glib.MainLoop().run() | |
except KeyboardInterrupt: | |
print('Quit') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# building on above and http://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python | |
import string | |
from ctypes import windll | |
import time | |
import os | |
import signal | |
def get_drives(): | |
drives = [] | |
bitmask = windll.kernel32.GetLogicalDrives() | |
for letter in string.uppercase: | |
if bitmask & 1: | |
drives.append(letter) | |
bitmask >>= 1 | |
return drives | |
if __name__ == '__main__': | |
quit = False | |
def handle_signal(signal, frame): | |
quit = True | |
print('quit') | |
signal.signal(signal.SIGINT, handle_signal) | |
last = set(get_drives()) | |
print('Detect drive change') | |
print('Find drive(s): %s' % last) | |
while not quit: | |
try: | |
current = set(get_drives()) | |
if len(current) > len(last): | |
drives = current - last | |
print('Find drive(s): %s' % current) | |
print('New drive(s) available: %s' % drives) | |
elif len(current) < len(last): | |
drives = last - current | |
print('Find drive(s): %s' % current) | |
print('Drive(s) %s removed' % drives) | |
last = current | |
time.sleep(0.1) | |
except: | |
break | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment