#!/usr/bin/python3

import pyudev
import subprocess
import time

context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by('block')

def event_handler(action, device):
    if device.action == 'add' and device.properties['DEVTYPE'] == 'partition' and device.properties['ID_BUS'] == 'usb' and device.properties['DEVNAME'][-1] == '1':
        print('{0}, {1} connected'.format(device, device.properties['DEVNAME']))
        isMounted = False
        while (isMounted != True):
            time.sleep(0.5)
            cmd_str = "findmnt {} -n -o TARGET".format(device.properties['DEVNAME'])
            print(cmd_str)
            filePath = subprocess.run(cmd_str, shell=True, capture_output=True)
            print(filePath)
            if filePath.stdout != b'':
                isMounted = True
        dolphinProcess = subprocess.Popen(["dolphin", filePath.stdout])

observer = pyudev.MonitorObserver(monitor, event_handler)
observer.start()

observer.join()
