How to check whether a file of a given path is a block device in Python?

How to check and test whether a file of a given path is a block device in Python? This can be Linux specific.

You can use the os.stat() function to get the stat of the path. Then use the stat.S_ISBLK() function against the stat’s .st_mode to test whether it is a block device.

An example:

$ python
Python 2.7.5 (default, Apr 11 2018, 07:36:10) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, stat
>>> stat.S_ISBLK(os.stat("/dev/sda").st_mode)
True
>>> 
Leave a Reply

Your email address will not be published. Required fields are marked *