我正在尝试编写 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
...
最佳答案
这里发生了一些非常规情况。
os.path.isfile()
对于常规文件,将返回 True
,对于设备文件,这将是
错误
。
但是至于
os.path.exists()
,
documetation 声明 False
如果“permission is not
授权执行 os.stat()
”。仅供引用
os.path.exists
是:
def exists(path):
"""Test whether a path exists. Returns False for broken symbolic links"""
try:
os.stat(path)
except OSError:
return False
return True
所以,如果 os.stat
对你失败了,我不明白 ls
怎么可能有
成功(ls
AFAIK 也调用 stat() 系统调用)。所以,检查什么
os.stat('/dev/bsd0')
提高理解你为什么不
能够检测到这个特定设备文件的存在
os.path.exists
,因为应该使用 os.path.exists()
是检查 block 设备文件是否存在的有效方法。
关于Python:检查/dev/disk 设备是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33685078/