在Python中,如何检查驱动器是否存在而不会为可移动驱动器抛出错误?

时间:2010-11-15 20:04:24

标签: python windows error-handling path disk

这是我到目前为止所拥有的:

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 - 无磁盘:没有磁盘   驱动器。请插入一张磁盘   drive \ Device \ Harddisk1 \ DR1 [取消,再试一次,继续]

我无法捕获异常,因为它实际上没有抛出Python错误。

显然,这只发生在已分配字母但未插入驱动器的可移动驱动器上。

有没有办法解决这个问题,而没有具体告诉脚本哪些驱动器可以跳过?

在我的场景中,我在学校实验室,驱动器号码根据我所在的实验室计算机而变化。此外,我没有访问磁盘管理的安全权限。

7 个答案:

答案 0 :(得分:8)

使用ctypes包访问GetLogicalDrives功能。这不需要像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])))
在Python 2.7和3.1中添加了

itertools.compress;如果你需要支持< 2.7或< 3.1,这里是该函数的一个实现:

def compress(data, selectors):
    for d, s in zip(data, selectors):
        if s:
            yield d

答案 1 :(得分:4)

如果您有win32file模块,则可以致电GetLogicalDrives()

def does_drive_exist(letter):
    import win32file
    return (win32file.GetLogicalDrives() >> (ord(letter.upper()) - 65) & 1) != 0

答案 2 :(得分:3)

要禁用错误弹出,您需要使用pywin设置SEM_FAILCRITICALERRORS Windows错误标志:

old_mode = win32api.SetErrorMode(0)
SEM_FAILCRITICALERRORS = 1 # not provided by PyWin, last I checked
win32api.SetErrorMode(old_mode & 1)

这告诉Win32不要显示重试对话框;当错误发生时,它会立即返回给应用程序。

请注意,这就是Python调用假设要做的事情。原则上,Python应该为您设置此标志。不幸的是,由于Python可能嵌入在另一个程序中,它不能像这样改变进程范围的标志,并且Win32无法以仅影响Python而不影响其余代码的方式指定此标志。

答案 3 :(得分:3)

对于Python 2和3,这种方法适用于Windows和Linux:

import platform,os
def hasdrive(letter):
    return "Windows" in platform.system() and os.system("vol %s: 2>nul>nul" % (letter)) == 0

答案 4 :(得分:1)

<div class="radio-group">
  <fieldset>
    <legend>Gender</legend>
    <label for="genderMale" class="gender-label">
        Male
        </label>
    <input type="radio" name="gender" id="genderMale" value="male">

    <label for="genderFemale" class="gender-label">
        Female
        </label>
    <input type="radio" name="gender" id="genderFemale" value="female">
  </fieldset>
</div>

答案 5 :(得分:0)

只要稍微解析是可以接受的,这是一种方法,无需安装win32api并且不迭代所有可能的驱动器号。

def upload_csv(filename, file_path)
  file = Tempfile.new(filename, Rails.root.join('tmp'), encoding: "ISO8859-1:utf-8").tap do |f|
   open(file_path).rewind
   f.write(open(file_path).read)
   f.close
  end

  CSV.foreach(file, headers: true, encoding: "ISO8859-1:utf-8")do |row|
   #do stuff to rows
  end
end

您还可以解析特定的驱动器类型,例如“网络连接”,以通过添加from subprocess import check_output def getDriveLetters(): args = [ 'wmic', 'logicaldisk', 'get', 'caption,description,providername', '/format:csv' ] output = check_output(args) results = list() for line in output.split('\n'): if line: lineSplit = line.split(',') if len(lineSplit) == 4 and lineSplit[1][1] == ':': results.append(lineSplit[1][0]) return results 来获取所有网络安装的驱动器号的列表。

或者,您可以返回一个字典,而不是返回列表,其中键是驱动器号,值是unc路径(and lineSplit[2] == 'Network Connection')。或者您要从lineSplit[3]提取的任何其他信息。要查看更多选项:wmic

答案 6 :(得分:0)

import os 
def IsDriveExists(drive):
    return os.path.exists(drive + ':\\')
    
print(IsDriveExists('c')) 
print(IsDriveExists('d'))
print(IsDriveExists('e'))
print(IsDriveExists('x'))
print(IsDriveExists('v'))

这适用于任何操作系统