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

ele*_*tro 7 python

我正在尝试编写python脚本以查明/ dev中是否存在磁盘设备,但它总是产生False.还有其他办法吗?

我试过了

>>> 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
...
Run Code Online (Sandbox Code Playgroud)

pgr*_*en2 5

这没有经过严格测试,但似乎有效:

import stat
import os.stat

def disk_exists(path):
     try:
             return stat.S_ISBLK(os.stat(path).st_mode)
     except:
             return False
Run Code Online (Sandbox Code Playgroud)

结果:

disk_exists("/dev/bsd0")
True
disk_exists("/dev/bsd2")
False
Run Code Online (Sandbox Code Playgroud)

  • 我认为不需要“import os.stat”。(至少对于python3) (4认同)
  • 旧答案,但在最近版本中它应该是“import os”*而不是“os.stat”。 (3认同)

jvd*_*vdm 5

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
Run Code Online (Sandbox Code Playgroud)

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.