windows - In Python, how do I check if a drive exists w/o throwing an error for removable drives? -
here's have far:
import os.path op d in map(chr, range(98, 123)): #drives b-z if not op.isdir(d + ':/'): continue
the problem pops "no disk" error box in windows:
maya.exe - no disk: there no disk in drive. please insert disk drive \device\harddisk1\dr1 [cancel, try again, continue]
i can't catch exception because doesn't throw python error.
apparently, happens on removable drives there letter assigned, no drive inserted.
is there way around issue without telling script drives skip?
in scenario, i'm @ school labs drive letters change depending on lab computer i'm at. also, have 0 security privileges access disk management.
use ctypes
package access getlogicaldrives
function. not require external libraries such pywin32, it's portable, although little clunkier work with. example:
import ctypes import itertools import os import string import platform def get_available_drives(): if 'windows' not in platform.system(): return [] drive_bitmask = ctypes.cdll.kernel32.getlogicaldrives() return list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
itertools.compress
added in python 2.7 , 3.1; if need support <2.7 or <3.1, here's implementation of function:
def compress(data, selectors): d, s in zip(data, selectors): if s: yield d
Comments
Post a Comment