ドライブを一覧表示するコマンド

コマンドプロンプト上でLaTeXでPDFを作成し、それをUSBメモリにコピーする事が頻繁にあるのですが、USBメモリのパスはどれだったっけマイコンピュータを開くのが面倒くさい!というわけで、pywin32で作ってみました。当然、Windowsでしか動きません

#!python3
#encoding: shift-jis

#drives.py

import sys
from win32api import (
    GetLogicalDriveStrings,
    GetVolumeInformation,
)
from win32file import (
    GetDiskFreeSpaceEx,
    GetDriveType,
)
from win32con import (
    DRIVE_UNKNOWN,
    DRIVE_NO_ROOT_DIR, 
    DRIVE_REMOVABLE,
    DRIVE_FIXED,
    DRIVE_REMOTE,
    DRIVE_CDROM,
    DRIVE_RAMDISK,
)
import pywintypes

from os.path import normpath, normcase
import string

def print_table(table, *, file=None):
    if file is None:
        file = sys.stdout
    
    max_col_count = max(len(row) for row in table)
    
    def width(astr):
        return sum(len(c.encode("mbcs")) for c in astr)
    
    col_widths = [
        max(width(row[col_index]) for row in table)
            for col_index in range(max_col_count)]
    
    lines = 
    for row in table:
        for col_index, value in enumerate(row):
            value = value.encode("mbcs").ljust(col_widths[col_index]).decode("mbcs")
            print(value, file=file, end=" ")
        print(file=file)
    


def byte_size_to_string(byte_size):
    for i, unit_name in enumerate("B KB MB GB TB".split()):
        unit = 2 ** (i * 10)
        if byte_size < unit * 2**10:
            size_in_unit = byte_size // unit
            return "{}{}".format(size_in_unit, unit_name)
    else:
        peta = 2 ** 50
        return "{}PB".format(byte_size // peta)
    


def GetDriveTypeString(root_path):
    t = GetDriveType(root_path)
    if t == DRIVE_NO_ROOT_DIR:
        raise pywintypes.error("{} is not a drive root path".format(repr(root_path)))
    
    return {
        DRIVE_REMOVABLE: "リムーバブル",
        DRIVE_FIXED: "固定",
        DRIVE_REMOTE: "リモート",
        DRIVE_CDROM: "CD-ROM",
        DRIVE_RAMDISK: "RAMディスク",
    }.get(t, "不明")


def main():
    root_paths = GetLogicalDriveStrings().split("\x00")[:-1]
    root_paths = [p.upper() for p in root_paths]
    root_paths.sort()
    
    table = 
    for root_path in root_paths:
        try:
            drive_type = GetDriveTypeString(root_path)
        except pywintypes.error:
            continue
        
        try:
            volume_label, _, _, _, _ = GetVolumeInformation(root_path)
        except pywintypes.error:
            volume_label = "不明"
        
        try:
            available_size, total_size, _ = GetDiskFreeSpaceEx(root_path)
        except pywintypes.error:
            size = "不明"
        else:
            size = "{}/{}".format(
                byte_size_to_string(available_size),
                byte_size_to_string(total_size))
        
        table.append([
            "({})".format(root_path),
            volume_label,
            size,
            drive_type,
        ])
    
    print_table(table)

if "__main__" == __name__:
    main()

そもそも、標準でこういうコマンドがあるような気がしてなりません。