Python: Check if a /dev/disk device exists

I am trying to write python script to find out if a disk device exists in /dev, but it always yield False. Any other way to do this?

I tried

>>> import os.path
>>> os.path.isfile("/dev/bsd0")
False
>>> os.path.exists("/dev/bsd0")
False

$ ll /dev
...
brw-rw----   1 root disk    252,   0 Nov 12 21:28 bsd0
...

This was not rigorously tested, but seems to work:

import stat
import os.stat

def disk_exists(path):
     try:
             return stat.S_ISBLK(os.stat(path).st_mode)
     except:
             return False

Results:

disk_exists("/dev/bsd0")
True
disk_exists("/dev/bsd2")
False

Some unconventional situation is going on here.

os.path.isfile() will return True for regular files, for device files this will be False .

But as for os.path.exists() , documetation states that False may be returned if "permission is not granted to execute os.stat() ". FYI the implementation of os.path.exists is:

def exists(path):
    """Test whether a path exists.  Returns False for broken symbolic links"""
    try:
        os.stat(path)
    except OSError:
        return False
    return True

So, if os.stat is failing on you I don't see how ls could have succeeded ( ls AFAIK also calls stat() syscall). So, check what os.stat('/dev/bsd0') is raising to understand why you're not being able to detect the existence of this particular device file with os.path.exists , because using os.path.exists() is supposed to be a valid method to check for the existence of a block device file.

链接地址: http://www.djcxy.com/p/88800.html

上一篇: UIPageViewController和UIPageControl透明背景颜色

下一篇: Python:检查/ dev / disk设备是否存在