icon-attention デザイン新しくしました。

icon-calendar 2019年9月2日

【RaspberryPi】Pythonを使ってUSBメモリを自動マウントする

未分類
mountpoint -q マウント先のパス; echo $?

そのパスがマウントされているかどうか調べられます。
マウントされていれば0、マウントされていなければ1です。

test -L /dev/disk/by-path/指定ポートのデバイス;echo $?

そのデバイスが存在するか調べられます。
存在していれば0、存在しなければ1です。

これを利用して以下のような関数を作りました。

def mount():
    mount_cmd = "mountpoint -q マウント先のパス; echo $?"
    mount_flag = int((subprocess.Popen(mount_cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]).decode("utf-8"))
    dev_cmd = "test -L /dev/disk/by-path/指定ポートのデバイス;echo $?"
    dev_flag = int((subprocess.Popen(dev_cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]).decode("utf-8"))

    # USB刺さってないのにマウントされている->アンマウント
    if mount_flag == 0 and dev_flag == 1:
        subprocess.call(["sudo", "umount", "マウント先のパス"])
        return False
    # USB刺さっているのにマウントされていない->マウント
    elif mount_flag == 1 and dev_flag == 0:
        subprocess.call(["sudo", "mount", "-w", "/dev/disk/by-path/指定ポートのデバイス", "マウント先のパス"])
        return True
    # USB刺さってないしマウントもされていない
    elif mount_flag == 1 and dev_flag == 1:
        return True
    # 正常
    else:
        return True