在Python中,如何检查驱动器是否存在w / o为可移动驱动器引发错误? [英] In Python, how do I check if a drive exists w/o throwing an error for removable drives?
问题描述
这是我到目前为止:
import os.path as op
for d in map(chr, range(98, 123)): #drives b-z
if not op.isdir(d + ':/'): continue
问题是它在Windows中弹出一个无磁盘错误框:
The problem is that it pops up a "No Disk" error box in Windows:
maya .exe - 无磁盘:
中没有磁盘。请将磁盘插入
驱动器\Device\Harddisk1\DR1 [取消,再次尝试,继续]
maya.exe - No Disk: There is no disk in the drive. Please insert a disk into drive \Device\Harddisk1\DR1 [Cancel, Try Again, Continue]
我不能捕获异常,因为它并没有引起Python错误。
I can't catch the exception because it doesn't actually throw a Python error.
显然,这只会发生在可分配的字母的可移动驱动器上,但没有驱动器插入。
Apparently, this only happens on removable drives where there is a letter assigned, but no drive inserted.
有没有一个方法来解决这个问题,没有具体说明脚本哪个驱动器跳过?
Is there a way to get around this issue without specifically telling the script which drives to skip?
在我的情况下,我在学校实验室,驱动器号改变取决于我在哪个实验室计算机。另外,我有零安全权限访问磁盘管理。
In my scenario, I'm at the school labs where the drive letters change depending on which lab computer I'm at. Also, I have zero security privileges to access disk management.
推荐答案
使用 ctypes
包以访问 GetLogicalDrives
功能。这不需要诸如pywin32这样的外部库,所以它是便携式的,尽管它有点小巧。例如:
Use the ctypes
package to access the GetLogicalDrives
function. This does not require external libraries such as pywin32, so it's portable, although it is a little clunkier to work with. For 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
添加在Python 2.7和3.1中;如果您需要支持< 2.7或< 3.1,这是该功能的实现:
itertools.compress
was added in Python 2.7 and 3.1; if you need to support <2.7 or <3.1, here's an implementation of that function:
def compress(data, selectors):
for d, s in zip(data, selectors):
if s:
yield d
这篇关于在Python中,如何检查驱动器是否存在w / o为可移动驱动器引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!