这是我到目前为止所拥有的:
import os.path as op
for d in map(chr, range(98, 123)): #drives b-z
if not op.isdir(d + ':/'): continue
问题是在Windows中弹出“No Disk”错误框:
maya.exe - 无磁盘:没有磁盘
驱动器。请将磁盘插入
驱动器 \Device\Harddisk1\DR1 [取消、重试、继续]
我无法捕获异常,因为它实际上并没有引发 Python 错误。
显然,这种情况仅发生在已分配字母但未插入驱动器的可移动驱动器上。
有没有一种方法可以解决这个问题,而无需专门告诉脚本要跳过哪些驱动器?
在我的场景中,我在学校实验室,驱动器号根据我所在的实验室计算机而变化。另外,我访问磁盘管理的安全权限为零。
Use the ctypes http://docs.python.org/library/ctypes.html包来访问GetLogicalDrives http://msdn.microsoft.com/en-us/library/aa364972%28v=vs.85%29.aspx功能。这不需要 pywin32 等外部库,因此它是可移植的,尽管使用起来有点笨拙。例如:
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
在Python 2.7和3.1中添加;如果您需要支持
def compress(data, selectors):
for d, s in zip(data, selectors):
if s:
yield d
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)