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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With