python中w_在Python中,如何检查驱动器是否存在w / o为可移动驱动器引发错误?

Here's what I have so far:

import os.path as op

for d in map(chr, range(98, 123)): #drives b-z

if not op.isdir(d + ':/'): continue

The problem is that it pops up a "No Disk" error box in Windows:

maya.exe - No Disk: There is no disk in

the drive. Please insert a disk into

drive \Device\Harddisk1\DR1 [Cancel, Try Again, Continue]

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.

解决方案

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 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值