How to test whether a file exists and is a block special file in Python on Linux?

Bash has a -b test to test whether a file exists and is a block special file.

-b file
      True if file exists and is a block special file.

How to do this in Python?

Python’s stat module provides the similar functions for the C standard APIs and macros underlining such as stat() and S_ISBLK().

Here is one Python function and example usage:

import os
import stat

def isblockdevice(path):
  return os.path.exists(path) and stat.S_ISBLK(os.stat(path).st_mode)

if __name__ == "__main__":
  for p in ["/dev/sda1", "/dev/sdz", "/tmp/a"]:
    print("isblockdevice({}): {}".format(p, isblockdevice(p)))

An example execution result is as follows.

$ python3 ./main.py 
isblockdevice(/dev/sda1): True
isblockdevice(/dev/sdz): False
isblockdevice(/tmp/a): False